[
  {
    "name": "Add-DbaAgDatabase",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Add",
    "popular": true,
    "url": "/Add-DbaAgDatabase",
    "popularityRank": 15,
    "synopsis": "Adds databases to an Availability Group with automated backup, restore, and synchronization handling.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Add-DbaAgDatabase View Source Chrissy LeMaire (@cl), netnerds.net , Andreas Jordan (@JordanOrdix), ordix.de Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Adds databases to an Availability Group with automated backup, restore, and synchronization handling. 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. The command executes a comprehensive five-step process for each database: Step 1: Setting seeding mode if needed. 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. The seeding mode will not be changed back but stay in this mode. If the seeding mode is changed to Automatic, the necessary rights to create databases will be granted. Step 2: Running backup and restore if needed. Action is only taken for replicas with a desired seeding mode of Manual and where the database does not yet exist. If -UseLastBackup is used, the restore will be performed based on the backup history of the database. 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. Step 3: Add the database to the Availability Group on the primary replica. This step is skipped, if the database is already part of the Availability Group. Step 4: Add the database to the Availability Group on the secondary replicas. This step is skipped for those replicas, where the database is already joined to the Availability Group. Step 5: Wait for the database to finish joining the Availability Group on the secondary replicas. Use Test-DbaAvailabilityGroup with -AddDatabase to test if all prerequisites are met before running this command. For 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. Syntax Add-DbaAgDatabase [-SqlInstance] [-SqlCredential ] -AvailabilityGroup -Database [-Secondary ] [-SecondarySqlCredential ] [-SeedingMode ] [-SharedPath ] [-UseLastBackup] [-AdvancedBackupParams ] [-NoWait] [-SkipReuseSourceFolderStructure] [-MasterKeySecurePassword ] [-EnableException] [-WhatIf] [-Confirm] [ ] Add-DbaAgDatabase [-AvailabilityGroup] [-Secondary ] [-SecondarySqlCredential ] -InputObject [-SeedingMode ] [-SharedPath ] [-UseLastBackup] [-AdvancedBackupParams ] [-NoWait] [-SkipReuseSourceFolderStructure] [-MasterKeySecurePassword ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Adds db1 and db2 to ag1 on sql2017a PS C:\\> Add-DbaAgDatabase -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2 -Confirm Adds db1 and db2 to ag1 on sql2017a. Prompts for confirmation. Example 2: Adds selected databases from sql2017a to ag1 PS C:\\> Get-DbaDatabase -SqlInstance sql2017a | Out-GridView -Passthru | Add-DbaAgDatabase -AvailabilityGroup ag1 Example 3: Adds SharePoint databases as found in SharePoint_Config on sqlcluster to ag1 on sqlcluster PS C:\\> Get-DbaDbSharePoint -SqlInstance sqlcluster | Add-DbaAgDatabase -AvailabilityGroup SharePoint Example 4: Adds SharePoint databases as found in SharePoint_Config_2019 on sqlcluster to ag1 on sqlcluster PS C:\\> Get-DbaDbSharePoint -SqlInstance sqlcluster -ConfigDatabase SharePoint_Config_2019 | Add-DbaAgDatabase -AvailabilityGroup SharePoint Example 5: Adds db1 to ag1 on sql2017a and sql2017b PS C:\\> $adv_param = @{ >> CompressBackup = $true >> FileCount = 3 >> } PS C:\\> $splat = @{ >> SqlInstance = 'sql2017a' >> AvailabilityGroup = 'ag1' >> Database = 'db1' >> Secondary = 'sql2017b' >> SeedingMode = 'Manual' >> SharedPath = '\\\\FS\\Backup' >> } PS C:\\> Add-DbaAgDatabase @splat -AdvancedBackupParams $adv_param Adds db1 to ag1 on sql2017a and sql2017b. Uses compression and three files while taking the backups. Example 6: Adds db1 to ag1 on sql2017a and returns immediately without waiting for seeding to complete on secondary... PS C:\\> Add-DbaAgDatabase -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1 -NoWait Adds db1 to ag1 on sql2017a and returns immediately without waiting for seeding to complete on secondary replicas. Seeding will continue in the background. Required Parameters -SqlInstance The primary replica of the Availability Group. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies the target Availability Group name where databases will be added. The AG must already exist and be configured. Use this to identify which existing Availability Group should receive the new database members. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Database Specifies which databases to add to the Availability Group. Accepts single database names, arrays, or wildcard patterns. Use this when you need to add specific databases rather than piping database objects from Get-DbaDatabase. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from pipeline input, typically from Get-DbaDatabase or Get-DbaDbSharePoint. Use this for workflow scenarios where you want to filter databases first, then pipe the results directly into the AG addition process. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Secondary Specifies secondary replica instances to target for database addition. Auto-discovered if not specified. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecondarySqlCredential Authentication credentials for connecting to secondary replica instances when they require different credentials than the primary. Use this when secondary replicas are in different domains, use SQL authentication, or require service accounts with specific permissions for backup/restore operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SeedingMode Controls how database data is transferred to secondary replicas during AG addition. Valid values are 'Automatic' or 'Manual'. Automatic seeding transfers data directly over the network without requiring backup/restore operations, but needs sufficient network bandwidth and proper endpoint configuration. Manual seeding uses traditional backup/restore through shared storage, giving you more control over timing and storage location but requiring accessible file shares. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Automatic,Manual | -SharedPath Specifies the UNC network path where backups are stored during manual seeding operations. Required when using Manual seeding mode. All 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you have recent backups available and want to avoid taking additional backups, reducing backup storage requirements and time. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AdvancedBackupParams Passes additional parameters to Backup-DbaDatabase as a hashtable when creating backups during manual seeding. Use this to control backup compression, file count, or other backup-specific settings like @{CompressBackup=$true; FileCount=4} for faster backup operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoWait Skips waiting for the database seeding and synchronization to complete on secondary replicas (Step 5). The underlying SQL command ALTER AVAILABILITY GROUP ... ADD DATABASE is immediate and does not wait for seeding to finish. Use this when you want the command to return immediately after adding the database to the AG, allowing seeding to continue in the background. This is particularly useful in deployments where seeding can take a long time and you want to start using the environment before synchronization completes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SkipReuseSourceFolderStructure Prevents restores from using the source server's folder structure when restoring databases to secondary replicas. When enabled, Restore-DbaDatabase uses the replica's default data and log directories instead of attempting to replicate the primary's folder structure. This is automatically set to true when the primary and replica servers run on different operating system platforms (e.g., Windows primary with Linux replica). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MasterKeySecurePassword Password for creating or opening the database master key on secondary replicas when adding TDE-encrypted databases. When a database is protected by Transparent Data Encryption (TDE), the certificate used to protect the Database Encryption Key must exist on every secondary replica. Providing this parameter together with SharedPath allows the command to automatically copy the TDE certificate from the primary to each secondary replica. If the secondary already has a master key, this password is used to create one if it is missing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityDatabase Returns 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 each secondary. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) AvailabilityGroup: Name of the availability group LocalReplicaRole: Role of this replica (Primary or Secondary) Name: Database name SynchronizationState: Current synchronization state (NotSynchronizing, Synchronizing, Synchronized, Reverting, Initializing) IsFailoverReady: Boolean indicating if the database is ready for failover IsJoined: Boolean indicating if the database has joined the availability group IsSuspended: Boolean indicating if data movement is suspended Additional properties available (from SMO AvailabilityDatabase object): DatabaseGuid: Unique identifier for the database EstimatedDataLoss: Estimated data loss in seconds EstimatedRecoveryTime: Estimated recovery time in seconds FileStreamSendRate: Rate of FILESTREAM data being sent (bytes/sec) GroupDatabaseId: Unique identifier for the database within the AG ID: Internal object ID IsAvailabilityDatabaseSuspended: Boolean indicating suspension state IsDatabaseDiskHealthy: Boolean indicating if database disk health is good IsDatabaseJoined: Boolean indicating database join state IsInstanceDiskHealthy: Boolean indicating if instance disk health is good IsInstanceHealthy: Boolean indicating overall instance health IsPendingSecondarySuspend: Boolean indicating if secondary suspend is pending LastCommitLsn: Last commit log sequence number LastCommitTime: Timestamp of last committed transaction LastHardenedLsn: Last hardened log sequence number LastHardenedTime: Timestamp when last LSN was hardened LastReceivedLsn: Last received log sequence number LastReceivedTime: Timestamp when last LSN was received LastRedoneLsn: Last redone log sequence number LastRedoneTime: Timestamp when last LSN was redone LastSentLsn: Last sent log sequence number LastSentTime: Timestamp when last LSN was sent LogSendQueue: Size of log send queue in KB LogSendRate: Rate of log sending (bytes/sec) LowWaterMarkForGhostCleanup: Low water mark LSN for ghost cleanup Parent: Reference to parent AvailabilityGroup SMO object RecoveryLsn: Recovery log sequence number RedoQueue: Size of redo queue in KB RedoRate: Rate of redo operations (bytes/sec) SecondaryLagSeconds: Lag in seconds for secondary replica State: SMO object state (Existing, Creating, Pending, etc.) SuspendReason: Reason for suspension if database is suspended Urn: Uniform Resource Name for the SMO object UserAccess: User access state All properties from the base SMO object are accessible even though only default properties are displayed without using Select-Object . &nbsp;"
  },
  {
    "name": "Add-DbaAgListener",
    "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't have client connectivity configured yet. Without a listener, applications must connect directly to replica server names, which breaks during failover scenarios.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaAgListener",
    "popularityRank": 72,
    "synopsis": "Creates a network listener endpoint for an Availability Group to provide client connectivity",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Add-DbaAgListener View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a network listener endpoint for an Availability Group to provide client connectivity 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. This 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. Use this when setting up new Availability Groups or when adding listeners to existing groups that don't have client connectivity configured yet. Without a listener, applications must connect directly to replica server names, which breaks during failover scenarios. Syntax Add-DbaAgListener [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Name] ] [[-IPAddress] ] [[-SubnetIP] ] [[-SubnetMask] ] [[-Port] ] [-Dhcp] [-Passthru] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a listener on 10.0.20.20 port 1433 for the SharePoint availability group on sql2017 PS C:\\> Add-DbaAgListener -SqlInstance sql2017 -AvailabilityGroup SharePoint -IPAddress 10.0.20.20 Example 2: Creates a listener on port 1433 with a dynamic IP for the group1 availability group on sql2017 PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2017 -AvailabilityGroup availabilitygroup1 | Add-DbaAgListener -Dhcp Example 3: Creates a multi-subnet listener with 10.0.20.20 and 10.1.77.77, on two /22 subnets, on port 1433 for the... PS C:\\> Add-DbaAgListener -SqlInstance sql2017 -AvailabilityGroup SharePoint -IPAddress 10.0.20.20,10.1.77.77 -SubnetMask 255.255.252.0 Creates 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. Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential) | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Required when using the SqlInstance parameter to identify which AG on the server needs client connectivity. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies a custom network name for the listener that clients will use to connect. Defaults to the Availability Group name if not specified. Use this when you need a different DNS name than your AG name, such as for application connection strings that can't be changed. Cannot be used when processing multiple Availability Groups in a single operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this for multi-subnet deployments or when DHCP is not available in your network environment. Cannot be combined with the Dhcp parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SubnetIP Specifies the network subnet addresses where the listener IPs will be configured. Auto-calculated from IPAddress and SubnetMask if not provided. Use this when you need explicit control over subnet configuration or when auto-calculation produces incorrect results. Must match the number of IP addresses specified, or provide a single subnet to apply to all IPs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SubnetMask Defines the subnet mask for each listener IP address, controlling the network range. Defaults to 255.255.255.0 (/24). Use this when your network uses non-standard subnet sizes or when configuring multi-subnet listeners with different mask requirements. Must match the number of IP addresses, or provide a single mask to apply to all IPs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 255.255.255.0 | -Port Specifies the TCP port number that clients will use to connect to the listener. Defaults to 1433. Change this when your environment requires non-standard SQL Server ports due to security policies or port conflicts with other services. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Cannot be used with IPAddress parameter and requires single-subnet AG configurations only. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Passthru Returns the listener object without creating it on the server, allowing for additional configuration before calling Create(). Use this when you need to set advanced properties not exposed by this function's parameters before committing the listener to SQL Server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts Availability Group objects from Get-DbaAvailabilityGroup through the pipeline, eliminating the need to specify SqlInstance and AvailabilityGroup parameters. Use this approach when working with multiple AGs or when you need to filter AGs before creating listeners. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityGroupListener Returns 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 additional configuration. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance hosting the Availability Group InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) AvailabilityGroup: Name of the Availability Group that owns this listener Name: Network name of the listener that clients use for connections PortNumber: TCP port number for client connections (default 1433) ClusterIPConfiguration: WSFC cluster IP resource configuration details Additional properties available (from SMO AvailabilityGroupListener object): AvailabilityGroupListenerIPAddresses: Collection of IP address configurations for this listener (one per subnet in multi-subnet scenarios) Urn: Unique resource name for programmatic identification State: SMO object state (Existing, Creating, Pending, etc.) Properties: Collection of object properties and their values All properties from the base SMO AvailabilityGroupListener object are accessible via Select-Object * even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Add-DbaAgReplica",
    "description": "Adds a replica to an availability group on one or more SQL Server instances.\n\nAutomatically creates database mirroring endpoints if required.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaAgReplica",
    "popularityRank": 74,
    "synopsis": "Adds a replica to an availability group on one or more SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Add-DbaAgReplica View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Adds a replica to an availability group on one or more SQL Server instances. Description Adds a replica to an availability group on one or more SQL Server instances. Automatically creates database mirroring endpoints if required. Syntax Add-DbaAgReplica [-SqlInstance] [[-SqlCredential] ] [[-Name] ] [[-ClusterType] ] [[-AvailabilityMode] ] [[-FailoverMode] ] [[-BackupPriority] ] [[-ConnectionModeInPrimaryRole] ] [[-ConnectionModeInSecondaryRole] ] [[-SeedingMode] ] [[-Endpoint] ] [[-EndpointUrl] ] [-Passthru] [[-ReadOnlyRoutingList] ] [[-ReadonlyRoutingConnectionUrl] ] [[-Certificate] ] [-ConfigureXESession] [[-SessionTimeout] ] [-InputObject] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Adds sql2017b to the SharePoint availability group on sql2017a PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b Example 2: Adds sql2017b to the SharePoint availability group on sql2017a with a manual failover mode PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b -FailoverMode Manual Example 3: Adds sql2017b to the SharePoint availability group on sql2017a with a custom endpoint URL PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b -EndpointUrl 'TCP://sql2017b.specialnet.local:5022' Required Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations. This is the target availability group where the replica will be added. Use pipeline scenarios like 'Get-DbaAvailabilityGroup -AvailabilityGroup \"AG1\" | Add-DbaAgReplica -SqlInstance server2' for streamlined replica management. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instances using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Sets the display name for the availability group replica being added. Defaults to the SQL Server instance's domain instance name. Use this when you need a custom replica name that differs from the server name, such as for clarity in multi-subnet scenarios. This parameter is only supported when adding a replica to a single instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ClusterType Specifies the underlying clustering technology for the availability group. Only supported in SQL Server 2017 and above. Use 'Wsfc' for traditional Windows Server Failover Cluster setups, 'External' for Linux Pacemaker clusters, or 'None' for read-scale availability groups. Defaults to 'Wsfc' which handles most Windows-based high availability scenarios. The default can be changed with: Set-DbatoolsConfig -FullName 'AvailabilityGroups.Default.ClusterType' -Value '...' -Passthru | Register-DbatoolsConfig | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'AvailabilityGroups.Default.ClusterType' -Fallback 'Wsfc') | | Accepted Values | 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. AsynchronousCommit commits immediately on primary without waiting for secondary confirmation, providing better performance but potential data loss during failover. Defaults to SynchronousCommit for maximum data protection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | SynchronousCommit | | Accepted Values | 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 availability. Manual failover requires DBA intervention but works with both synchronous and asynchronous commit modes. Defaults to Automatic for immediate failover capabilities. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Automatic | | Accepted Values | Automatic,Manual,External | -BackupPriority Sets the replica's preference for hosting backups within the availability group, ranging from 0-100 where higher values indicate higher priority. Use this to designate specific replicas for backup operations, such as setting secondary replicas to higher values to offload backup workloads from the primary. Defaults to 50, giving all replicas equal backup preference. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 50 | -ConnectionModeInPrimaryRole Controls which client connections are allowed when this replica is the primary. AllowAllConnections permits both read-write and read-only connections. AllowReadWriteConnections restricts access to connections that specify read-write intent, blocking read-only connection attempts. Defaults to AllowAllConnections for maximum compatibility with existing applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | AllowAllConnections | | Accepted Values | AllowAllConnections,AllowReadWriteConnections | -ConnectionModeInSecondaryRole Controls client access to secondary replicas for read operations. AllowNoConnections blocks all client connections to the secondary. AllowReadIntentConnectionsOnly permits only connections that specify ApplicationIntent=ReadOnly, ideal for reporting workloads. AllowAllConnections allows any client connection regardless of intent. Defaults to AllowNoConnections for security and performance. The default can be changed with: Set-DbatoolsConfig -FullName 'AvailabilityGroups.Default.ConnectionModeInSecondaryRole' -Value '...' -Passthru | Register-DbatoolsConfig | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'AvailabilityGroups.Default.ConnectionModeInSecondaryRole' -Fallback 'AllowNoConnections') | | Accepted Values | 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. Automatic seeding transfers data directly over the network without manual backup/restore operations, ideal for large databases or automated deployments. Manual seeding requires you to manually backup databases on the primary and restore them on the secondary, providing more control over the timing and process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this when you need a custom endpoint name instead of the default \"hadr_endpoint\" that gets created automatically. Each SQL Server instance requires a database mirroring endpoint for Always On availability group replication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EndpointUrl Overrides the default endpoint URL with custom network addresses for availability group communication. Defaults to the FQDN from the existing endpoint. Required for special network configurations like multi-subnet deployments, NAT environments, or when replicas need specific IP addresses for cross-network communication. Must be in format 'TCP://system-address:port' with one entry per instance. When creating new endpoints, IPv4 addresses in the URL will be used for endpoint configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Passthru Returns the replica object without actually creating it in the availability group, allowing for additional customization before final creation. Use this when you need to modify replica properties that aren't exposed as direct parameters before adding it to the availability group. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this to direct reporting queries to specific secondary replicas, creating an ordered list like @('Server2', 'Server3') to balance read-only workloads. This parameter is only supported when adding a replica to a single instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Must be in format 'TCP://system-address:port' and typically differs from the regular endpoint URL when using custom network configurations for read workloads. This parameter is only supported when adding a replica to a single instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this in environments where SQL Server instances run under different domain accounts or in workgroup configurations where Windows authentication isn't feasible. The remote replica must have a matching certificate with the corresponding public key for secure communication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ConfigureXESession Automatically configures the AlwaysOn_health extended events session to start with SQL Server, matching the behavior of the SSMS availability group wizard. Use this to enable automatic collection of availability group health data for monitoring and troubleshooting replica connectivity, failover events, and performance issues. The session captures critical Always On events and is essential for proactive availability group management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Lower values provide faster failure detection but may cause false failures under network stress. Higher values prevent false failures but delay failover detection. Microsoft recommends keeping this at 10 seconds or higher for stable operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityReplica Returns one AvailabilityReplica object for each replica added to the availability group. When -Passthru is specified, the replica object is returned before being added to the availability group, allowing for additional customization. When -Passthru is not specified, the replica is added to the availability group and the returned object includes added properties for display and context. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) AvailabilityGroup: Name of the availability group that contains this replica Name: The name/display name of the availability replica Role: Current role of the replica (Primary or Secondary) RollupSynchronizationState: Synchronization state (NotSynchronizing, Synchronizing, Synchronized, Reverting, Initializing) AvailabilityMode: Commit mode (SynchronousCommit or AsynchronousCommit) BackupPriority: Backup preference priority (0-100) EndpointUrl: Database mirroring endpoint URL for replica communication SessionTimeout: Session timeout in seconds for failure detection FailoverMode: Failover mode (Automatic or Manual) ReadonlyRoutingList: Priority-ordered list of replicas for read-only routing Additional properties available (from SMO AvailabilityReplica object): ConnectionModeInPrimaryRole: Connection mode when this replica is primary (AllowAllConnections or AllowReadWriteConnections) ConnectionModeInSecondaryRole: Connection mode when this replica is secondary (AllowNoConnections, AllowReadIntentConnectionsOnly, or AllowAllConnections) ReadonlyRoutingConnectionUrl: Connection URL for read-only routing operations SeedingMode: Database seeding mode (Automatic or Manual) - SQL Server 2016+ Parent: Reference to the parent AvailabilityGroup object State: The state of the SMO object (Existing, Creating, Pending, etc.) Urn: Uniform resource name of the replica All properties from the base SMO AvailabilityReplica object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Add-DbaComputerCertificate",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaComputerCertificate",
    "popularityRank": 86,
    "synopsis": "Imports X.509 certificates into the Windows certificate store on local or remote computers.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Add-DbaComputerCertificate View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Imports X.509 certificates into the Windows certificate store on local or remote computers. 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. When 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. The 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. Syntax Add-DbaComputerCertificate [[-ComputerName] ] [[-Credential] ] [[-SecurePassword] ] [[-Certificate] ] [[-Path] ] [[-Store] ] [[-Folder] ] [[-Flag] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Adds the local C:\\temp\\cert.cer to the remote server Server1 in LocalMachine\\My (Personal) PS C:\\> Add-DbaComputerCertificate -ComputerName Server1 -Path C:\\temp\\cert.cer Example 2: Adds the local C:\\temp\\cert.cer to the local computer&#39;s LocalMachine\\My (Personal) certificate store PS C:\\> Add-DbaComputerCertificate -Path C:\\temp\\cert.cer Example 3: Adds the local C:\\temp\\cert.cer to the local computer&#39;s LocalMachine\\My (Personal) certificate store PS C:\\> Add-DbaComputerCertificate -Path C:\\temp\\cert.cer Example 4: Adds the local C:\\temp\\sql01.pfx to sql01&#39;s LocalMachine\\My (Personal) certificate store and marks the... PS C:\\> Add-DbaComputerCertificate -ComputerName sql01 -Path C:\\temp\\sql01.pfx -Confirm:$false -Flag NonExportable Adds the local C:\\temp\\sql01.pfx to sql01's LocalMachine\\My (Personal) certificate store and marks the private key as non-exportable. Skips confirmation prompt. Example 5: Imports a Let&#39;s Encrypt certificate with the full chain (including intermediate certificates) from a PFX... PS C:\\> $password = Read-Host \"Enter the SSL Certificate Password\" -AsSecureString PS C:\\> Add-DbaComputerCertificate -ComputerName sql01 -Path C:\\cert\\fullchain.pfx -SecurePassword $password PS C:\\> Get-DbaComputerCertificate -ComputerName sql01 | Where-Object Subject -match \"letsencrypt\" | Set-DbaNetworkCertificate -SqlInstance sql01 Imports a Let's 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 Set-DbaNetworkCertificate can properly set permissions on the certificate. Optional Parameters -ComputerName The target computer or computers where certificates will be installed. Accepts server names, FQDNs, or IP addresses. Use this when installing certificates on remote SQL Server hosts or cluster nodes. Defaults to localhost when not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to $ComputerName using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecurePassword The password for encrypted certificate files (.pfx files with private keys). Required when importing password-protected certificates. Use this when installing SSL certificates or Service Broker certificates that were exported with password protection. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -Certificate A certificate object from the pipeline or PowerShell variable. Accepts X509Certificate2 objects from Get-ChildItem Cert:\\ or other certificate commands. Use this when you already have certificate objects loaded in memory rather than reading from disk files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Path The local file path to the certificate file (.cer, .crt, .pfx, .p12). The file must be accessible from the machine running the command. Specify this when installing certificates from files on disk, commonly used for SSL certificates or custom CA certificates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Store The certificate store location where certificates will be installed. Options are LocalMachine (system-wide) or CurrentUser (user-specific). Use LocalMachine for SQL Server service certificates and system certificates that need to be available to services. Defaults to LocalMachine. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | LocalMachine | -Folder The certificate store folder within the specified store. Common folders include My (Personal), Root (Trusted Root), and CA (Intermediate). Use My for SQL Server SSL certificates and Service Broker certificates. Defaults to My which is the Personal certificate store. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | My | -Flag Controls how certificate private keys are stored and accessed in the Windows certificate store. Determines security and accessibility characteristics. Use NonExportable for production SQL Server certificates to prevent private key extraction. Use Exportable when you need to back up or migrate certificates. Defaults to: Exportable, PersistKeySet EphemeralKeySet The key associated with a PFX file is created in memory and not persisted on disk when importing a certificate. Exportable Imported keys are marked as exportable. NonExportable Explicitly mark keys as nonexportable. PersistKeySet The key associated with a PFX file is persisted when importing a certificate. UserProtected 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 add a certificate to localhost, as it causes a prompt to appear. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @(\"Exportable\", \"PersistKeySet\") | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.Security.Cryptography.X509Certificates.X509Certificate2 Returns 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, intermediate, and leaf certificates). Default display properties (via Select-DefaultView): FriendlyName: The friendly name of the certificate (as configured in the certificate store) DnsNameList: Collection of DNS names the certificate is valid for (Subject Alternative Names) Thumbprint: The SHA-1 hash of the certificate, used as a unique identifier NotBefore: DateTime when the certificate becomes valid NotAfter: DateTime when the certificate expires Subject: The distinguished name of the certificate subject (organization, common name, etc.) Issuer: The distinguished name of the certificate issuer (certification authority) Additional properties available on the X509Certificate2 object: Archived: Boolean indicating if the certificate is marked as archived in the store Extensions: Collection of X.509 extensions (key usage, extended key usage, etc.) HasPrivateKey: Boolean indicating if the private key is available IssuerName: X500DistinguishedName object for the issuer PrivateKey: Cryptographic private key object (if HasPrivateKey is true) PublicKey: Cryptographic public key object SerialNumber: Serial number of the certificate SignatureAlgorithm: Algorithm used to sign the certificate SubjectName: X500DistinguishedName object for the subject Version: X.509 version number Use Select-Object * to access all properties of the imported certificate objects. &nbsp;"
  },
  {
    "name": "Add-DbaDbFile",
    "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.",
    "category": "Database Operations",
    "tags": [
      "storage",
      "data",
      "file",
      "filegroup"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaDbFile",
    "popularityRank": 0,
    "synopsis": "Adds data files to existing filegroups in SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Add-DbaDbFile View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Adds data files to existing filegroups in SQL Server databases. 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. Syntax Add-DbaDbFile [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-FileGroup] ] [[-FileName] ] [[-Path] ] [[-Size] ] [[-Growth] ] [[-MaxSize] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Adds a new data file named HRFG1_data1 to the HRFG1 filegroup in the TestDb database using default size and... PS C:\\> Add-DbaDbFile -SqlInstance sql2016 -Database TestDb -FileGroup HRFG1 -FileName \"HRFG1_data1\" Adds a new data file named HRFG1_data1 to the HRFG1 filegroup in the TestDb database using default size and growth settings. Example 2: Adds a memory-optimized container to the dbatools_inmem MemoryOptimizedDataFileGroup PS C:\\> Add-DbaDbFile -SqlInstance sql2016 -Database TestDb -FileGroup dbatools_inmem -FileName \"inmem_container\" -Path \"C:\\Data\\inmem\" Adds a memory-optimized container to the dbatools_inmem MemoryOptimizedDataFileGroup. For memory-optimized filegroups, the Path should be a directory. Example 3: Adds a new 512MB data file with 128MB growth increments and a maximum size of 10GB to the Secondary filegroup PS C:\\> Add-DbaDbFile -SqlInstance sql2016 -Database TestDb -FileGroup Secondary -FileName \"Secondary_data2\" -Size 512 -Growth 128 -MaxSize 10240 Example 4: Pipes the TestDb database and adds a new file to the HRFG1 filegroup using pipeline input PS C:\\> Get-DbaDatabase -SqlInstance sql2016 -Database TestDb | Add-DbaDbFile -FileGroup HRFG1 -FileName \"HRFG1_data1\" Example 5: Adds a new data file with a custom path and filename to the HRFG1 filegroup PS C:\\> Add-DbaDbFile -SqlInstance sql2016 -Database TestDb -FileGroup HRFG1 -FileName \"HRFG1_data1\" -Path \"E:\\SQLData\\TestDb_HRFG1_data1.ndf\" Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database(s) containing the filegroup where the file will be added. Supports multiple database names for bulk operations. Use this when you need to add files to the same filegroup across multiple databases for consistency. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileGroup Specifies the name of the filegroup where the new file will be added. The filegroup must already exist in the database. This is typically used after creating a new filegroup with New-DbaDbFileGroup, especially for MemoryOptimizedDataFileGroup which requires files before use. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileName Sets the logical name for the new file being created. This name is used within SQL Server to reference the file. If not specified, a name will be auto-generated based on the database and filegroup names to ensure uniqueness. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the full physical path where the file will be created on disk, including the filename and extension (.ndf for data files). If not specified, the file will be placed in the SQL Server default data directory with an auto-generated filename. For MemoryOptimizedDataFileGroup, the path should point to a directory (not a file) where the container will be created. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Size Sets the initial size of the file in megabytes (MB). Defaults to 128MB if not specified. Use larger values for high-volume databases or smaller values for development/test databases to optimize storage allocation. For MemoryOptimizedDataFileGroup, this parameter is ignored as memory-optimized filegroups manage their own sizing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 128 | -Growth Specifies the file growth increment in megabytes (MB). Defaults to 64MB if not specified. This controls how much the file expands when it runs out of space, with fixed-size growth preferred over percentage-based for predictable space management. For MemoryOptimizedDataFileGroup, this parameter is ignored as memory-optimized filegroups do not use auto-growth settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 64 | -MaxSize Sets the maximum size the file can grow to in megabytes (MB). Defaults to unlimited (-1) if not specified. Use this to prevent runaway file growth and protect disk space, particularly important on shared storage or systems with limited capacity. For MemoryOptimizedDataFileGroup, this parameter is ignored. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | -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. Useful when working with multiple databases that match specific criteria rather than specifying database names directly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.DataFile Returns 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. Common properties: Name: The logical name of the data file as specified in the FileName parameter FileName: The physical path to the file on disk 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. Growth: The file growth increment in kilobytes (KB) - set based on the Growth parameter multiplied by 1024. Not set for memory-optimized filegroups. GrowthType: The type of growth (KB or Percent). Set to \"KB\" for standard data files. Not set for memory-optimized filegroups. 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. Parent: The FileGroup object that contains this file IsPrimaryFile: Boolean indicating if this is the primary data file for the database IsReadOnly: Boolean indicating if the file is marked as read-only IsOffline: Boolean indicating if the file is offline Additional properties available from SMO DataFile object: ID: Unique identifier for the file AvailableSpace: Available space in the file in bytes UsedSpace: Space currently used by data in the file in bytes BytesReadFromDisk: Total bytes read from the file since SQL Server started BytesWrittenToDisk: Total bytes written to the file since SQL Server started NumberOfDiskReads: Total number of read operations on the file NumberOfDiskWrites: Total number of write operations on the file VolumeFreeSpace: Free space available on the volume containing the file in bytes IsReadOnlyMedia: Boolean indicating if the file's media is read-only IsSparse: Boolean indicating if the file is a sparse file State: The current state of the SMO object (Existing, Creating, Pending, etc.) All properties are accessible via Select-Object * or by referencing the property directly on the returned object. &nbsp;"
  },
  {
    "name": "Add-DbaDbMirrorMonitor",
    "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.",
    "category": "Utilities",
    "tags": [
      "mirroring",
      "mirror",
      "ha"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaDbMirrorMonitor",
    "popularityRank": 273,
    "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",
    "windowsOnly": false,
    "fullContent": "Add-DbaDbMirrorMonitor View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on the server instance. Description Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on the server instance. Basically executes sp_dbmmonitoraddmonitoring. Syntax Add-DbaDbMirrorMonitor [-SqlInstance] [[-SqlCredential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored... PS C:\\> Add-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012 Creates a database mirroring monitor job that periodically updates the mirroring status for every mirrored database on sql2008 and sql2012. Required Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance where the mirroring monitor was successfully added. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) MonitorStatus: Status of the operation - displays \"Added\" when the mirror monitoring job is successfully created &nbsp;"
  },
  {
    "name": "Add-DbaDbRoleMember",
    "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.",
    "category": "Utilities",
    "tags": [
      "role",
      "user"
    ],
    "verb": "Add",
    "popular": true,
    "url": "/Add-DbaDbRoleMember",
    "popularityRank": 41,
    "synopsis": "Adds database users or roles as members to database roles across SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Add-DbaDbRoleMember View Source Ben Miller (@DBAduck) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Adds database users or roles as members to database roles across SQL Server instances 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. Syntax Add-DbaDbRoleMember [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Role] ] [-Member] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Adds user1 to the role db_owner in the database mydb on the local default SQL Server instance PS C:\\> Add-DbaDbRoleMember -SqlInstance localhost -Database mydb -Role db_owner -Member user1 Example 2: Adds user1 in servers localhost and sql2016 in the msdb database to the SqlAgentOperatorRole PS C:\\> Add-DbaDbRoleMember -SqlInstance localhost, sql2016 -Role SqlAgentOperatorRole -Member user1 -Database msdb Example 3: Adds user1 to the SqlAgentOperatorRole in the msdb database in every server in C:\\servers.txt PS C:\\> $servers = Get-Content C:\\servers.txt PS C:\\> $servers | Add-DbaDbRoleMember -Role SqlAgentOperatorRole -Member user1 -Database msdb Example 4: Adds user1 in the database DEMODB on the server localhost to the roles db_datareader and db_datawriter PS C:\\> Add-DbaDbRoleMember -SqlInstance localhost -Role \"db_datareader\",\"db_datawriter\" -Member user1 -Database DEMODB Example 5: Adds user1 in the database DEMODB on the server localhost to the roles db_datareader and db_datawriter PS C:\\> $roles = Get-DbaDbRole -SqlInstance localhost -Role \"db_datareader\",\"db_datawriter\" -Database DEMODB PS C:\\> $roles | Add-DbaDbRoleMember -Member user1 Required Parameters -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. The function validates that each member exists in the database before attempting to add them, preventing errors from typos or missing objects. | Property | Value | | --- | --- | | Alias | User | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to process for role membership changes. Accepts multiple database names and supports wildcards. When omitted, the function processes all databases on the target instances, making it useful for organization-wide security standardization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need to grant specific database permissions by adding users or roles to appropriate database roles. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts piped input from Get-DbaDbRole, Get-DbaDatabase, or SQL Server instances for streamlined workflows. Use this when chaining commands together, such as filtering specific roles first then adding members to those filtered results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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. When -WhatIf is specified, the command will display what changes would be made without performing them. &nbsp;"
  },
  {
    "name": "Add-DbaExtendedProperty",
    "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't 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",
    "category": "Utilities",
    "tags": [
      "general",
      "extendedproperty"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaExtendedProperty",
    "popularityRank": 257,
    "synopsis": "Adds extended properties to SQL Server objects for metadata storage and documentation",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Add-DbaExtendedProperty View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Adds extended properties to SQL Server objects for metadata storage and documentation 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't affect object performance but provide valuable context for DBAs managing complex environments. This 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: Aggregate Assembly Column Constraint Contract Database Event Notification Filegroup Function Index Logical File Name Message Type Parameter Partition Function Partition Scheme Procedure Queue Remote Service Binding Route Rule Schema Service Synonym Table Trigger Type View Xml Schema Collection Syntax Add-DbaExtendedProperty [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [-Name] [-Value] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the version extended property for the db1 database to 1.0.0 PS C:\\> Add-DbaExtendedProperty -SqlInstance Server1 -Database db1 -Name version -Value \"1.0.0\" Example 2: Creates an extended property for all stored procedures in the tempdb database named SPVersion with a value of... PS C:\\> Get-DbaDbStoredProcedure -SqlInstance localhost -Database tempdb | Add-DbaExtendedProperty -Name SPVersion -Value 10.2 Creates an extended property for all stored procedures in the tempdb database named SPVersion with a value of 10.2 Example 3: Creates an extended property named MyExtendedProperty for the mytable table in the mydb, with a value of... PS C:\\> Get-DbaDbTable -SqlInstance localhost -Database mydb -Table mytable | Add-DbaExtendedProperty -Name MyExtendedProperty -Value \"This is a test\" Creates an extended property named MyExtendedProperty for the mytable table in the mydb, with a value of \"This is a test\" Required Parameters -Name Sets the name identifier for the extended property being created. Must be unique per object. Common examples include \"Version\", \"Owner\", \"Purpose\", \"DataClassification\", or \"LastModified\" for documentation and compliance tracking. | Property | Value | | --- | --- | | Alias | Property | | Required | True | | Pipeline | false | | Default Value | | -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. Keep values concise as they're stored in system catalogs and are visible in SQL Server Management Studio object properties. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to target when adding extended properties directly to database objects. Accepts wildcards for pattern matching. Use this when you want to add metadata to entire databases rather than piping specific objects from Get-Dba commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. This is the primary method for bulk-applying extended properties across multiple objects in your database environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.ExtendedProperty Returns one ExtendedProperty object for each extended property successfully created on the target object(s). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ParentName: The name of the SQL Server object to which the extended property was added (database, table, procedure, etc.) Type: The SMO object type name of the parent object (Database, Table, StoredProcedure, View, etc.) Name: The name identifier of the extended property being created Value: The string value assigned to the extended property Additional properties available (from SMO ExtendedProperty object): ID: Numeric identifier of the extended property Urn: Unique Resource Name identifying the extended property in the object hierarchy State: SMO object state (Existing, Creating, Pending, etc.) All properties from the base SMO object are accessible even though only default properties are displayed without using Select-Object . &nbsp;"
  },
  {
    "name": "Add-DbaInstanceList",
    "description": "Adds SQL Server instance names to a persistent list that pre-populates the tab completion\ncache for the -SqlInstance parameter across all dbatools commands. This allows users to\nhave their frequently used instances available for autocomplete in their PowerShell\nterminal without needing to connect to them first.\n\nThe instance list is stored using the dbatools configuration system. Use -Register to\npersist the list across PowerShell sessions.\n\nInstances can also be pre-loaded at module import time by setting the\n$env:DBATOOLS_KNOWN_INSTANCES environment variable to a comma-separated list of instance\nnames in your PowerShell profile.",
    "category": "Server Management",
    "tags": [
      "tabcompletion",
      "autocomplete"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaInstanceList",
    "popularityRank": 0,
    "synopsis": "Adds one or more SQL Server instances to the user-maintained autocomplete list.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Add-DbaInstanceList View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Adds one or more SQL Server instances to the user-maintained autocomplete list. Description Adds SQL Server instance names to a persistent list that pre-populates the tab completion cache for the -SqlInstance parameter across all dbatools commands. This allows users to have their frequently used instances available for autocomplete in their PowerShell terminal without needing to connect to them first. The instance list is stored using the dbatools configuration system. Use -Register to persist the list across PowerShell sessions. Instances can also be pre-loaded at module import time by setting the $env:DBATOOLS_KNOWN_INSTANCES environment variable to a comma-separated list of instance names in your PowerShell profile. Syntax Add-DbaInstanceList [-SqlInstance] [-Register] [[-Scope] {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [ ] &nbsp; Examples &nbsp; Example 1: Adds sql01 and sql02\\dev to the autocomplete instance list for the current session PS C:\\> Add-DbaInstanceList -SqlInstance \"sql01\", \"sql02\\dev\" Example 2: Adds sql01 to the autocomplete instance list and persists it across PowerShell sessions PS C:\\> Add-DbaInstanceList -SqlInstance \"sql01\" -Register Example 3: Adds two instances to the list via pipeline and persists them across sessions PS C:\\> \"sql01\", \"sql02\" | Add-DbaInstanceList -Register Required Parameters -SqlInstance The SQL Server instance name or names to add to the autocomplete list. Accepts pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | Optional Parameters -Register Persists the instance list to disk so it is available in future PowerShell sessions. Without this switch, the list only exists for the current session. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Scope Determines where the persistent configuration is stored when using -Register. UserDefault stores the setting for the current user only. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UserDefault | Outputs None This command updates the autocomplete cache but does not output any objects to the pipeline. Use Get-DbaInstanceList to retrieve the configured instance names. &nbsp;"
  },
  {
    "name": "Add-DbaPfDataCollectorCounter",
    "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.",
    "category": "Utilities",
    "tags": [
      "perfmon"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaPfDataCollectorCounter",
    "popularityRank": 304,
    "synopsis": "Adds performance counters to existing Windows Performance Monitor Data Collector Sets for SQL Server monitoring.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Add-DbaPfDataCollectorCounter View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Adds performance counters to existing Windows Performance Monitor Data Collector Sets for SQL Server monitoring. 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. Syntax Add-DbaPfDataCollectorCounter [[-ComputerName] ] [[-Credential] ] [[-CollectorSet] ] [[-Collector] ] [-Counter] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Adds the &#39;\\LogicalDisk()\\Avg PS C:\\> Add-DbaPfDataCollectorCounter -ComputerName sql2017 -CollectorSet 'System Correlation' -Collector DataCollector01 -Counter '\\LogicalDisk()\\Avg. Disk Queue Length' Adds the '\\LogicalDisk()\\Avg. Disk Queue Length' counter within the DataCollector01 collector within the System Correlation collector set on sql2017. Example 2: Allows you to select which Data Collector you&#39;d like to add the counter &#39;\\LogicalDisk()\\Avg PS C:\\> Get-DbaPfDataCollector | Out-GridView -PassThru | Add-DbaPfDataCollectorCounter -Counter '\\LogicalDisk()\\Avg. Disk Queue Length' -Confirm Allows you to select which Data Collector you'd like to add the counter '\\LogicalDisk()\\Avg. Disk Queue Length' on localhost and prompts for confirmation. Required Parameters -Counter Specifies the performance counter path to add to the Data Collector. Must use the full counter path format like '\\Processor(_Total)\\% Processor Time' or '\\SQLServer:Buffer Manager\\Page life expectancy'. Use Get-DbaPfAvailableCounter to find available SQL Server and system counters with their exact paths. | Property | Value | | --- | --- | | Alias | Name | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -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. Defaults to localhost if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to $ComputerName using alternative credentials. To use: $cred = Get-Credential, then pass $cred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CollectorSet Specifies the name of the Windows Performance Monitor Data Collector Set that contains the collector you want to modify. This is the parent container that organizes related performance data collectors for your monitoring scenario. | Property | Value | | --- | --- | | Alias | DataCollectorSet | | Required | False | | Pipeline | false | | Default Value | | -Collector Specifies the name of the individual Data Collector within the CollectorSet where the new counter will be added. Each collector can contain multiple performance counters and defines how the data is gathered and stored. | Property | Value | | --- | --- | | Alias | DataCollector | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Data Collector objects from Get-DbaPfDataCollector via the pipeline. This allows you to target specific collectors for counter addition. Also accepts counter objects from Get-DbaPfAvailableCounter to add available counters directly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per counter added to the Data Collector Set. Default display properties (via Select-DefaultView): ComputerName: The name of the computer where the Data Collector Set is configured DataCollectorSet: The name of the parent Data Collector Set containing the collector DataCollector: The name of the specific Data Collector within the Collector Set Name: The full path of the performance counter that was added FileName: The output file name where performance counter data will be stored Additional properties available: DataCollectorSetXml: The XML configuration of the Data Collector Set (typically excluded from default view) Credential: The credentials used to connect to the target computer (typically excluded from default view) CounterObject: Internal flag indicating this is a counter object (typically excluded from default view) &nbsp;"
  },
  {
    "name": "Add-DbaRegServer",
    "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't 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.",
    "category": "Utilities",
    "tags": [
      "registeredserver",
      "cms"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaRegServer",
    "popularityRank": 81,
    "synopsis": "Registers SQL Server instances to Central Management Server or Local Server Groups in SSMS",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Add-DbaRegServer View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Registers SQL Server instances to Central Management Server or Local Server Groups in SSMS 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't 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. Syntax Add-DbaRegServer [[-SqlInstance] ] [[-SqlCredential] ] [[-ServerName] ] [[-Name] ] [[-Description] ] [[-Group] ] [[-ActiveDirectoryTenant] ] [[-ActiveDirectoryUserId] ] [[-ConnectionString] ] [[-OtherParams] ] [[-InputObject] ] [[-ServerObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a registered server on sql2008&#39;s CMS which points to the SQL Server, sql01 PS C:\\> Add-DbaRegServer -SqlInstance sql2008 -ServerName sql01 Creates a registered server on sql2008's CMS which points to the SQL Server, sql01. When scrolling in CMS, the name \"sql01\" will be visible. Example 2: Creates a registered server in Local Server Groups which points to the SQL Server, sql01 PS C:\\> Add-DbaRegServer -ServerName sql01 Creates 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. Example 3: Creates a registered server on sql2008&#39;s CMS which points to the SQL Server, sql01 PS C:\\> Add-DbaRegServer -SqlInstance sql2008 -ServerName sql01 -Name \"The 2008 Clustered Instance\" -Description \"HR's Dedicated SharePoint instance\" Creates a registered server on sql2008's CMS which points to the SQL Server, sql01. When scrolling in CMS, \"The 2008 Clustered Instance\" will be visible. Clearly this is hard to explain ;) Example 4: Creates a registered server on sql2008&#39;s CMS which points to the SQL Server, sql01 PS C:\\> Add-DbaRegServer -SqlInstance sql2008 -ServerName sql01 -Group hr\\Seattle Creates a registered server on sql2008's 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. Example 5: Creates a registered server called &quot;mydockerjam&quot; in Local Server Groups that uses SQL authentication and... PS C:\\> Connect-DbaInstance -SqlInstance dockersql1 -SqlCredential sqladmin | Add-DbaRegServer -ServerName mydockerjam Creates a registered server called \"mydockerjam\" in Local Server Groups that uses SQL authentication and points to the server dockersql1. Optional Parameters -SqlInstance The target SQL Server instance if a CMS is used | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ServerName Specifies the actual SQL Server instance name or network address that will be used to connect to the server. This is the technical identifier that SSMS uses for the physical connection (e.g., \"sql01.domain.com,1433\" or \"sql01\\INSTANCE\"). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Sets the display name that appears in the SSMS Registered Servers tree or CMS interface. Use this to give servers meaningful, recognizable names like \"Production HR Database\" instead of cryptic server names. Defaults to ServerName if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $ServerName | -Description Provides additional details about the registered server that appear in SSMS properties. Use this to document the server's purpose, environment, or important notes like \"Primary OLTP for HR applications\" or \"Read-only replica for reporting\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Group Places the registered server into a specific organizational folder within CMS or Local Server Groups. Creates nested groups using backslash notation like \"Production\\OLTP\" or \"Dev\\Testing\". The group structure will be created automatically if it doesn't exist. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ActiveDirectoryTenant Specifies the Azure Active Directory tenant ID when registering servers that use Azure AD authentication. Required when connecting to Azure SQL Database or SQL Managed Instance with AAD credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ActiveDirectoryUserId Sets the Azure Active Directory user principal name for AAD authentication scenarios. Use this when you want the registered server to authenticate with a specific AAD account instead of integrated authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ConnectionString Provides a complete SQL Server connection string with all authentication and connection parameters. Use this when you need specific connection properties like encryption settings, timeout values, or custom authentication methods not covered by other parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OtherParams Appends additional connection string parameters to the base connection. Useful for adding specific connection properties like \"MultipleActiveResultSets=True\" or \"TrustServerCertificate=True\" without rebuilding the entire connection string. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts a server group object from Get-DbaRegServerGroup to specify where the server should be registered. Use this when you want to programmatically target a specific group or when piping group objects from other dbatools commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -ServerObject Accepts an existing SMO Server object from Connect-DbaInstance to register that connection. This preserves all connection settings and authentication from the original connection, making it ideal for registering servers you've already successfully connected to. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer Returns one RegisteredServer object for each server registered. Multiple servers can be returned when registering to different server groups or Central Management Server instances. Default display properties (via Select-DefaultView): Name: Display name of the registered server as it appears in SSMS Registered Servers pane ServerName: The actual SQL Server connection string or instance name Group: The server group hierarchy path where the server is registered (null if in root) Description: User-provided description of the registered server Source: Origin of the registration (Central Management Servers, Local Server Groups, or Azure Data Studio) Additional properties available (from SMO RegisteredServer object): ComputerName: The computer name of the CMS or local registration location InstanceName: The instance name of the CMS or local registration location SqlInstance: The full SQL instance identifier of the CMS (computer\\instance) ParentServer: Reference to the parent server store object Id: Unique identifier of the registered server within its store ConnectionString: The connection string used to connect to the server SecureConnectionString: Encrypted version of the connection string ActiveDirectoryTenant: Azure AD tenant ID if using Azure AD authentication ActiveDirectoryUserId: Azure AD user principal name if using Azure AD authentication OtherParams: Additional connection string parameters CredentialPersistenceType: How credentials are stored (PersistLoginNameAndPassword, etc.) ServerType: Type of server (DatabaseEngine, AnalysisServices, etc.) FQDN: Fully qualified domain name (populated when -ResolveNetworkName is used on Get-DbaRegServer) IPAddress: IP address of the server (populated when -ResolveNetworkName is used on Get-DbaRegServer) &nbsp;"
  },
  {
    "name": "Add-DbaRegServerGroup",
    "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't exist. If you need to import existing groups and servers from other sources, use Import-DbaRegServer instead.",
    "category": "Utilities",
    "tags": [
      "registeredserver",
      "cms"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaRegServerGroup",
    "popularityRank": 279,
    "synopsis": "Creates organizational server groups within SQL Server Central Management Server (CMS)",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Add-DbaRegServerGroup View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates organizational server groups within SQL Server Central Management Server (CMS) 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't exist. If you need to import existing groups and servers from other sources, use Import-DbaRegServer instead. Syntax Add-DbaRegServerGroup [[-SqlInstance] ] [[-SqlCredential] ] [-Name] [[-Description] ] [[-Group] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a registered server group called HR, in the root of sql2012&#39;s CMS PS C:\\> Add-DbaRegServerGroup -SqlInstance sql2012 -Name HR Example 2: Creates a registered server group on sql2012 and sql2014 called sub-folder within the HR group PS C:\\> Add-DbaRegServerGroup -SqlInstance sql2012, sql2014 -Name sub-folder -Group HR Example 3: Creates a registered server group on sql2012 and sql2014 called sub-folder within the HR group of each server PS C:\\> Get-DbaRegServerGroup -SqlInstance sql2012, sql2014 -Group HR | Add-DbaRegServerGroup -Name sub-folder Required Parameters -Name Specifies the name for the new server group within Central Management Server. Use descriptive names that reflect your organizational structure like 'Production', 'Development', or 'HR-Databases'. Group names can include backslashes to create nested hierarchies (e.g., 'Production\\WebServers' creates a WebServers subgroup under Production). | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Description Provides additional details about the server group's purpose or contents. Use this to document the group's role, maintenance schedules, or contact information. Helpful for team environments where multiple DBAs need to understand each group's function. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use backslash notation to specify nested paths like 'Production\\WebServers' - this automatically creates any missing parent groups in the hierarchy. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Enables bulk operations where you can pipe existing groups and create new subgroups within each one simultaneously. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.RegisteredServers.ServerGroup Returns 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). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance hosting the Central Management Server InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the server group DisplayName: The display name of the server group Description: Description of the server group (if provided) ServerGroups: Collection of subgroups within this group RegisteredServers: Collection of registered servers in this group Additional properties available from the SMO ServerGroup object: Id: Unique identifier for the group within the CMS Parent: The parent ServerGroup object Urn: Uniform Resource Name identifying the group in the SMO object hierarchy State: SMO object state (Existing, Creating, Pending, etc.) &nbsp;"
  },
  {
    "name": "Add-DbaReplArticle",
    "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.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaReplArticle",
    "popularityRank": 400,
    "synopsis": "Adds a table or other database object as an article to an existing replication publication.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Add-DbaReplArticle View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Adds a table or other database object as an article to an existing replication publication. 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. Syntax Add-DbaReplArticle [-SqlInstance] [[-SqlCredential] ] [-Database] [-Publication] [[-Schema] ] [-Name] [[-Filter] ] [[-CreationScriptOptions] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Adds the TableToRepl table to the PubFromPosh publication from mssql1.Northwind PS C:\\> Add-DbaReplArticle -SqlInstance mssql1 -Database Northwind -Publication PubFromPosh -Name TableToRepl Example 2: Adds the publishers table to the TestPub publication from mssql1.Pubs with a horizontal filter of only rows... PS C:\\> $article = @{ >> SqlInstance = \"mssql1\" >> Database = \"pubs\" >> Publication = \"testPub\" >> Name = \"publishers\" >> Filter = \"city = 'seattle'\" >> } PS C:\\> Add-DbaReplArticle @article -EnableException Adds the publishers table to the TestPub publication from mssql1.Pubs with a horizontal filter of only rows where city = 'seattle. Example 3: Adds the stores table to the testPub publication from mssql1.pubs with the NonClusteredIndexes and Statistics... PS C:\\> $cso = New-DbaReplCreationScriptOptions -Options NonClusteredIndexes, Statistics PS C:\\> $article = @{ >> SqlInstance = 'mssql1' >> Database = 'pubs' >> Publication = 'testPub' >> Name = 'stores' >> CreationScriptOptions = $cso >> } PS C:\\> Add-DbaReplArticle @article -EnableException Adds the stores table to the testPub publication from mssql1.pubs with the NonClusteredIndexes and Statistics options set includes default options. Required Parameters -SqlInstance The SQL Server instance(s) for the publication. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Database Specifies the database containing both the publication and the object you want to add as an article. This must be the same database where your replication publication was created. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Publication Specifies the name of the existing replication publication to add the article to. The publication must already exist and be configured for the type of replication you want (transactional, snapshot, or merge). | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Name Specifies the name of the database object (typically a table) to add as an article to the publication. This object will be replicated to all subscribers of the publication. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Specifies the schema name of the object you want to add as an article. Use this when your table or object exists in a schema other than dbo. Defaults to dbo if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | dbo | -Filter Applies a WHERE clause condition to filter which rows get replicated from the article (horizontal filtering). Use this when you only want to replicate specific rows, such as \"City = 'Seattle'\" or \"Status = 'Active'\". Do not include the word 'WHERE' in your filter expression. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CreationScriptOptions Controls which schema elements get created on the subscriber database when the article is replicated. Use this to specify whether indexes, constraints, triggers, and other objects should be created on subscribers. Create this object using New-DbaReplCreationScriptOptions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Replication.TransArticle or Microsoft.SqlServer.Replication.MergeArticle Returns 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. Default display properties (via Select-DefaultView): ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: The name of the database containing the article PublicationName: The name of the publication containing the article Name: The name of the article as it appears in the publication Type: The type of article (table, view, stored procedure, etc.) VerticalPartition: Boolean indicating if the article uses vertical partitioning (column filtering) SourceObjectOwner: The schema of the source object (typically 'dbo') SourceObjectName: The name of the source object being replicated Additional properties available (from SMO Article object): BusinessLogicHandlerName: Name of the business logic handler (merge replication only) ColumnTrackingLevel: Column tracking level for merge replication CreationScript: Script containing the CREATE TABLE statement for the article DestinationObjectName: Optional different object name on the subscriber DestinationObjectOwner: Optional different schema name on the subscriber FilterClause: WHERE clause used for horizontal partitioning (row filtering) HorizontalPartition: Boolean indicating if the article uses horizontal partitioning IdentityRange: Range for identity column values (transactional replication only) IdentityRangeManagementOption: How identity ranges are managed IdentitySeed: Starting value for identity column replication PreCreatedObject: Boolean indicating if the object already exists on the subscriber PublicationName: Name of the publication containing the article SchemaOption: Defines which schema elements are included in the replication All properties from the SMO Article object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Add-DbaServerRoleMember",
    "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't have to manually assign permissions through SSMS or T-SQL scripts.",
    "category": "Security",
    "tags": [
      "role",
      "login"
    ],
    "verb": "Add",
    "popular": false,
    "url": "/Add-DbaServerRoleMember",
    "popularityRank": 99,
    "synopsis": "Adds logins or server roles to server-level roles for SQL Server security administration.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Add-DbaServerRoleMember View Source Shawn Melton (@wsmelton) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Adds logins or server roles to server-level roles for SQL Server security administration. 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't have to manually assign permissions through SSMS or T-SQL scripts. Syntax Add-DbaServerRoleMember [[-SqlInstance] ] [[-SqlCredential] ] [[-ServerRole] ] [[-Login] ] [[-Role] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Adds login1 to the dbcreator fixed server-level role on the instance server1 PS C:\\> Add-DbaServerRoleMember -SqlInstance server1 -ServerRole dbcreator -Login login1 Example 2: Adds login1 in customrole custom server-level role on the instance server1 and sql2016 PS C:\\> Add-DbaServerRoleMember -SqlInstance server1, sql2016 -ServerRole customrole -Login login1 Example 3: Adds customrole custom server-level role to dbcreator fixed server-level role PS C:\\> Add-DbaServerRoleMember -SqlInstance server1 -ServerRole customrole -Role dbcreator Example 4: Adds login1 to the sysadmin fixed server-level role in every server in C:\\servers.txt PS C:\\> $servers = Get-Content C:\\servers.txt PS C:\\> $servers | Add-DbaServerRoleMember -ServerRole sysadmin -Login login1 Example 5: Adds login1 on the server localhost to the bulkadmin and dbcreator fixed server-level roles PS C:\\> Add-DbaServerRoleMember -SqlInstance localhost -ServerRole bulkadmin, dbcreator -Login login1 Example 6: Adds login1 on the server localhost to the bulkadmin and dbcreator fixed server-level roles PS C:\\> $roles = Get-DbaServerRole -SqlInstance localhost -ServerRole bulkadmin, dbcreator PS C:\\> $roles | Add-DbaServerRoleMember -Login login1 Example 7: PS C:\\ $srvLogins = Get-DbaLogin -SqlInstance server1 -Login $logins PS C:\\ New-DbaServerRole -SqlInstance... PS C:\\> PS C:\\ $logins = Get-Content C:\\logins.txt PS C:\\ $srvLogins = Get-DbaLogin -SqlInstance server1 -Login $logins PS C:\\ New-DbaServerRole -SqlInstance server1 -ServerRole mycustomrole -Owner sa | Add-DbaServerRoleMember -Login $logins Adds all the logins found in C:\\logins.txt to the newly created server-level role mycustomrole on server1. Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need to grant server-level permissions by adding logins or nesting roles within these target roles. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -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. Use this when you need to give specific users or service accounts server-level permissions rather than nesting entire roles. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when implementing role-based security designs where you want to group permissions through role membership rather than individual login assignments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts server role objects piped from Get-DbaServerRole or New-DbaServerRole commands. Allows you to chain commands together for workflow automation. Use this when you want to operate on roles retrieved by other dbatools commands rather than specifying role names as strings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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 information about the actions being performed, or the -WhatIf switch to preview what would be changed without making modifications. &nbsp;"
  },
  {
    "name": "Backup-DbaComputerCertificate",
    "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.",
    "category": "Backup & Restore",
    "tags": [
      "certbackup",
      "certificate",
      "backup"
    ],
    "verb": "Backup",
    "popular": false,
    "url": "/Backup-DbaComputerCertificate",
    "popularityRank": 217,
    "synopsis": "Exports computer certificates to disk for SQL Server network encryption backup and disaster recovery.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Backup-DbaComputerCertificate View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports computer certificates to disk for SQL Server network encryption backup and disaster recovery. 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. Syntax Backup-DbaComputerCertificate [[-SecurePassword] ] [-InputObject] [[-Path] ] [[-FilePath] ] [[-Type] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Backs up all certs to C:\\temp PS C:\\> Get-DbaComputerCertificate | Backup-DbaComputerCertificate -Path C:\\temp Backs up all certs to C:\\temp. Auto-names the files. Example 2: Backs up certificate with the thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 to the temp directory PS C:\\> Get-DbaComputerCertificate -Thumbprint 29C469578D6C6211076A09CEE5C5797EEA0C2713 | Backup-DbaComputerCertificate -FilePath C:\\temp\\29C469578D6C6211076A09CEE5C5797EEA0C2713.cer Required Parameters -InputObject The certificate objects to export, typically from Get-DbaComputerCertificate pipeline output. Use this to specify which certificates to backup for SQL Server network encryption recovery scenarios. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SecurePassword Provides password protection for certificate exports, required when exporting private keys with Pfx format. Essential for securing certificate backups that contain private keys used for SQL Server TLS encryption. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the target directory where certificate files will be saved with auto-generated filenames. Files are named using the pattern: ComputerName-Thumbprint.cer for easy identification during recovery. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $pwd | -FilePath Specifies the exact file path and name for the exported certificate. Use this when you need to control the output filename or when backing up a single certificate to a specific location. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Determines the certificate export format for different backup and deployment scenarios. Use 'Cert' for public key only backups, 'Pfx' for complete certificate with private key backup, or other formats based on your security requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Cert | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns one FileInfo object per certificate that was successfully exported. This represents the certificate file created on disk. Properties: Name: The filename of the exported certificate (e.g., ComputerName-Thumbprint.cer) FullName: The complete path to the exported certificate file DirectoryName: The directory where the certificate file is stored Directory: The DirectoryInfo object of the parent directory Extension: The file extension (.cer, .pfx, etc., based on Type parameter) Length: The size of the exported certificate file in bytes CreationTime: When the certificate file was created LastWriteTime: When the certificate file was last written Attributes: File attributes (Archive, Normal, etc.) &nbsp;"
  },
  {
    "name": "Backup-DbaDatabase",
    "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's 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.",
    "category": "Backup & Restore",
    "tags": [
      "disasterrecovery",
      "backup",
      "restore"
    ],
    "verb": "Backup",
    "popular": true,
    "url": "/Backup-DbaDatabase",
    "popularityRank": 5,
    "synopsis": "Creates database backups with flexible destination options and enterprise backup features.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Backup-DbaDatabase View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates database backups with flexible destination options and enterprise backup features. 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's 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. Syntax Backup-DbaDatabase [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-Path ] [-FilePath ] [-IncrementPrefix] [-ReplaceInName] [-NoAppendDbNameInPath] [-CopyOnly] [-Type ] [-CreateFolder] [-FileCount ] [-CompressBackup] [-Checksum] [-Verify] [-MaxTransferSize ] [-BlockSize ] [-BufferCount ] [-StorageBaseUrl ] [-StorageCredential ] [-StorageRegion ] [-NoRecovery] [-BuildPath] [-WithFormat] [-Initialize] [-SkipTapeHeader] [-TimeStampFormat ] [-IgnoreFileChecks] [-OutputScriptOnly] [-EncryptionAlgorithm ] [-EncryptionCertificate ] [-Description ] [-EnableException] [-WhatIf] [-Confirm] [ ] Backup-DbaDatabase -SqlInstance [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-Path ] [-FilePath ] [-IncrementPrefix] [-ReplaceInName] [-NoAppendDbNameInPath] [-CopyOnly] [-Type ] [-CreateFolder] [-FileCount ] [-CompressBackup] [-Checksum] [-Verify] [-MaxTransferSize ] [-BlockSize ] [-BufferCount ] [-StorageBaseUrl ] [-StorageCredential ] [-StorageRegion ] [-NoRecovery] [-BuildPath] [-WithFormat] [-Initialize] [-SkipTapeHeader] [-TimeStampFormat ] [-IgnoreFileChecks] [-OutputScriptOnly] [-EncryptionAlgorithm ] [-EncryptionCertificate ] [-Description ] [-EnableException] [-WhatIf] [-Confirm] [ ] Backup-DbaDatabase [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-Path ] [-FilePath ] [-IncrementPrefix] [-ReplaceInName] [-NoAppendDbNameInPath] [-CopyOnly] [-Type ] -InputObject [-CreateFolder] [-FileCount ] [-CompressBackup] [-Checksum] [-Verify] [-MaxTransferSize ] [-BlockSize ] [-BufferCount ] [-StorageBaseUrl ] [-StorageCredential ] [-StorageRegion ] [-NoRecovery] [-BuildPath] [-WithFormat] [-Initialize] [-SkipTapeHeader] [-TimeStampFormat ] [-IgnoreFileChecks] [-OutputScriptOnly] [-EncryptionAlgorithm ] [-EncryptionCertificate ] [-Description ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: This will perform a full database backup on the databases HR and Finance on SQL Server Instance Server1 to... PS C:\\> Backup-DbaDatabase -SqlInstance Server1 -Database HR, Finance This will perform a full database backup on the databases HR and Finance on SQL Server Instance Server1 to Server1 default backup directory. Example 2: Backs up AdventureWorks2014 to sql2016 C:\\temp folder PS C:\\> Backup-DbaDatabase -SqlInstance sql2016 -Path C:\\temp -Database AdventureWorks2014 -Type Full Example 3: Performs a full backup of all databases on the sql2016 instance to their own containers under the... PS C:\\> Backup-DbaDatabase -SqlInstance sql2016 -StorageBaseUrl https://dbatoolsaz.blob.core.windows.net/azbackups/ -StorageCredential dbatoolscred -Type Full -CreateFolder Performs 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 credential \"dbatoolscred\" registered on the sql2016 instance. Example 4: Performs a full backup of all databases on the sql2016 instance to the... PS C:\\> Backup-DbaDatabase -SqlInstance sql2016 -AzureBaseUrl https://dbatoolsaz.blob.core.windows.net/azbackups/ -Type Full Performs 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 credential \"https://dbatoolsaz.blob.core.windows.net/azbackups\" registered on the sql2016 instance. Example 5: Performs a full backup of db1 into the folder \\\\filestore\\backups\\server1\\prod\\db1\\Full PS C:\\> Backup-DbaDatabase -SqlInstance Server1\\Prod -Database db1 -Path \\\\filestore\\backups\\servername\\instancename\\dbname\\backuptype -Type Full -ReplaceInName Example 6: Performs a log backup for every database PS C:\\> Backup-DbaDatabase -SqlInstance Server1\\Prod -Path \\\\filestore\\backups\\servername\\instancename\\dbname\\backuptype -FilePath dbname-backuptype-timestamp.trn -Type Log -ReplaceInName Performs 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 Example 7: Performs a backup of master, but sends the output to the NUL device (ie; throws it away) PS C:\\> Backup-DbaDatabase -SqlInstance Sql2017 -Database master -FilePath NUL Example 8: Performs a backup of the database stripetest, striping it across the 2 Azure blob containers at... PS C:\\> Backup-DbaDatabase -SqlInstance Sql2016 -Database stripetest -AzureBaseUrl https://az.blob.core.windows.net/sql,https://dbatools.blob.core.windows.net/sql Performs 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 Shared Access Signature credentials for both containers exist on the source instance Example 9: Backs up the master database using the BackupCert certificate and the AES256 algorithm PS C:\\> Backup-DbaDatabase -SqlInstance Sql2017 -Database master -EncryptionAlgorithm AES256 -EncryptionCertificate BackupCert Example 10: Performs a full compressed backup of the AdventureWorks database to an S3-compatible storage bucket PS C:\\> Backup-DbaDatabase -SqlInstance sql2022 -Database AdventureWorks -StorageBaseUrl \"s3://mybucket.s3.us-west-2.amazonaws.com/backups\" -Type Full -CompressBackup Performs 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 New-DbaCredential using Identity 'S3 Access Key'. Example 11: Performs a full backup to a MinIO S3-compatible storage server using the S3BaseUrl alias PS C:\\> Backup-DbaDatabase -SqlInstance sql2022 -Database AdventureWorks -S3BaseUrl \"s3://minio.local:9000/sqlbackups\" -Type Full Performs 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. Example 12: Performs a full backup to S3 with explicit region specification and a 10MB transfer size PS C:\\> Backup-DbaDatabase -SqlInstance sql2022 -Database AdventureWorks -StorageBaseUrl \"s3://mybucket.s3.amazonaws.com/backups\" -StorageRegion \"us-west-2\" -MaxTransferSize 10485760 -Type Full Performs 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. Required Parameters -SqlInstance The SQL Server instance hosting the databases to be backed up. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from pipeline for backup operations. Allows piping databases from Get-DbaDatabase or other dbatools commands. Internal parameter primarily used for pipeline processing and automation scenarios. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to include in the backup operation. Accepts database names, wildcards, or arrays. When omitted, all user databases are backed up (tempdb is automatically excluded). Use this to target specific databases instead of backing up the entire instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to exclude from the backup operation. Accepts database names, wildcards, or arrays. Useful when you want to backup most databases but skip specific ones like test or temporary databases. Combined with Database parameter, exclusions are applied after inclusions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Sets the directory path where backup files will be created. Defaults to the instance's default backup location. Multiple paths enable striping for improved performance and overrides FileCount parameter. SQL Server creates missing directories automatically if it has permissions. Striped files are numbered x-of-y for set identification. | Property | Value | | --- | --- | | Alias | BackupDirectory | | Required | False | | Pipeline | false | | Default Value | | -FilePath Specifies the complete backup file name including extension. Only valid for single database backups. When omitted, files are auto-named as DatabaseName_yyyyMMddHHmm with appropriate extensions (.bak, .trn, .dif). Repeated use appends to the same file at incrementing positions. Use 'NUL' to discard backup output for testing. All paths are relative to the SQL Server instance, not the local machine running the command. | Property | Value | | --- | --- | | Alias | BackupFileName | | Required | False | | Pipeline | false | | Default Value | | -IncrementPrefix Prefixes backup files with incremental numbers (1-, 2-, etc.) when striping across multiple files. Primarily used for Azure SQL Database platforms where this naming convention may improve restore performance. Only applies when FileCount is greater than 1 or multiple paths are specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ReplaceInName Enables dynamic token replacement in file paths and names for flexible backup naming schemes. Replaces: instancename, servername, dbname, timestamp, backuptype with actual values. Essential for standardized backup naming across environments and automated backup scripts with consistent file organization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoAppendDbNameInPath Prevents automatic database name folder creation when using CreateFolder parameter. By default, CreateFolder adds a database-specific subdirectory for organization. Use this when you want files directly in the specified path without database name folders. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CopyOnly Creates copy-only backups that don't break the restore chain or affect log backup sequences. Essential for ad-hoc backups during maintenance, before major changes, or for moving databases to other environments. Copy-only backups don't reset differential bases or interfere with scheduled backup strategies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Type Specifies the backup type to perform: Full, Log, Differential, or Database (same as Full). Log backups require full recovery model and prior full backup. Differential backups require prior full backup. Choose based on your recovery objectives and backup strategy requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Database | | Accepted Values | Full,Log,Differential,Diff,Database | -CreateFolder Creates a separate subdirectory for each database within the backup path for better organization. Results in paths like 'BackupPath\\DatabaseName\\BackupFile.bak' instead of all files in one directory. Particularly useful for multi-database backups and maintaining organized backup directory structures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FileCount Specifies the number of files to stripe the backup across for improved performance. Higher values increase backup speed but require more disk space and coordination during restores. Automatically overridden when multiple Path values are provided. Typically use 2-4 files for optimal performance. When using a single StorageBaseUrl (S3/Azure), an explicit FileCount allows striping multiple backup files into the same bucket/container. Multiple StorageBaseUrl values determine the stripe count. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -CompressBackup Forces backup compression when supported by SQL Server edition and version (Enterprise/Standard 2008+). Reduces backup file size by 50-80% but increases CPU usage during backup operations. When omitted, uses server default compression setting. Explicitly false disables compression entirely. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Checksum Enables backup checksum calculation to detect backup corruption during creation and restore. Adds minimal overhead but provides important data integrity verification for critical backups. Recommended for production environments to ensure backup reliability and early corruption detection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Verify Performs RESTORE VERIFYONLY after backup completion to confirm backup integrity and restorability. Adds time to backup operations but ensures backups are usable before considering the job complete. Critical for validating backups in automated processes and compliance requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MaxTransferSize Controls the size of each data transfer unit during backup operations. Must be a multiple of 64KB. For disk and Azure backups: Maximum value is 4MB. For S3 backups: Value must be between 5MB and 20MB (required for S3-compatible storage). Larger values can improve performance for fast storage but may cause memory pressure. Automatically set to 128KB for TDE-encrypted databases with compression to avoid conflicts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BlockSize Sets the physical block size for backup devices. Must be 0.5KB, 1KB, 2KB, 4KB, 8KB, 16KB, 32KB, or 64KB. Affects backup file structure and restore performance. Larger blocks may improve performance for fast storage. Cannot be used with Azure page blob backups (when StorageCredential is specified). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BufferCount Specifies the number of I/O buffers allocated for the backup operation. More buffers can improve performance on fast storage but consume additional memory. SQL Server calculates optimal values automatically, so specify only when performance tuning specific scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -StorageBaseUrl Specifies cloud storage URLs for backup destinations, supporting Azure Blob Storage and S3-compatible object storage. For Azure: Use https:// URLs like 'https://account.blob.core.windows.net/container'. Single URL required for page blobs (with StorageCredential), multiple URLs supported for block blobs with SAS. For S3: Use s3:// URLs like 's3://bucket.s3.region.amazonaws.com/folder'. Requires SQL Server 2022 or later. Supports AWS S3, MinIO, and other S3-compatible providers. Requires corresponding SQL Server credentials for authentication. Essential for backing up to cloud storage for cloud-native or hybrid SQL Server deployments. | Property | Value | | --- | --- | | Alias | AzureBaseUrl,S3BaseUrl | | Required | False | | Pipeline | false | | Default Value | | -StorageCredential Specifies the SQL Server credential name for cloud storage authentication. For Azure: The credential for storage access key authentication. Creates page blob backups with automatic single-file restriction and ignores BlockSize/MaxTransferSize. For S3: The credential containing the S3 Access Key ID and Secret Key ID. The credential name should match the S3 URL path. For SAS authentication, use credentials named to match the StorageBaseUrl. | Property | Value | | --- | --- | | Alias | AzureCredential,S3Credential | | Required | False | | Pipeline | false | | Default Value | | -StorageRegion Specifies the AWS region for S3 backups using the BACKUP_OPTIONS JSON parameter. Only applies to S3-compatible storage. Use this when your S3 bucket is in a specific region that differs from the default, or when required by your S3-compatible provider. Example regions: us-east-1, us-west-2, eu-west-1, ap-southeast-1. When specified, adds BACKUP_OPTIONS = '{\"s3\": {\"region\":\" \"}}' to the backup command. | Property | Value | | --- | --- | | Alias | S3Region | | Required | False | | Pipeline | false | | Default Value | | -NoRecovery Performs transaction log backup without truncating the log, leaving database in restoring state. Essential for tail-log backups during disaster recovery or before restoring to a point in time. Only applicable to log backups and prevents normal database operations until recovery is completed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BuildPath Enables automatic creation of missing directory paths when SQL Server has permissions. By default, the function expects backup paths to exist and will fail if they don't. Useful for automated backup scripts where destination folders might not exist yet. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WithFormat Formats the backup media before writing, destroying any existing backup sets on the device. Automatically enables Initialize and SkipTapeHeader options for complete media initialization. Use when starting fresh backup sets or when media corruption requires reformatting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Initialize Overwrites existing backup sets on the media to start a new backup set. Destroys all previous backups on the target files/devices but preserves media formatting. Use when you want to replace old backups without formatting the entire media. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SkipTapeHeader Skips tape header information during backup operations, primarily for compatibility. Mainly relevant for tape devices and legacy backup scenarios. Automatically enabled with WithFormat parameter for proper media initialization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -TimeStampFormat Customizes the timestamp format used in auto-generated backup file names. Defaults to yyyyMMddHHmm. Must use valid Get-Date format strings (e.g., 'yyyy-MM-dd_HH-mm-ss' for readable timestamps). Applied when FilePath is not specified and ReplaceInName contains 'timestamp' placeholder. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IgnoreFileChecks Skips path validation checks before backup operations, useful when SQL Server has limited filesystem access. Bypasses safety checks that normally prevent backup failures due to permissions or missing paths. Use with caution as it may result in backup failures that could have been prevented. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -OutputScriptOnly Generates and returns the T-SQL BACKUP commands without executing them. Useful for reviewing backup commands, incorporating into scripts, or troubleshooting backup parameter combinations. No actual backup operations occur and no paths are created when using this option. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EncryptionAlgorithm Specifies the encryption algorithm for backup encryption: AES128, AES192, AES256, or TRIPLEDES. Requires either EncryptionCertificate or EncryptionKey for the encryption process. AES256 recommended for maximum security, though it may impact backup performance on older hardware. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | AES128,AES192,AES256,TRIPLEDES | -EncryptionCertificate Specifies the certificate name in the master database for backup encryption. Certificate existence is validated before backup begins to prevent failures mid-operation. Mutually exclusive with EncryptionKey. Essential for protecting sensitive data in backup files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Description Adds a description to the backup set metadata for documentation and identification purposes. Limited to 255 characters and stored in MSDB backup history for backup set identification. Useful for tracking backup purposes, change sets, or special circumstances around the backup timing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Dataplat.Dbatools.Database.BackupHistory Returns one backup history object per database backed up. When -OutputScriptOnly is specified, returns the T-SQL BACKUP command string(s) instead. Default display properties (via Select-DefaultView): SqlInstance: The full SQL Server instance name (computer\\instance) Database: Database name Type: Backup type (Full, Differential, or Log) TotalSize: Total backup size in bytes DeviceType: Backup destination device type (Disk, Tape, URL, Virtual Device, etc.) Duration: Time span of the backup operation Additional properties available on all BackupHistory objects: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name DatabaseId: System object ID of the database UserName: SQL login that performed the backup Start: DateTime when backup started End: DateTime when backup completed Path: Array of physical file paths where backup files were written CompressedBackupSize: Size of compressed backup in bytes (if compression was used) CompressionRatio: Ratio of uncompressed to compressed size BackupSetId: Unique identifier for the backup set MediaSetId: Unique identifier for the media set Position: Backup set position on the media FirstLsn: First Log Sequence Number in the backup DatabaseBackupLsn: Database backup LSN CheckpointLsn: Checkpoint LSN LastLsn: Last Log Sequence Number in the backup SoftwareVersionMajor: SQL Server major version that created the backup Software: Software name and version (e.g., \"Microsoft SQL Server 2019\") IsCopyOnly: Boolean indicating if this is a copy-only backup LastRecoveryForkGuid: GUID of the recovery fork at backup time RecoveryModel: Database recovery model at backup time (Simple, Full, or BulkLogged) EncryptorType: Type of encryption used (ServerCertificate, ServerAsymmetricKey, or None) EncryptorThumbprint: Certificate or key thumbprint if encrypted KeyAlgorithm: Encryption algorithm used (AES128, AES192, AES256, or TRIPLEDES) BackupComplete: Boolean indicating if the backup operation completed successfully BackupFile: The filename(s) of the backup file(s) created BackupFilesCount: Number of striped backup files created BackupFolder: Parent directory path where backup files were created BackupPath: Full path(s) to the backup file(s) created Script: T-SQL BACKUP command that was executed FileList: Array of data and log files that were backed up (only when Verify is used) Verified: Boolean indicating if backup verification passed (only when Verify is used) Notes: Warning or error messages from the backup operation When -OutputScriptOnly is specified, the command returns a System.String containing the T-SQL BACKUP statement without performing the backup operation. &nbsp;"
  },
  {
    "name": "Backup-DbaDbCertificate",
    "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's default backup directory unless a custom path is specified.",
    "category": "Backup & Restore",
    "tags": [
      "certbackup",
      "certificate",
      "backup"
    ],
    "verb": "Backup",
    "popular": false,
    "url": "/Backup-DbaDbCertificate",
    "popularityRank": 130,
    "synopsis": "Exports database certificates and private keys to physical backup files on SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Backup-DbaDbCertificate View Source Jess Pomfret (@jpomfret) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports database certificates and private keys to physical backup files on SQL Server instances. 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's default backup directory unless a custom path is specified. Syntax Backup-DbaDbCertificate [-SqlCredential ] [-EncryptionPassword ] [-DecryptionPassword ] [-Path ] [-Suffix ] [-FileBaseName ] [-EnableException] [-WhatIf] [-Confirm] [ ] Backup-DbaDbCertificate -SqlInstance [-SqlCredential ] [-Certificate ] [-Database ] [-ExcludeDatabase ] [-EncryptionPassword ] [-DecryptionPassword ] [-Path ] [-Suffix ] [-FileBaseName ] [-EnableException] [-WhatIf] [-Confirm] [ ] Backup-DbaDbCertificate [-SqlCredential ] [-EncryptionPassword ] [-DecryptionPassword ] [-Path ] [-Suffix ] [-FileBaseName ] [-InputObject ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Exports all the certificates on the specified SQL Server to the default data path for the instance PS C:\\> Backup-DbaDbCertificate -SqlInstance Server1 Example 2: Connects using sqladmin credential and exports all the certificates on the specified SQL Server to the... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Backup-DbaDbCertificate -SqlInstance Server1 -SqlCredential $cred Connects using sqladmin credential and exports all the certificates on the specified SQL Server to the default data path for the instance. Example 3: Exports only the certificate named Certificate1 on the specified SQL Server to the default data path for the... PS C:\\> Backup-DbaDbCertificate -SqlInstance Server1 -Certificate Certificate1 Exports only the certificate named Certificate1 on the specified SQL Server to the default data path for the instance. Example 4: Exports only the certificates for AdventureWorks on the specified SQL Server to the default data path for the... PS C:\\> Backup-DbaDbCertificate -SqlInstance Server1 -Database AdventureWorks Exports only the certificates for AdventureWorks on the specified SQL Server to the default data path for the instance. Example 5: Exports all certificates except those for AdventureWorks on the specified SQL Server to the default data path... PS C:\\> Backup-DbaDbCertificate -SqlInstance Server1 -ExcludeDatabase AdventureWorks Exports all certificates except those for AdventureWorks on the specified SQL Server to the default data path for the instance. Example 6: Exports all the certificates and private keys on the specified SQL Server PS C:\\> Backup-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates -EncryptionPassword (Get-Credential NoUsernameNeeded).Password Example 7: Exports all the certificates on the specified SQL Server using the supplied DecryptionPassword, since an... PS C:\\> $EncryptionPassword = (Get-Credential NoUsernameNeeded).Password PS C:\\> $DecryptionPassword = (Get-Credential NoUsernameNeeded).Password PS C:\\> Backup-DbaDbCertificate -SqlInstance Server1 -EncryptionPassword $EncryptionPassword -DecryptionPassword $DecryptionPassword Exports all the certificates on the specified SQL Server using the supplied DecryptionPassword, since an EncryptionPassword is specified private keys are also exported. Example 8: Exports all certificates on the specified SQL Server to the specified path PS C:\\> Backup-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates Example 9: Exports all certificates on the specified SQL Server to the specified path, appends DbaTools to the end of... PS C:\\> Backup-DbaDbCertificate -SqlInstance Server1 -Suffix DbaTools Exports all certificates on the specified SQL Server to the specified path, appends DbaTools to the end of the filenames. Example 10: Exports all certificates found on sql2016 to the default data directory PS C:\\> Get-DbaDbCertificate -SqlInstance sql2016 | Backup-DbaDbCertificate Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Certificate Specifies the names of specific certificates to export instead of backing up all certificates on the instance. Use this when you only need to backup certain certificates, such as TDE certificates or specific application certificates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Limits the backup operation to certificates associated with specific databases only. Use this when you need to backup certificates for particular databases, especially before database migrations or when creating targeted disaster recovery plans. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases whose certificates should be excluded from the backup operation. Use this to skip system databases or test databases when performing bulk certificate exports across the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EncryptionPassword Secure password used to encrypt the private key (.pvk) file during export, enabling backup of both certificate and private key components. Required when you need to backup the private key for disaster recovery scenarios where the certificate must be restored with the ability to decrypt data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DecryptionPassword Password required to decrypt the certificate's existing private key before it can be re-encrypted for backup. Use this when the certificate was created with a password or imported from another source that had password protection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Directory path on the SQL Server where certificate backup files will be saved, specified from the SQL Server's perspective. Defaults to the instance's backup directory if not specified. Use UNC paths for network storage or local paths accessible by the SQL Server service account. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Suffix Text appended to the end of backup file names to help organize or identify different backup sets. Use this to distinguish between different backup runs or environments, such as \"Prod\" or \"DR-Test\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileBaseName Custom base name for the backup files instead of the default \"instance-database-certificate\" naming format. Use this when exporting a single certificate and you want specific file names for easier identification or scripted restore processes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Certificate objects piped from Get-DbaDbCertificate for processing specific certificates found by that command. Use this parameter when you need to filter or validate certificates before backing them up. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per certificate that was successfully exported. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the certificate DatabaseID: The unique identifier of the database Certificate: The name of the certificate that was backed up Path: The file path where the certificate (.cer file) was saved Key: The file path where the private key (.pvk file) was saved, or a message if not exported Status: Result status of the export operation (Success or error message) Additional properties available: ExportPath: Same as Path property ExportKey: Same as Key property exportPathCert: Internal property - same as Path exportPathKey: Internal property - same as Key &nbsp;"
  },
  {
    "name": "Backup-DbaDbMasterKey",
    "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's default backup directory or a specified path. Each backup file uses a unique naming convention to prevent overwrites during multiple exports.",
    "category": "Backup & Restore",
    "tags": [
      "certbackup",
      "certificate",
      "backup"
    ],
    "verb": "Backup",
    "popular": false,
    "url": "/Backup-DbaDbMasterKey",
    "popularityRank": 179,
    "synopsis": "Exports database master keys to encrypted backup files for disaster recovery and compliance.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Backup-DbaDbMasterKey View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports database master keys to encrypted backup files for disaster recovery and compliance. 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. This 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. Works with databases that contain master keys and saves backup files to the server's default backup directory or a specified path. Each backup file uses a unique naming convention to prevent overwrites during multiple exports. Syntax Backup-DbaDbMasterKey [[-SqlInstance] ] [[-SqlCredential] ] [[-Credential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-SecurePassword] ] [[-Path] ] [[-FileBaseName] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Prompts for export password, then logs into server1\\sql2016 with Windows credentials then backs up all... PS C:\\> Backup-DbaDbMasterKey -SqlInstance server1\\sql2016 >> ComputerName : SERVER1 >> InstanceName : SQL2016 >> SqlInstance : SERVER1\\SQL2016 >> Filename : E:\\MSSQL13.SQL2016\\MSSQL\\Backup\\server1$sql2016-SMK-20170614162311.key >> Status : Success Prompts for export password, then logs into server1\\sql2016 with Windows credentials then backs up all database keys to the default backup directory. Example 2: Logs into sql2016 with Windows credentials then backs up db1&#39;s keys to the \\\\nas\\sqlbackups\\keys directory PS C:\\> Backup-DbaDbMasterKey -SqlInstance Server1 -Database db1 -Path \\\\nas\\sqlbackups\\keys Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Pass a credential object for the password | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to export master keys from. Only databases containing master keys will be processed. Use this when you need to backup encryption keys from specific databases rather than all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from master key backup operations. Auto-completes with available database names. Useful when backing up master keys from most databases but skipping test, development, or non-encrypted databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecurePassword Password used to encrypt the exported master key backup files. Must be provided as a SecureString object. This password will be required when restoring the master keys, so store it securely with your backup documentation. If not specified, you'll be prompted to enter the password interactively for each database. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -Path Directory path where master key backup files will be saved. Accepts local paths or UNC network shares. Defaults to the SQL Server instance's configured backup directory if not specified. The SQL Server service account must have write permissions to the specified location. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileBaseName Overrides the default file naming convention with a custom base name for the backup file. Useful when exporting a single database's master key and you want a specific filename for documentation or automation. The \".key\" extension is automatically appended to whatever name you specify. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase or other dbatools database commands. Allows you to filter databases using Get-DbaDatabase parameters before piping to this function for master key backup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.MasterKey Returns one MasterKey object per database that was successfully backed up. Each object is enhanced with additional properties describing the backup operation result. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database containing the master key Path: The full file path where the master key backup was saved Status: Result of the backup operation (\"Success\" or \"Failure\") Additional properties available (added by this function): DatabaseID: The ID (GUID) of the database containing the master key Filename: The complete file path where the master key backup was exported All properties from the base SMO MasterKey object are also accessible: CreateDate: DateTime when the master key was created DateLastModified: DateTime when the master key was last modified IsEncryptedByServer: Boolean indicating if the master key is encrypted by the server master key &nbsp;"
  },
  {
    "name": "Backup-DbaServiceMasterKey",
    "description": "Creates an encrypted backup of the SQL Server Service Master Key (SMK), which sits at the top of SQL Server's 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.",
    "category": "Backup & Restore",
    "tags": [
      "certbackup",
      "certificate",
      "backup"
    ],
    "verb": "Backup",
    "popular": false,
    "url": "/Backup-DbaServiceMasterKey",
    "popularityRank": 227,
    "synopsis": "Exports SQL Server Service Master Key to an encrypted backup file for disaster recovery.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Backup-DbaServiceMasterKey View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports SQL Server Service Master Key to an encrypted backup file for disaster recovery. Description Creates an encrypted backup of the SQL Server Service Master Key (SMK), which sits at the top of SQL Server's 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. Syntax Backup-DbaServiceMasterKey [-SqlInstance] [[-SqlCredential] ] [[-KeyCredential] ] [[-SecurePassword] ] [[-Path] ] [[-FileBaseName] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Prompts for export password, then logs into server1\\sql2016 with Windows credentials then backs up the... PS C:\\> Backup-DbaServiceMasterKey -SqlInstance server1\\sql2016 >> ComputerName : SERVER1 >> InstanceName : SQL2016 >> SqlInstance : SERVER1\\SQL2016 >> Filename : E:\\MSSQL13.SQL2016\\MSSQL\\Backup\\server1$sql2016-SMK-20170614162311.key >> Status : Success Prompts for export password, then logs into server1\\sql2016 with Windows credentials then backs up the service master key to the default backup directory. Example 2: Logs into sql2016 with Windows credentials then backs up the service master key to the \\\\nas\\sqlbackups\\keys... PS C:\\> Backup-DbaServiceMasterKey -SqlInstance Server1 -Path \\\\nas\\sqlbackups\\keys Logs into sql2016 with Windows credentials then backs up the service master key to the \\\\nas\\sqlbackups\\keys directory. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -KeyCredential Provides an alternative way to pass the encryption password using a PowerShell credential object. Use this when you need to automate the backup process without interactive password prompts or when integrating with credential management systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecurePassword Sets the password used to encrypt the Service Master Key backup file. Must be provided as a SecureString object for security. If not specified, you'll be prompted to enter the password interactively. Store this password securely as it's required to restore the Service Master Key during disaster recovery. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory where the Service Master Key backup file will be created. Defaults to the SQL Server instance's configured backup directory if not specified. Use this when you need to store the backup in a specific location for compliance, network storage, or organizational requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need predictable file names for automation scripts or when following specific naming standards in your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.ServiceMasterKey Returns one ServiceMasterKey object per instance provided as input. The object includes added properties tracking the backup operation results. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Path: The full file path where the Service Master Key backup was exported Status: Result of the backup operation (Success or Failure) Additional properties available from the base SMO ServiceMasterKey object and added NoteProperties: Filename: Alias for Path - the full file path where the Service Master Key backup was exported All other properties from the SMO ServiceMasterKey object are accessible via Select-Object * &nbsp;"
  },
  {
    "name": "Clear-DbaConnectionPool",
    "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",
    "category": "Utilities",
    "tags": [
      "diagnostic",
      "connection"
    ],
    "verb": "Clear",
    "popular": false,
    "url": "/Clear-DbaConnectionPool",
    "popularityRank": 172,
    "synopsis": "Clears all SQL Server connection pools on the specified computer to resolve connection issues.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Clear-DbaConnectionPool View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Clears all SQL Server connection pools on the specified computer to resolve connection issues. 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. Connection 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. Active 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. Ref: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.clearallpools(v=vs.110).aspx Syntax Clear-DbaConnectionPool [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Clears all local connection pools PS C:\\> Clear-DbaConnectionPool Example 2: Clears all connection pools on workstation27 PS C:\\> Clear-DbaConnectionPool -ComputerName workstation27 Optional Parameters -ComputerName Specifies the computer(s) where SQL Server connection pools should be cleared. Accepts multiple computer names and supports pipeline input. Use this when connection pool issues are occurring on specific client machines or application servers connecting to SQL Server. Defaults to the local computer if not specified. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Alternate credential object to use for accessing the target computer(s). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs None This command does not return any output. It performs an action to clear connection pools on the specified computer(s) and completes silently on success. &nbsp;"
  },
  {
    "name": "Clear-DbaLatchStatistics",
    "description": "Clears all accumulated latch statistics from the sys.dm_os_latch_stats dynamic management view by executing DBCC SQLPERF (N'sys.dm_os_latch_stats', 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.",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "latchstatistic",
      "waits"
    ],
    "verb": "Clear",
    "popular": false,
    "url": "/Clear-DbaLatchStatistics",
    "popularityRank": 375,
    "synopsis": "Resets SQL Server latch statistics counters to establish a fresh performance baseline",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Clear-DbaLatchStatistics View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Resets SQL Server latch statistics counters to establish a fresh performance baseline Description Clears all accumulated latch statistics from the sys.dm_os_latch_stats dynamic management view by executing DBCC SQLPERF (N'sys.dm_os_latch_stats', CLEAR). This resets counters for latch types like BUFFER, ACCESS_METHODS_DATASET_PARENT, and others to zero values. Use 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. Syntax Clear-DbaLatchStatistics [-SqlInstance] [[-SqlCredential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: After confirmation, clears latch statistics on servers sql2008 and sqlserver2012 PS C:\\> Clear-DbaLatchStatistics -SqlInstance sql2008, sqlserver2012 Example 2: Clears latch statistics on servers sql2008 and sqlserver2012, without prompting PS C:\\> Clear-DbaLatchStatistics -SqlInstance sql2008, sqlserver2012 -Confirm:$false Example 3: After confirmation, clears latch statistics on servers sql2008 and sqlserver2012 PS C:\\> 'sql2008','sqlserver2012' | Clear-DbaLatchStatistics Example 4: Connects using sqladmin credential and clears latch statistics on servers sql2008 and sqlserver2012 PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Clear-DbaLatchStatistics -SqlInstance sql2008 -SqlCredential $cred Required Parameters -SqlInstance Allows you to specify a comma separated list of servers to query. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance specified. The object contains the result of clearing latch statistics for that instance. Properties: ComputerName: The computer name of the target SQL Server instance InstanceName: The SQL Server service/instance name SqlInstance: The full SQL Server instance name in domain\\instance format Status: \"Success\" if the DBCC SQLPERF command executed successfully, or an exception object if an error occurred &nbsp;"
  },
  {
    "name": "Clear-DbaPlanCache",
    "description": "Monitors your SQL Server's 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('SQL Plans').\n\nSingle-use plans are a common cause of memory pressure in SQL Server environments with dynamic SQL or applications that don't 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're 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's performance.\n\nReferences: https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "memory"
    ],
    "verb": "Clear",
    "popular": false,
    "url": "/Clear-DbaPlanCache",
    "popularityRank": 333,
    "synopsis": "Clears SQL Server plan cache when single-use adhoc and prepared plans exceed memory threshold",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Clear-DbaPlanCache View Source Tracy Boggiano, databasesuperhero.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Clears SQL Server plan cache when single-use adhoc and prepared plans exceed memory threshold Description Monitors your SQL Server's 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('SQL Plans'). Single-use plans are a common cause of memory pressure in SQL Server environments with dynamic SQL or applications that don't use parameterized queries. Instead of manually checking sys.dm_exec_cached_plans and running DBCC commands, this function automates the detection and cleanup process. Use this when you're 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's performance. References: https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/ Syntax Clear-DbaPlanCache [[-SqlInstance] ] [[-SqlCredential] ] [[-Threshold] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Logs into the SQL Server instance &quot;sql2017&quot; and removes plan caches if over 200 MB PS C:\\> Clear-DbaPlanCache -SqlInstance sql2017 -Threshold 200 Example 2: Logs into the SQL instance using the SQL Login &#39;sqladmin&#39; and then Windows instance as &#39;ad\\sqldba&#39; and... PS C:\\> Clear-DbaPlanCache -SqlInstance sql2017 -SqlCredential sqladmin Logs into the SQL instance using the SQL Login 'sqladmin' and then Windows instance as 'ad\\sqldba' and removes if Threshold over 100 MB. Example 3: Scans localhost for instances using the browser service, traverses all instances and gets the plan cache for... PS C:\\> Find-DbaInstance -ComputerName localhost | Get-DbaPlanCache | Clear-DbaPlanCache -Threshold 200 Scans 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. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Threshold Specifies the memory threshold in megabytes for single-use adhoc and prepared plans before the plan cache is cleared. Default is 100 MB. Use this to control when plan cache cleanup occurs based on your server's memory capacity and workload patterns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 100 | -InputObject Accepts plan cache objects from Get-DbaPlanCache via pipeline input. Each object contains plan cache statistics including memory usage and instance details. Use this to process multiple instances or when you need to filter plan cache results before clearing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per plan cache result processed. The object contains the following properties: ComputerName: The name of the computer running the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The fully qualified SQL Server instance name (computer\\instance) Size: The size of the plan cache (displayed with appropriate units) 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 threshold &nbsp;"
  },
  {
    "name": "Clear-DbaWaitStatistics",
    "description": "Clears all accumulated wait statistics from sys.dm_os_wait_stats by executing DBCC SQLPERF (N'sys.dm_os_wait_stats', 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.",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "waitstats",
      "waits"
    ],
    "verb": "Clear",
    "popular": false,
    "url": "/Clear-DbaWaitStatistics",
    "popularityRank": 313,
    "synopsis": "Resets SQL Server wait statistics to establish a clean monitoring baseline",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Clear-DbaWaitStatistics View Source Chrissy LeMaire (@cl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Resets SQL Server wait statistics to establish a clean monitoring baseline Description Clears all accumulated wait statistics from sys.dm_os_wait_stats by executing DBCC SQLPERF (N'sys.dm_os_wait_stats', 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. Syntax Clear-DbaWaitStatistics [-SqlInstance] [[-SqlCredential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: After confirmation, clears wait stats on servers sql2008 and sqlserver2012 PS C:\\> Clear-DbaWaitStatistics -SqlInstance sql2008, sqlserver2012 Example 2: Clears wait stats on servers sql2008 and sqlserver2012, without prompting PS C:\\> Clear-DbaWaitStatistics -SqlInstance sql2008, sqlserver2012 -Confirm:$false Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance, confirming the operation status. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName) Status: Either \"Success\" if the wait statistics were cleared, or the exception message if the operation failed &nbsp;"
  },
  {
    "name": "Compare-DbaAgReplicaAgentJob",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "availabilitygroup",
      "ag",
      "job",
      "agent"
    ],
    "verb": "Compare",
    "popular": false,
    "url": "/Compare-DbaAgReplicaAgentJob",
    "popularityRank": 0,
    "synopsis": "Compares SQL Agent Jobs across Availability Group replicas to identify configuration differences.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Compare-DbaAgReplicaAgentJob View Source dbatools team Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Compares SQL Agent Jobs across Availability Group replicas to identify configuration differences. 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. This 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. By default, compares job names and their presence/absence. Use -IncludeModifiedDate to also compare DateLastModified timestamps to detect configuration drift. Syntax Compare-DbaAgReplicaAgentJob [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [-ExcludeSystemJob] [-IncludeModifiedDate] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Compares all SQL Agent Jobs across replicas in the AG1 Availability Group PS C:\\> Compare-DbaAgReplicaAgentJob -SqlInstance sql2016 -AvailabilityGroup AG1 Example 2: Compares user-created SQL Agent Jobs across replicas, excluding system jobs PS C:\\> Compare-DbaAgReplicaAgentJob -SqlInstance sql2016 -AvailabilityGroup AG1 -ExcludeSystemJob Example 3: Compares SQL Agent Jobs including their DateLastModified property to detect configuration drift PS C:\\> Compare-DbaAgReplicaAgentJob -SqlInstance sql2016 -AvailabilityGroup AG1 -IncludeModifiedDate Example 4: Compares SQL Agent Jobs for all Availability Groups on sql2016 via pipeline input PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAgReplicaAgentJob Optional Parameters -SqlInstance The target SQL Server instance or instances. Can be any replica in the Availability Group. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies one or more Availability Group names to compare jobs across their replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemJob Excludes system jobs from the comparison results. Use this to focus on user-created jobs and ignore built-in SQL Server jobs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeModifiedDate Includes DateLastModified comparison in addition to job name comparison. Use this to detect when jobs have been reconfigured on some replicas but not others. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 -IncludeModifiedDate is specified). Properties: AvailabilityGroup: The name of the Availability Group being compared Replica: The SQL Server instance name where the job status applies JobName: The name of the SQL Agent job Status: Job status on this replica (either \"Present\" or \"Missing\") 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) &nbsp;"
  },
  {
    "name": "Compare-DbaAgReplicaCredential",
    "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.",
    "category": "Security",
    "tags": [
      "availabilitygroup",
      "ag",
      "credential",
      "security"
    ],
    "verb": "Compare",
    "popular": false,
    "url": "/Compare-DbaAgReplicaCredential",
    "popularityRank": 0,
    "synopsis": "Compares SQL Server Credentials across Availability Group replicas to identify configuration differences.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Compare-DbaAgReplicaCredential View Source dbatools team Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Compares SQL Server Credentials across Availability Group replicas to identify configuration differences. 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. This 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. Compares credential names and their associated identities to detect configuration drift. Syntax Compare-DbaAgReplicaCredential [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Compares all SQL Server Credentials across replicas in the AG1 Availability Group PS C:\\> Compare-DbaAgReplicaCredential -SqlInstance sql2016 -AvailabilityGroup AG1 Example 2: Compares SQL Server Credentials for all Availability Groups on sql2016 via pipeline input PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAgReplicaCredential Optional Parameters -SqlInstance The target SQL Server instance or instances. Can be any replica in the Availability Group. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies one or more Availability Group names to compare credentials across their replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per credential that has configuration differences across replicas in the Availability Group. Properties: AvailabilityGroup: The name of the Availability Group being compared Replica: The name of the replica instance where the credential status was checked CredentialName: The name of the SQL Server credential Status: The credential state on this replica (\"Present\" if the credential exists, \"Missing\" if it doesn't) Identity: The credential's identity/principal on replicas where the credential is Present; $null where Status is \"Missing\" Only credentials with differences (missing on at least one replica or having different identities across replicas) are returned. &nbsp;"
  },
  {
    "name": "Compare-DbaAgReplicaLogin",
    "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.",
    "category": "Security",
    "tags": [
      "availabilitygroup",
      "ag",
      "login",
      "security"
    ],
    "verb": "Compare",
    "popular": false,
    "url": "/Compare-DbaAgReplicaLogin",
    "popularityRank": 0,
    "synopsis": "Compares SQL Server logins across Availability Group replicas to identify configuration differences.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Compare-DbaAgReplicaLogin View Source dbatools team Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Compares SQL Server logins across Availability Group replicas to identify configuration differences. 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. This 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. By default, compares login names and their presence/absence. Use -IncludeModifiedDate to also compare modify_date timestamps from sys.server_principals to detect configuration drift. Syntax Compare-DbaAgReplicaLogin [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [-ExcludeSystemLogin] [-IncludeModifiedDate] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Compares all SQL Server logins across replicas in the AG1 Availability Group PS C:\\> Compare-DbaAgReplicaLogin -SqlInstance sql2016 -AvailabilityGroup AG1 Example 2: Compares user-created SQL Server logins across replicas, excluding system logins PS C:\\> Compare-DbaAgReplicaLogin -SqlInstance sql2016 -AvailabilityGroup AG1 -ExcludeSystemLogin Example 3: Compares SQL Server logins including their modify_date property to detect configuration drift PS C:\\> Compare-DbaAgReplicaLogin -SqlInstance sql2016 -AvailabilityGroup AG1 -IncludeModifiedDate Example 4: Compares SQL Server logins for all Availability Groups on sql2016 via pipeline input PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAgReplicaLogin Optional Parameters -SqlInstance The target SQL Server instance or instances. Can be any replica in the Availability Group. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies one or more Availability Group names to compare logins across their replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemLogin Excludes built-in system logins from the comparison results. Use this to focus on user-created logins and ignore built-in SQL Server logins. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeModifiedDate Includes modify_date comparison in addition to login name comparison. Use this to detect when logins have been reconfigured on some replicas but not others. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties: AvailabilityGroup: The name of the Availability Group being compared Replica: The name of the SQL Server replica instance LoginName: The name of the login account Status: Current status of the login on this replica (\"Present\" or \"Missing\") 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) CreateDate: The datetime when the login was created on this replica (null if Status is \"Missing\") When -IncludeModifiedDate is specified, ModifyDate contains the exact modification timestamp from sys.server_principals. Without this switch, ModifyDate may be null in output objects. &nbsp;"
  },
  {
    "name": "Compare-DbaAgReplicaOperator",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "availabilitygroup",
      "ag",
      "operator",
      "agent"
    ],
    "verb": "Compare",
    "popular": false,
    "url": "/Compare-DbaAgReplicaOperator",
    "popularityRank": 0,
    "synopsis": "Compares SQL Agent Operators across Availability Group replicas to identify configuration differences.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Compare-DbaAgReplicaOperator View Source dbatools team Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Compares SQL Agent Operators across Availability Group replicas to identify configuration differences. 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. This 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. Compares operator names and their email addresses to detect configuration drift. Syntax Compare-DbaAgReplicaOperator [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Compares all SQL Agent Operators across replicas in the AG1 Availability Group PS C:\\> Compare-DbaAgReplicaOperator -SqlInstance sql2016 -AvailabilityGroup AG1 Example 2: Compares SQL Agent Operators for all Availability Groups on sql2016 via pipeline input PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAgReplicaOperator Optional Parameters -SqlInstance The target SQL Server instance or instances. Can be any replica in the Availability Group. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies one or more Availability Group names to compare operators across their replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 but missing on others, or present with different email addresses). Properties: AvailabilityGroup: Name of the Availability Group being compared Replica: The SQL Server instance name of the replica OperatorName: Name of the SQL Agent operator Status: Configuration status of the operator on this replica (\"Present\" or \"Missing\") EmailAddress: Email address of the operator (null if Status is \"Missing\") &nbsp;"
  },
  {
    "name": "Compare-DbaAgReplicaSync",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "availabilitygroup",
      "ag",
      "sync",
      "compare"
    ],
    "verb": "Compare",
    "popular": false,
    "url": "/Compare-DbaAgReplicaSync",
    "popularityRank": 0,
    "synopsis": "Compares server-level objects across Availability Group replicas to identify synchronization differences.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Compare-DbaAgReplicaSync View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Compares server-level objects across Availability Group replicas to identify synchronization differences. 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. This 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. By default, compares these object types across all replicas: SpConfigure CustomErrors Credentials DatabaseMail LinkedServers Logins SystemTriggers AgentCategory AgentOperator AgentAlert AgentProxy AgentSchedule AgentJob Any 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. Syntax Compare-DbaAgReplicaSync [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Exclude] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Compares all server-level objects across replicas in the AG1 Availability Group and reports differences PS C:\\> Compare-DbaAgReplicaSync -SqlInstance sql2016 -AvailabilityGroup AG1 Example 2: Compares server-level objects excluding LinkedServers and DatabaseMail configurations PS C:\\> Compare-DbaAgReplicaSync -SqlInstance sql2016 -AvailabilityGroup AG1 -Exclude LinkedServers, DatabaseMail Example 3: Compares server-level objects for all Availability Groups on sql2016 via pipeline input PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAgReplicaSync Example 4: Shows only objects that are missing on one or more replicas PS C:\\> Compare-DbaAgReplicaSync -SqlInstance sql2016 -AvailabilityGroup AG1 | Where-Object Status -eq \"Missing\" Optional Parameters -SqlInstance The target SQL Server instance or instances. Can be any replica in the Availability Group. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies one or more Availability Group names to compare objects across their replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Exclude Excludes specific object types from comparison. Valid values: SpConfigure, CustomErrors, Credentials, DatabaseMail, LinkedServers, Logins, SystemTriggers, AgentCategory, AgentOperator, AgentAlert, AgentProxy, AgentSchedule, AgentJob | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per difference detected across the Availability Group replicas. Each object represents a synchronization discrepancy that would impact failover readiness. Properties: AvailabilityGroup: Name of the Availability Group being compared Replica: Name of the replica where the discrepancy was detected ObjectType: Type of object with the difference (Login, AgentJob, Credential, LinkedServer, AgentOperator, AgentAlert, AgentProxy, CustomError) ObjectName: Name of the specific object that differs 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) 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\") &nbsp;"
  },
  {
    "name": "Compare-DbaAvailabilityGroup",
    "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.",
    "category": "Security",
    "tags": [
      "availabilitygroup",
      "ag",
      "job",
      "login",
      "credential",
      "operator"
    ],
    "verb": "Compare",
    "popular": false,
    "url": "/Compare-DbaAvailabilityGroup",
    "popularityRank": 0,
    "synopsis": "Compares configuration across Availability Group replicas to identify differences in Jobs, Logins, Credentials, and Operators.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Compare-DbaAvailabilityGroup View Source dbatools team Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Compares configuration across Availability Group replicas to identify differences in Jobs, Logins, Credentials, and Operators. 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. This is the main command for comparing AG replica configurations. It can run all comparison checks or specific ones based on the Type parameter. Use 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. Syntax Compare-DbaAvailabilityGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Type] ] [-ExcludeSystemJob] [-ExcludeSystemLogin] [-IncludeModifiedDate] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Compares all object types (Jobs, Logins, Credentials, Operators) across replicas in AG1 PS C:\\> Compare-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 Example 2: Compares only SQL Agent Jobs across replicas in AG1 PS C:\\> Compare-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -Type AgentJob Example 3: Compares SQL Agent Jobs and Logins across replicas in AG1 PS C:\\> Compare-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -Type AgentJob, Login Example 4: Compares all object types including DateLastModified timestamps for jobs and logins PS C:\\> Compare-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -IncludeModifiedDate Example 5: Compares all object types for all Availability Groups on sql2016 via pipeline input PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2016 | Compare-DbaAvailabilityGroup Example 6: Compares all object types excluding system jobs and system logins PS C:\\> Compare-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -ExcludeSystemJob -ExcludeSystemLogin Optional Parameters -SqlInstance The target SQL Server instance or instances. Can be any replica in the Availability Group. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies one or more Availability Group names to compare across their replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies which object types to compare. Valid options are: AgentJob, Login, Credential, Operator, All. Default is All which runs all comparison checks. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | All | | Accepted Values | AgentJob,Login,Credential,Operator,All | -ExcludeSystemJob Excludes system jobs from the agent job comparison. Only applicable when Type includes AgentJob or All. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeSystemLogin Excludes built-in system logins from the login comparison. Only applicable when Type includes Login or All. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeModifiedDate Includes DateLastModified comparison for jobs and modify_date comparison for logins. Only applicable when Type includes AgentJob, Login, or All. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns zero or more objects representing configuration differences detected across Availability Group replicas. The specific properties returned depend on which comparison types are executed (controlled by the -Type parameter). For AgentJob comparisons: AvailabilityGroup: The name of the Availability Group being compared Replica: The SQL Server instance name where the job status applies JobName: The name of the SQL Agent job Status: Job status on this replica (\"Present\" or \"Missing\") DateLastModified: DateTime when the job was last modified, or $null if the job is missing on this replica (only populated when -IncludeModifiedDate is specified) For Login comparisons: AvailabilityGroup: The name of the Availability Group being compared Replica: The name of the SQL Server replica instance LoginName: The name of the login account Status: Current status of the login on this replica (\"Present\" or \"Missing\") ModifyDate: The datetime when the login was last modified on this replica (null if Status is \"Missing\"; only populated when -IncludeModifiedDate is specified) CreateDate: The datetime when the login was created on this replica (null if Status is \"Missing\") For Credential comparisons: AvailabilityGroup: The name of the Availability Group being compared Replica: The name of the replica instance where the credential status was checked CredentialName: The name of the SQL Server credential Status: The credential state on this replica (\"Present\" if the credential exists, \"Missing\" if it doesn't) Identity: The credential's identity/principal on replicas where the credential is Present; $null where Status is \"Missing\" For Operator comparisons: AvailabilityGroup: Name of the Availability Group being compared Replica: The SQL Server instance name of the replica OperatorName: Name of the SQL Agent operator Status: Configuration status of the operator on this replica (\"Present\" or \"Missing\") EmailAddress: Email address of the operator (null if Status is \"Missing\") Only objects representing differences (missing items or differing values when -IncludeModifiedDate is specified) are returned. If all configurations are identical across replicas, no output is generated. &nbsp;"
  },
  {
    "name": "Compare-DbaDbSchema",
    "description": "Uses sqlpackage's DeployReport action to compare a source DACPAC against a target (live database or DACPAC file) and returns a structured list of schema differences.\n\nThe source must be a DACPAC file. The target can be either a live SQL Server database or another DACPAC file.\n\nNote: Comparing two live databases is not supported by sqlpackage. To compare two live databases, first export one as a DACPAC using Export-DbaDacPackage, then pass that DACPAC as the source to this command.\n\nsqlpackage must be available. Install it via Install-DbaSqlPackage if needed.",
    "category": "Utilities",
    "tags": [
      "dacpac",
      "schema",
      "sqlpackage",
      "compare",
      "deployment"
    ],
    "verb": "Compare",
    "popular": false,
    "url": "/Compare-DbaDbSchema",
    "popularityRank": 0,
    "synopsis": "Compares the schema of a DACPAC file against a target database or DACPAC file using sqlpackage.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Compare-DbaDbSchema View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Compares the schema of a DACPAC file against a target database or DACPAC file using sqlpackage. Description Uses sqlpackage's DeployReport action to compare a source DACPAC against a target (live database or DACPAC file) and returns a structured list of schema differences. The source must be a DACPAC file. The target can be either a live SQL Server database or another DACPAC file. Note: Comparing two live databases is not supported by sqlpackage. To compare two live databases, first export one as a DACPAC using Export-DbaDacPackage, then pass that DACPAC as the source to this command. sqlpackage must be available. Install it via Install-DbaSqlPackage if needed. Syntax Compare-DbaDbSchema [-SourcePath] [[-TargetSqlInstance] ] [[-TargetSqlCredential] ] [[-TargetDatabase] ] [[-TargetPath] ] [[-OutputPath] ] [-KeepReport] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Compares the source.dacpac schema against the AdventureWorks database on sql2019 and returns a list of... PS C:\\> Compare-DbaDbSchema -SourcePath C:\\temp\\source.dacpac -TargetSqlInstance sql2019 -TargetDatabase AdventureWorks Compares the source.dacpac schema against the AdventureWorks database on sql2019 and returns a list of differences. Example 2: Compares two DACPAC files offline and returns the schema differences PS C:\\> Compare-DbaDbSchema -SourcePath C:\\temp\\v2.dacpac -TargetPath C:\\temp\\v1.dacpac Example 3: Exports a DACPAC from the source database, then compares it against the target database on the same instance PS C:\\> Export-DbaDacPackage -SqlInstance sql2016 -Database db_source -FilePath C:\\temp\\db_source.dacpac PS C:\\> Compare-DbaDbSchema -SourcePath C:\\temp\\db_source.dacpac -TargetSqlInstance sql2016 -TargetDatabase db_target Example 4: Compares schema and keeps the XML report file in C:\\reports PS C:\\> Compare-DbaDbSchema -SourcePath C:\\temp\\source.dacpac -TargetSqlInstance sql2019 -TargetDatabase AdventureWorks -KeepReport -OutputPath C:\\reports Required Parameters -SourcePath The path to the source DACPAC file to compare from. | Property | Value | | --- | --- | | Alias | Path,FilePath | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -TargetSqlInstance The target SQL Server instance containing the database to compare against. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TargetSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Only SQL authentication is supported. When not specified, uses Trusted Authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TargetDatabase The name of the target database on the target SQL Server instance to compare against. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TargetPath The path to the target DACPAC file to compare against. Use this for offline comparisons between two DACPAC files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OutputPath The directory where the XML deployment report will be saved. Defaults to the configured DbatoolsExport path. The report file is removed after parsing unless -KeepReport is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName \"Path.DbatoolsExport\") | -KeepReport When specified, the generated XML deployment report file is kept after parsing. By default, the file is removed after processing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per schema difference found between source and target. Properties: SourcePath: Full path to the source DACPAC file Target: The target database or DACPAC path Operation: The type of change (e.g., Create, Alter, Drop, Rename) Value: The schema object name (e.g., [dbo].[MyTable]) Type: The object type (e.g., Table, Procedure, View) ReportPath: Full path to the XML deployment report (only present when -KeepReport is specified) &nbsp;"
  },
  {
    "name": "Compare-DbaLogin",
    "description": "Compares SQL Server logins between a source instance and one or more destination instances to identify which logins exist only on the source, only on the destination, or on both. This is useful for identifying logins that would be lost when using Copy-DbaLogin with -Force, or for auditing login consistency between environments.\n\nReturns one object per login per destination instance, indicating whether the login exists on the source, destination, or both.",
    "category": "Security",
    "tags": [
      "login",
      "security",
      "compare"
    ],
    "verb": "Compare",
    "popular": false,
    "url": "/Compare-DbaLogin",
    "popularityRank": 0,
    "synopsis": "Compares SQL Server logins between a source and one or more destination instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Compare-DbaLogin View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Compares SQL Server logins between a source and one or more destination instances. Description Compares SQL Server logins between a source instance and one or more destination instances to identify which logins exist only on the source, only on the destination, or on both. This is useful for identifying logins that would be lost when using Copy-DbaLogin with -Force, or for auditing login consistency between environments. Returns one object per login per destination instance, indicating whether the login exists on the source, destination, or both. Syntax Compare-DbaLogin [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Login] ] [[-ExcludeLogin] ] [-ExcludeSystemLogin] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Compares all logins between sql1 and sql2, returning the status of each login PS C:\\> Compare-DbaLogin -Source sql1 -Destination sql2 Example 2: Returns logins that exist on sql2 but not on sql1 PS C:\\> Compare-DbaLogin -Source sql1 -Destination sql2 | Where-Object Status -eq \"DestinationOnly\" Returns logins that exist on sql2 but not on sql1. These logins would be lost if Copy-DbaLogin -Force were run from sql1 to sql2. Example 3: Returns logins that exist on sql1 but not on sql2 PS C:\\> Compare-DbaLogin -Source sql1 -Destination sql2 | Where-Object Status -eq \"SourceOnly\" Returns logins that exist on sql1 but not on sql2. These are the logins that Copy-DbaLogin would create. Example 4: Compares user-created logins between sql1 and sql2, excluding built-in system logins PS C:\\> Compare-DbaLogin -Source sql1 -Destination sql2 -ExcludeSystemLogin Example 5: Compares the specified logins between sql1 and both sql2 and sql3 PS C:\\> Compare-DbaLogin -Source sql1 -Destination sql2, sql3 -Login \"appuser\", \"reportuser\" Required Parameters -Source The source SQL Server instance. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination The destination SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Login to the source instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login to the destination instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Specifies one or more logins to include in the comparison. All other logins are excluded. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeLogin Specifies one or more logins to exclude from the comparison. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemLogin Excludes built-in system logins from the comparison results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object for each login found on either the source or destination instance. Properties: SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance LoginName: The name of the login account LoginType: The login type (SqlLogin, WindowsUser, WindowsGroup, etc.) Status: Indicates where the login exists - \"SourceOnly\", \"DestinationOnly\", or \"Both\" &nbsp;"
  },
  {
    "name": "Connect-DbaInstance",
    "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'll 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['master'].ExecuteNonQuery($sql)",
    "category": "Server Management",
    "tags": [
      "connection"
    ],
    "verb": "Connect",
    "popular": true,
    "url": "/Connect-DbaInstance",
    "popularityRank": 8,
    "synopsis": "Creates a persistent SQL Server Management Object (SMO) connection for database operations.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Connect-DbaInstance View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a persistent SQL Server Management Object (SMO) connection for database operations. 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. The 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. This is the connection object you'll 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. The 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. For 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. Reference documentation: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx To execute SQL commands directly: $server.ConnectionContext.ExecuteReader($sql) or $server.Databases['master'].ExecuteNonQuery($sql) Syntax Connect-DbaInstance [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ApplicationIntent] ] [-AzureUnsupported] [[-BatchSeparator] ] [[-ClientName] ] [[-ConnectTimeout] ] [-EncryptConnection] [[-FailoverPartner] ] [[-LockTimeout] ] [[-MaxPoolSize] ] [[-MinPoolSize] ] [[-MinimumVersion] ] [-MultipleActiveResultSets] [-MultiSubnetFailover] [[-NetworkProtocol] ] [-NonPooledConnection] [[-PacketSize] ] [[-PooledConnectionLifetime] ] [[-SqlExecutionModes] ] [[-StatementTimeout] ] [-TrustServerCertificate] [-AllowTrustServerCertificate] [[-WorkstationId] ] [-AlwaysEncrypted] [[-AppendConnectionString] ] [-SqlConnectionOnly] [[-AzureDomain] ] [[-Tenant] ] [[-AccessToken] ] [[-AuthenticationType] ] [-DedicatedAdminConnection] [-DisableException] [ ] &nbsp; Examples &nbsp; Example 1: Creates an SMO Server object that connects using Windows Authentication PS C:\\> Connect-DbaInstance -SqlInstance sql2014 Example 2: Creates an SMO Server object that connects using alternative Windows credentials PS C:\\> $wincred = Get-Credential ad\\sqladmin PS C:\\> Connect-DbaInstance -SqlInstance sql2014 -SqlCredential $wincred Example 3: Login to sql2014 as SQL login sqladmin PS C:\\> $sqlcred = Get-Credential sqladmin PS C:\\> $server = Connect-DbaInstance -SqlInstance sql2014 -SqlCredential $sqlcred Example 4: Creates an SMO Server object that connects using Windows Authentication and uses the client name &quot;my... PS C:\\> $server = Connect-DbaInstance -SqlInstance sql2014 -ClientName \"my connection\" Creates an SMO Server object that connects using Windows Authentication and uses the client name \"my connection\". So when you open up profiler or use extended events, you can search for \"my connection\". Example 5: Creates an SMO Server object that connects to sql2014 using Windows Authentication, then it sets the packet... PS C:\\> $server = Connect-DbaInstance -SqlInstance sql2014 -AppendConnectionString \"Packet Size=4096;AttachDbFilename=C:\\MyFolder\\MyDataFile.mdf;User Instance=true;\" Creates 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. Example 6: Creates an SMO Server object that connects using Windows Authentication that uses TCP/IP and has... PS C:\\> $server = Connect-DbaInstance -SqlInstance sql2014 -NetworkProtocol TcpIp -MultiSubnetFailover Creates an SMO Server object that connects using Windows Authentication that uses TCP/IP and has MultiSubnetFailover enabled. Example 7: Connects with ReadOnly ApplicationIntent PS C:\\> $server = Connect-DbaInstance sql2016 -ApplicationIntent ReadOnly Example 8: Logs into Azure SQL DB using AAD / Azure Active Directory, then performs a sample query PS C:\\> $server = Connect-DbaInstance -SqlInstance myserver.database.windows.net -Database mydb -SqlCredential me@mydomain.onmicrosoft.com -DisableException PS C:\\> Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\" Example 9: Logs into Azure SQL DB using AAD Integrated Auth, then performs a sample query PS C:\\> $server = Connect-DbaInstance -SqlInstance psdbatools.database.windows.net -Database dbatools -DisableException PS C:\\> Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\" Example 10: Logs into Azure SQL Managed instance using AAD / Azure Active Directory, then performs a sample query PS C:\\> $server = Connect-DbaInstance -SqlInstance \"myserver.public.cust123.database.windows.net,3342\" -Database mydb -SqlCredential me@mydomain.onmicrosoft.com -DisableException PS C:\\> Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\" Example 11: In the event your AzureSqlDb is not on a database.windows.net domain, you can set a custom domain using the... PS C:\\> $server = Connect-DbaInstance -SqlInstance db.mycustomazure.com -Database mydb -AzureDomain mycustomazure.com -DisableException PS C:\\> Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\" In the event your AzureSqlDb is not on a database.windows.net domain, you can set a custom domain using the AzureDomain parameter. This tells Connect-DbaInstance to login to the database using the method that works best with Azure. Example 12: Logs into Azure using a preconstructed connstring, then performs a sample query PS C:\\> $connstring = \"Data Source=TCP:mydb.database.windows.net,1433;User ID=sqladmin;Password=adfasdf;Connect Timeout=30;\" PS C:\\> $server = Connect-DbaInstance -ConnectionString $connstring PS C:\\> Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\" Logs into Azure using a preconstructed connstring, then performs a sample query. ConnectionString is an alias of SqlInstance, so you can use -SqlInstance $connstring as well. Example 13: When connecting from a non-Azure workstation, logs into Azure using Universal with MFA Support with a... PS C:\\> $cred = Get-Credential guid-app-id-here # appid for username, clientsecret for password PS C:\\> $server = Connect-DbaInstance -SqlInstance psdbatools.database.windows.net -Database abc -SqlCredential $cred -Tenant guidheremaybename PS C:\\> Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\" When connecting from a non-Azure workstation, logs into Azure using Universal with MFA Support with a username and password, then performs a sample query. Note 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. Example 14: Permanently sets some app id config values PS C:\\> $cred = Get-Credential guid-app-id-here # appid for username, clientsecret for password PS C:\\> Set-DbatoolsConfig -FullName azure.tenantid -Value 'guidheremaybename' -Passthru | Register-DbatoolsConfig PS C:\\> Set-DbatoolsConfig -FullName azure.appid -Value $cred.Username -Passthru | Register-DbatoolsConfig PS C:\\> Set-DbatoolsConfig -FullName azure.clientsecret -Value $cred.Password -Passthru | Register-DbatoolsConfig # requires securestring PS C:\\> Set-DbatoolsConfig -FullName sql.connection.database -Value abc -Passthru | Register-DbatoolsConfig PS C:\\> Connect-DbaInstance -SqlInstance psdbatools.database.windows.net Permanently sets some app id config values. To set them temporarily (just for a session), remove -Passthru | Register-DbatoolsConfig When 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. Example 15: Connect to an Azure SQL Database or an Azure SQL Managed Instance with an AccessToken PS C:\\> $azureCredential = Get-Credential -Message 'Azure Credential' PS C:\\> $azureAccount = Connect-AzAccount -Credential $azureCredential PS C:\\> $azureToken = Get-AzAccessToken -ResourceUrl https://database.windows.net PS C:\\> $azureInstance = \"YOURSERVER.database.windows.net\" PS C:\\> $azureDatabase = \"MYDATABASE\" PS C:\\> $server = Connect-DbaInstance -SqlInstance $azureInstance -Database $azureDatabase -AccessToken $azureToken PS C:\\> Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\" Connect to an Azure SQL Database or an Azure SQL Managed Instance with an AccessToken. Works with both Azure PowerShell v13 (string tokens) and v14+ (SecureString tokens). Note that the token is valid for only one hour and cannot be renewed automatically. Example 16: Connect to an Azure SQL Managed Instance using Azure PowerShell v14+ where Get-AzAccessToken returns a... PS C:\\> # Azure PowerShell v14+ with SecureString token support PS C:\\> Connect-AzAccount PS C:\\> $azureToken = (Get-AzAccessToken -ResourceUrl https://database.windows.net).Token PS C:\\> $azureInstance = \"YOUR-AZURE-SQL-MANAGED-INSTANCE.database.windows.net\" PS C:\\> $server = Connect-DbaInstance -SqlInstance $azureInstance -Database \"YOURDATABASE\" -AccessToken $azureToken PS C:\\> Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\" Connect to an Azure SQL Managed Instance using Azure PowerShell v14+ where Get-AzAccessToken returns a SecureString. The function automatically detects and converts the SecureString token to the required format. Example 17: Uses dbatools to generate the access token for an Azure SQL Database, then logs in using that AccessToken PS C:\\> $token = New-DbaAzAccessToken -Type RenewableServicePrincipal -Subtype AzureSqlDb -Tenant $tenantid -Credential $cred PS C:\\> Connect-DbaInstance -SqlInstance sample.database.windows.net -Accesstoken $token Example 18: Creates a dedicated admin connection (DAC) to the default instance on server srv1 PS C:\\> $server = Connect-DbaInstance -SqlInstance srv1 -DedicatedAdminConnection PS C:\\> $dbaProcess = Get-DbaProcess -SqlInstance $server -ExcludeSystemSpids PS C:\\> $killedProcess = $dbaProcess | Out-GridView -OutputMode Multiple | Stop-DbaProcess PS C:\\> $server | Disconnect-DbaInstance Creates a dedicated admin connection (DAC) to the default instance on server srv1. Receives all non-system processes from the instance using the DAC. Opens a grid view to let the user select processes to be stopped. Closes the connection. Example 19: Connects to multiple servers where some may have valid TLS certificates and others may not PS C:\\> $servers = \"sql1\", \"sql2\", \"sql3\" PS C:\\> $servers | Connect-DbaInstance -AllowTrustServerCertificate Connects to multiple servers where some may have valid TLS certificates and others may not. For each server, attempts connection with proper TLS validation first. If a server fails due to certificate validation, automatically retries with TrustServerCertificate enabled. This provides a secure-by-default approach for mixed environments without requiring separate connection logic. Example 20: Connects to a SQL Server instance (Azure SQL VM, Azure SQL Database, Azure SQL Managed Instance, or Fabric... PS C:\\> $server = Connect-DbaInstance -SqlInstance sql01 -AuthenticationType ActiveDirectoryInteractive Connects to a SQL Server instance (Azure SQL VM, Azure SQL Database, Azure SQL Managed Instance, or Fabric SQL Database) using Entra ID (Azure AD) interactive authentication with MFA. A browser dialog will appear prompting you to select your Entra ID account and complete any required MFA steps. Example 21: Connects to an Azure SQL Database using Entra ID interactive authentication with MFA PS C:\\> $server = Connect-DbaInstance -SqlInstance myserver.database.windows.net -Database mydb -AuthenticationType ActiveDirectoryInteractive Connects to an Azure SQL Database using Entra ID interactive authentication with MFA. A browser dialog will appear to complete authentication. Example 22: Connects to a SQL Server instance using Entra ID integrated authentication PS C:\\> $server = Connect-DbaInstance -SqlInstance sql01 -AuthenticationType ActiveDirectoryIntegrated Connects to a SQL Server instance using Entra ID integrated authentication. Uses the currently signed-in Entra ID identity without prompting for credentials. Required Parameters -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. | Property | Value | | --- | --- | | Alias | Connstring,ConnectionString | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -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 are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the initial database context for the connection instead of connecting to the default database. Useful when you need to connect directly to a specific database or when the login's default database is unavailable. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'sql.connection.database') | -ApplicationIntent Declares the application workload type when connecting to an Always On Availability Group. Use \"ReadOnly\" to route connections to readable secondary replicas for reporting workloads, reducing load on the primary replica. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | ReadOnly,ReadWrite | -AzureUnsupported Causes the connection to fail if the target is detected as Azure SQL Database. Use this to prevent operations that are incompatible with Azure SQL Database from attempting to connect to cloud instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BatchSeparator Sets the batch separator for multi-statement SQL execution, defaulting to \"GO\". Change this when working with scripts that use different batch separators or when \"GO\" conflicts with your SQL content. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ClientName Sets a custom application name in the connection string for identification in SQL Server monitoring tools. Use this to distinguish dbatools sessions from other applications when analyzing connections in Profiler, Extended Events, or sys.dm_exec_sessions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'sql.connection.clientname') | -ConnectTimeout Sets the connection timeout in seconds before the connection attempt fails. Increase 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | ([Dataplat.Dbatools.Connection.ConnectionHost]::SqlConnectionTimeout) | -EncryptConnection Forces SSL encryption for all data transmitted between client and server. Required for many compliance scenarios and recommended for connections over untrusted networks. Ensure server certificates are properly configured to avoid connection failures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'sql.connection.encrypt') | -FailoverPartner Specifies the failover partner server name for database mirroring configurations. Use this when connecting to databases configured for database mirroring to enable automatic failover if the primary server becomes unavailable. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LockTimeout Sets the lock timeout in seconds for transactions on this connection. Use this to control how long statements wait for locks before timing out, which helps prevent long-running blocking scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaxPoolSize Sets the maximum number of connections allowed in the connection pool for this connection string. Increase this for applications with high concurrency requirements, but be mindful of server resource limits and licensing constraints. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MinPoolSize Sets the minimum number of connections maintained in the connection pool for this connection string. Use this to pre-warm the connection pool for better performance when you know connections will be used frequently. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MinimumVersion Specifies the minimum SQL Server version required for the connection to succeed. Use this to ensure scripts only run against SQL Server versions that support the required features, preventing compatibility issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MultipleActiveResultSets Enables Multiple Active Result Sets (MARS) allowing multiple commands to be executed simultaneously on a single connection. Use this when you need to execute multiple queries concurrently without opening additional connections, though it can impact performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MultiSubnetFailover Enables faster detection and connection to the active server in Always On Availability Groups across multiple subnets. Essential for AG configurations where replicas are in different subnets, reducing connection time during failover scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'sql.connection.multisubnetfailover') | -NetworkProtocol Specifies the network protocol for connecting to SQL Server. Use \"TcpIp\" for remote connections, \"NamedPipes\" for local connections with better security, or \"SharedMemory\" for fastest local connections. Most modern environments use TcpIp. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'sql.connection.protocol') | | Accepted Values | TcpIp,NamedPipes,Multiprotocol,AppleTalk,BanyanVines,Via,SharedMemory,NWLinkIpxSpx | -NonPooledConnection Creates a dedicated connection that bypasses connection pooling. Use this for long-running operations, dedicated admin connections, or when you need to ensure the connection isn't shared with other processes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -PacketSize Sets the network packet size in bytes for communication with SQL Server. Increase from the default 4096 bytes to improve performance for large data transfers, but ensure the server is configured to support the same packet size. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'sql.connection.packetsize') | -PooledConnectionLifetime Sets the maximum lifetime in seconds for pooled connections before they're discarded and recreated. Use this in clustered environments to force load balancing or to refresh connections periodically. Zero means unlimited lifetime. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -SqlExecutionModes Controls how SQL commands are processed by the connection. Use \"CaptureSql\" to generate scripts without execution, \"ExecuteAndCaptureSql\" to both execute and log commands, or \"ExecuteSql\" for normal execution. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | CaptureSql,ExecuteAndCaptureSql,ExecuteSql | -StatementTimeout Sets the timeout in seconds for SQL statement execution before canceling the command. Use this to prevent runaway queries from blocking operations indefinitely. Zero means unlimited, but set reasonable limits for production environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'sql.execution.timeout') | -TrustServerCertificate Bypasses certificate validation when using encrypted connections. Use this for development environments or when connecting to servers with self-signed certificates, but avoid in production for security reasons. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'sql.connection.trustcert') | -AllowTrustServerCertificate Attempts connection with proper TLS validation first, then retries with TrustServerCertificate if the initial connection fails due to certificate validation. Provides a secure-by-default approach for mixed environments where some servers have valid certificates and others do not. Only retries on certificate validation failures, not on other connection errors like authentication or network issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'sql.connection.allowtrustcert') | -WorkstationId Sets the workstation name visible in SQL Server monitoring and session information. Use this to identify the source of connections in sys.dm_exec_sessions or when troubleshooting connection issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AlwaysEncrypted Enables Always Encrypted support for accessing encrypted columns in databases with column-level encryption. Required when working with sensitive data protected by Always Encrypted, allowing proper decryption of encrypted column values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AppendConnectionString Adds custom connection string parameters to the generated connection string. Use this for advanced connection properties like custom timeout values, SSL settings, or application-specific parameters that aren't covered by other parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlConnectionOnly Returns only a SqlConnection object instead of the full SMO server object. Use this when you only need basic connection functionality and want to reduce memory overhead or avoid SMO initialization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AzureDomain Specifies the domain for Azure SQL Database connections, defaulting to database.windows.net. Use this when connecting to Azure SQL instances in sovereign clouds or custom domains that require different authentication methods. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | database.windows.net | -Tenant Specifies the Azure Active Directory tenant ID for Azure SQL Database authentication. Required when using service principal authentication or when your account exists in multiple Azure AD tenants. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'azure.tenantid') | -AccessToken Authenticates to Azure SQL Database using an access token generated by Get-AzAccessToken or New-DbaAzAccessToken. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AuthenticationType Specifies the authentication method for connecting to Azure SQL or Entra ID-protected SQL Server instances. Use \"ActiveDirectoryInteractive\" for Entra ID (Azure AD) authentication with MFA â€” a browser dialog will prompt you to select your Entra ID account. Use \"ActiveDirectoryIntegrated\" for Entra ID integrated authentication using your current Windows session. Use \"ActiveDirectoryPassword\" for Entra ID authentication with a username and password via SqlCredential. Use \"ActiveDirectoryServicePrincipal\" for service principal authentication (client ID and secret via SqlCredential). Use \"ActiveDirectoryManagedIdentity\" for managed identity authentication in Azure-hosted environments. Use \"ActiveDirectoryDeviceCodeFlow\" for device code flow authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | ActiveDirectoryIntegrated,ActiveDirectoryInteractive,ActiveDirectoryPassword,ActiveDirectoryServicePrincipal,ActiveDirectoryManagedIdentity,ActiveDirectoryDeviceCodeFlow | -DedicatedAdminConnection Creates a dedicated administrator connection (DAC) for emergency access to SQL Server. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisableException Changes exception handling from throwing errors to displaying warnings. Use this in interactive sessions where you want graceful error handling instead of script-stopping exceptions, which is the default behavior for this command. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Server (default) Returns 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 queries, access database objects, and perform administrative tasks. The returned object includes both standard SMO properties and dbatools-specific added properties: Added dbatools properties: ComputerName: The computer name of the SQL Server instance IsAzure: Boolean indicating if the target is Azure SQL Database DbaInstanceName: The instance name component (for named instances like \"SQLSERVER\\INSTANCENAME\") SqlInstance: The full SQL Server instance name in DomainInstanceName format (e.g., \"COMPUTERNAME\\INSTANCENAME\") NetPort: The TCP port number used for the connection ConnectedAs: The login used to establish the connection (from ConnectionContext.TrueLogin) Standard SMO Server object properties (selected): Databases: Collection of Database objects on the server Logins: Collection of Login objects on the server LinkedServers: Collection of LinkedServer objects Endpoints: Collection of Endpoint objects ConnectionContext: ServerConnection object containing connection details and configuration 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) VersionMinor: Minor version number Version: Full version object ServiceInstanceId: Service instance ID DefaultFile: Default data file path DefaultLog: Default log file path MasterDBLogPath: Master database log file path MasterDBPath: Master database path InstallDataDirectory: SQL Server installation data directory BackupDirectory: Default backup directory Name: The server name DatabaseEngineType: Engine type (Standard, Compact, SqlAzureDatabase, etc.) HostPlatform: Platform the server is running on (Windows or Linux) Microsoft.Data.SqlClient.SqlConnection (when -SqlConnectionOnly is specified) Returns only the underlying SQL connection object from the SMO Server's ConnectionContext.SqlConnectionObject. Use this when you need basic connection functionality without the overhead of initializing the full SMO Server object. The connection can be used with ADO.NET code or when integrating with other .NET libraries. &nbsp;"
  },
  {
    "name": "ConvertTo-DbaDataTable",
    "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.",
    "category": "Utilities",
    "tags": [
      "table",
      "data"
    ],
    "verb": "ConvertTo",
    "popular": false,
    "url": "/ConvertTo-DbaDataTable",
    "popularityRank": 62,
    "synopsis": "Converts PowerShell objects into .NET DataTable objects for bulk SQL Server operations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "ConvertTo-DbaDataTable View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Converts PowerShell objects into .NET DataTable objects for bulk SQL Server operations 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. The 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. Common 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. Thanks to Chad Miller, this is based on his script. https://gallery.technet.microsoft.com/scriptcenter/4208a159-a52e-4b99-83d4-8048468d29dd If the attempt to convert to data table fails, try the -Raw parameter for less accurate datatype detection. Syntax ConvertTo-DbaDataTable [-InputObject] [-TimeSpanType ] [-SizeType ] [-IgnoreNull] [-Raw] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Creates a DataTable from the output of Get-Service PS C:\\> Get-Service | ConvertTo-DbaDataTable Example 2: Creates a DataTable from the CSV object $csv.cheesetypes PS C:\\> ConvertTo-DbaDataTable -InputObject $csv.cheesetypes Example 3: Creates a DataTable from the $dblist object passed in via pipeline PS C:\\> $dblist | ConvertTo-DbaDataTable Example 4: Creates a DataTable with the running processes and converts any TimeSpan property to TotalSeconds PS C:\\> Get-Process | ConvertTo-DbaDataTable -TimeSpanType TotalSeconds Required Parameters -InputObject PowerShell objects to convert into a DataTable with proper SQL Server-compatible column types. Accepts results from dbatools commands like Get-DbaDatabase, Get-DbaBackupHistory, or any PowerShell object array. Handles complex properties, arrays, and dbatools-specific types like DbaSize and DbaTimeSpan automatically. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -TimeSpanType Controls how TimeSpan and DbaTimeSpan objects are converted for database storage. Use 'TotalMilliseconds' (default) for precise timing data, 'TotalSeconds' for general duration tracking, or 'String' to preserve readable format. Common when converting backup duration, job runtime, or database uptime data for reporting tables. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | TotalMilliseconds | | Accepted Values | Ticks,TotalDays,TotalHours,TotalMinutes,TotalSeconds,TotalMilliseconds,String | -SizeType Controls how DbaSize objects (file sizes, database sizes) are converted for database storage. Use 'Int64' (default) for precise byte values suitable for calculations, 'Int32' for smaller datasets, or 'String' to preserve human-readable format like '1.5 GB'. Essential when storing database size reports, backup file information, or disk space data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Int64 | | Accepted Values | Int64,Int32,String | -IgnoreNull Excludes null objects from the DataTable instead of creating empty rows. Use this when preparing clean datasets for bulk insert operations where empty rows would cause issues. Helpful when processing filtered results that may contain null entries from failed connections or missing databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Raw Forces all DataTable columns to be strings instead of detecting proper data types. Use this as a fallback when automatic type detection fails or when you need maximum compatibility with target tables that expect string data. Trades type safety for reliability when dealing with complex or problematic object properties. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Data.DataTable Returns 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. Column data types are automatically detected based on input object properties: Numeric types (Int32, Int64, Decimal, Double, Single, etc.) are preserved as their original types TimeSpan and DbaTimeSpan objects are converted based on the -TimeSpanType parameter (default: TotalMilliseconds as Int64) DbaSize (file/database size) objects are converted based on the -SizeType parameter (default: Byte value as Int64) DateTime objects are preserved as System.DateTime Boolean, Guid, and Char types are preserved String arrays and System.Object[] are joined with comma separators Other types are converted to strings When 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. The 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. &nbsp;"
  },
  {
    "name": "ConvertTo-DbaTimeline",
    "description": "Transforms SQL Server job execution, backup operation, and database growth event data into visual timeline reports for analysis and troubleshooting. Takes piped output from Get-DbaAgentJobHistory, Get-DbaDbBackupHistory, or Find-DbaDbGrowthEvent and generates a complete HTML file with an interactive Google Charts timeline.\n\nPerfect for analyzing job schedules, identifying backup windows, visualizing auto-growth events, troubleshooting overlapping operations, or creating visual reports for management. The timeline shows execution duration, status, and timing relationships across multiple instances, with hover tooltips displaying detailed information including start/end times and duration calculations.\n\nOutput is a self-contained HTML file that can be viewed in any browser, emailed to stakeholders, or archived for historical analysis. Supports both single and multi-instance scenarios with automatic labeling and color-coded status indicators.",
    "category": "Utilities",
    "tags": [
      "utility",
      "chart"
    ],
    "verb": "ConvertTo",
    "popular": false,
    "url": "/ConvertTo-DbaTimeline",
    "popularityRank": 146,
    "synopsis": "Generates interactive HTML timeline visualizations from SQL Server job history, backup history, and database growth event data",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "ConvertTo-DbaTimeline View Source Marcin Gminski (@marcingminski) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates interactive HTML timeline visualizations from SQL Server job history, backup history, and database growth event data Description Transforms SQL Server job execution, backup operation, and database growth event data into visual timeline reports for analysis and troubleshooting. Takes piped output from Get-DbaAgentJobHistory, Get-DbaDbBackupHistory, or Find-DbaDbGrowthEvent and generates a complete HTML file with an interactive Google Charts timeline. Perfect for analyzing job schedules, identifying backup windows, visualizing auto-growth events, troubleshooting overlapping operations, or creating visual reports for management. The timeline shows execution duration, status, and timing relationships across multiple instances, with hover tooltips displaying detailed information including start/end times and duration calculations. Output 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. Syntax ConvertTo-DbaTimeline [-InputObject] [-ExcludeRowLabel] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: -Encoding ASCII Creates an output file containing a pretty timeline for all of the agent job history results... PS C:\\> Get-DbaAgentJobHistory -SqlInstance sql-1 -StartDate '2018-08-13 00:00' -EndDate '2018-08-13 23:59' -ExcludeJobSteps | ConvertTo-DbaTimeline | Out-File C:\\temp\\DbaAgentJobHistory.html -Encoding ASCII Creates 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 Example 2: Creates an output file containing a pretty timeline for the agent job history since 2018-08-13 for all of the... PS C:\\> Get-DbaRegServer -SqlInstance sqlcm | Get-DbaDbBackupHistory -Since '2018-08-13 00:00' | ConvertTo-DbaTimeline | Out-File C:\\temp\\DbaBackupHistory.html -Encoding ASCII Creates an output file containing a pretty timeline for the agent job history since 2018-08-13 for all of the registered servers on sqlcm Example 3: Creates an output file containing a timeline of all database auto-growth and auto-shrink events for sql-1 PS C:\\> Find-DbaDbGrowthEvent -SqlInstance sql-1 | ConvertTo-DbaTimeline | Out-File C:\\temp\\DbaDbGrowthEvent.html -Encoding ASCII Example 4: Sends an email to dba@ad.local with the results of Get-DbaDbBackupHistory PS C:\\> $messageParameters = @{ >> Subject = \"Backup history for sql2017 and sql2016\" >> Body = Get-DbaDbBackupHistory -SqlInstance sql2017, sql2016 -Since '2018-08-13 00:00' | ConvertTo-DbaTimeline | Out-String >> From = \"dba@ad.local\" >> To = \"dba@ad.local\" >> SmtpServer = \"smtp.ad.local\" >> } >> PS C:\\> Send-MailMessage @messageParameters -BodyAsHtml Sends 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. Required Parameters -InputObject Specifies the SQL Server data to convert into timeline visualization. Accepts piped output from Get-DbaAgentJobHistory, Get-DbaDbBackupHistory, or Find-DbaDbGrowthEvent. Use this to transform job execution history, backup operation data, or database auto-growth/shrink events into an interactive HTML timeline chart. The function automatically detects the input type and formats the timeline appropriately with status colors and duration calculations. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -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 timeline row. Use this when you need to maximize chart space for better visualization of timeline data, especially with long instance or job names. All label information remains available in the hover tooltips when you mouse over timeline bars. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String Returns 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: header/scripts (HTML head section), body rows (timeline data), and footer (HTML closing tags and chart rendering code). The 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 in a web browser, renders an interactive timeline with: Horizontal timeline bars showing execution duration Color-coded status indicators (Success, Failure, etc. based on input data) Hover tooltips displaying item name, status, start time, end time, and duration Configurable row labels (disabled with -ExcludeRowLabel parameter) Responsive sizing that adjusts to content Multi-instance support with automatic instance labeling &nbsp;"
  },
  {
    "name": "ConvertTo-DbaXESession",
    "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/",
    "category": "Performance",
    "tags": [
      "trace",
      "extendedevent"
    ],
    "verb": "ConvertTo",
    "popular": false,
    "url": "/ConvertTo-DbaXESession",
    "popularityRank": 404,
    "synopsis": "Converts SQL Server Traces to Extended Events sessions using intelligent column and event mapping.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "ConvertTo-DbaXESession View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Converts SQL Server Traces to Extended Events sessions using intelligent column and event mapping. 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. The 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. By 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. T-SQL code by: Jonathan M. Kehayias, SQLskills.com. T-SQL can be found in this module directory and at https://www.sqlskills.com/blogs/jonathan/converting-sql-trace-to-extended-events-in-sql-server-2012/ Syntax ConvertTo-DbaXESession [-InputObject] [-Name] [[-SqlCredential] ] [-OutputScriptOnly] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Converts Trace with ID 2 to a Session named Test on SQL Server instances named sql2017 and sql2012 and... PS C:\\> Get-DbaTrace -SqlInstance sql2017, sql2012 | Where-Object Id -eq 2 | ConvertTo-DbaXESession -Name 'Test' Converts 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. Example 2: Converts selected traces on sql2014 to sessions, creates the session, and starts it PS C:\\> Get-DbaTrace -SqlInstance sql2014 | Out-GridView -PassThru | ConvertTo-DbaXESession -Name 'Test' | Start-DbaXESession Example 3: Converts trace ID 1 on sql2014 to an Extended Event and outputs the resulting T-SQL PS C:\\> Get-DbaTrace -SqlInstance sql2014 | Where-Object Id -eq 1 | ConvertTo-DbaXESession -Name 'Test' -OutputScriptOnly Required Parameters -InputObject Specifies the SQL Server Trace objects to convert to Extended Events sessions. Must be trace objects returned by Get-DbaTrace. Use this to convert existing traces from SQL Trace to Extended Events, preserving event mappings and filter configurations. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -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. Choose 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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Particularly useful in compliance environments where all scripts require approval before running against production databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String (when -OutputScriptOnly is specified) Returns 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 SQL Trace. Microsoft.SqlServer.Management.XEvent.Session (default output) Returns 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 properties added by Get-DbaXESession: Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The Extended Events session name (the converted trace name) Status: Current session status (Running or Stopped) StartTime: Date and time the session started AutoStart: Boolean indicating if the session auto-starts on SQL Server startup State: Session state (Created, Running, etc.) Targets: Extended Events targets collecting the data TargetFile: Path to the target output file(s) Events: Extended Events events configured in the session MaxMemory: Maximum memory allocated to the session in MB MaxEventSize: Maximum size of events in KB Additional properties available (from SMO XEStore.ServerSession object): Session: The session name (duplicate of Name property) RemoteTargetFile: UNC path to the target output file(s) for remote access Parent: Reference to the SQL Server SMO server object Store: Reference to the XEStore object IsRunning: Boolean indicating if the session is currently running Description: Session description CreateDate: Date and time the session was created ModifyDate: Date and time the session was last modified &nbsp;"
  },
  {
    "name": "Copy-DbaAgentAlert",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "agent"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaAgentAlert",
    "popularityRank": 56,
    "synopsis": "Copies SQL Server Agent alerts from source instance to destination instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaAgentAlert View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies SQL Server Agent alerts from source instance to destination instances 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. Essential 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. By 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. Syntax Copy-DbaAgentAlert [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Alert] ] [[-ExcludeAlert] ] [-IncludeDefaults] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all alerts from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster Copies all alerts from sqlserver2014a to sqlcluster using Windows credentials. If alerts with the same name exist on sqlcluster, they will be skipped. Example 2: Copies a only the alert named PSAlert from sqlserver2014a to sqlcluster using SQL credentials for... PS C:\\> Copy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster -Alert PSAlert -SourceSqlCredential $cred -Force Copies 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 sqlcluster, it will be dropped and recreated because -Force was used. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaAgentAlert -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -Source Specifies the source SQL Server instance containing the alerts to copy. Must be SQL Server 2000 or higher. Use this to identify the server with the alert configurations you want to migrate or replicate. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Specifies one or more destination SQL Server instances where alerts will be copied. Must be SQL Server 2000 or higher. Accepts multiple instances to copy alerts to several servers simultaneously during migrations or standardization efforts. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Specifies alternative credentials for connecting to the source SQL Server instance. Use this when the current Windows credentials don't have access to the source server or when connecting with SQL Server authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Specifies alternative credentials for connecting to the destination SQL Server instances. Use this when the current Windows credentials don't have access to destination servers or when connecting with SQL Server authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Alert Specifies specific alert names to copy instead of copying all alerts from the source instance. Use this when you only need to migrate particular alerts rather than the entire alert configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeAlert Specifies alert names to skip during the copy operation while processing all other alerts. Use this when you want to copy most alerts but exclude specific ones that shouldn't be migrated. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeDefaults Copies SQL Server Agent system settings including FailSafeEmailAddress, ForwardingServer, and PagerSubjectTemplate. Use this when migrating to a new server where you want to replicate the source server's Agent notification configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Drops and recreates alerts that already exist on the destination servers instead of skipping them. Use this when you need to overwrite existing alerts with updated configurations from the source. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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. Properties: SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance where the alert was copied Name: Name of the alert or configuration item being copied Type: Type of object being processed (Agent Alert, Agent Alert Job Association, Agent Alert Notification, or Alert Defaults) Status: Result of the operation (Successful, Failed, or Skipped) Notes: Additional details about the operation, such as why it was skipped or error message DateTime: Timestamp when the operation was performed (Dataplat.Dbatools.Utility.DbaDateTime) When 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, the operation is shown as a separate action in the output. &nbsp;"
  },
  {
    "name": "Copy-DbaAgentJob",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "agent",
      "job"
    ],
    "verb": "Copy",
    "popular": true,
    "url": "/Copy-DbaAgentJob",
    "popularityRank": 9,
    "synopsis": "Migrates SQL Server Agent jobs between instances with dependency validation",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaAgentJob View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Migrates SQL Server Agent jobs between instances with dependency validation 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. The 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. Syntax Copy-DbaAgentJob [[-Source] ] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Job] ] [[-ExcludeJob] ] [-DisableOnSource] [-DisableOnDestination] [-Force] [[-NewName] ] [-UseLastModified] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all jobs from sqlserver2014a to sqlcluster, using Windows credentials PS C:\\> Copy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster Copies all jobs from sqlserver2014a to sqlcluster, using Windows credentials. If jobs with the same name exist on sqlcluster, they will be skipped. Example 2: Copies a single job, the PSJob job from sqlserver2014a to sqlcluster, using SQL credentials for... PS C:\\> Copy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster -Job PSJob -SourceSqlCredential $cred -Force Copies 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 sqlcluster, it will be dropped and recreated because -Force was used. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaAgentJob -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Example 4: Copies all SSRS jobs (subscriptions) from AlwaysOn Primary SQL instance sqlserver2014a to AlwaysOn Secondary... PS C:\\> Get-DbaAgentJob -SqlInstance sqlserver2014a | Where-Object Category -eq \"Report Server\" | Copy-DbaAgentJob -Destination sqlserver2014b Copies all SSRS jobs (subscriptions) from AlwaysOn Primary SQL instance sqlserver2014a to AlwaysOn Secondary SQL instance sqlserver2014b Example 5: Copies jobs from sqlserver2014a to sqlserver2014b, but only creates new jobs or updates existing jobs where... PS C:\\> Copy-DbaAgentJob -Source sqlserver2014a -Destination sqlserver2014b -UseLastModified Copies 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 skipped. Example 6: Copies the job &quot;OriginalJob&quot; on sqlserver2014a to the same server as &quot;JobCopy&quot; PS C:\\> Copy-DbaAgentJob -Source sqlserver2014a -Destination sqlserver2014a -Job \"OriginalJob\" -NewName \"JobCopy\" Copies the job \"OriginalJob\" on sqlserver2014a to the same server as \"JobCopy\". When source and destination are the same instance, -NewName is required. Required Parameters -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. Supports multiple destinations to copy jobs to multiple servers simultaneously during migrations or DR setup. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. Use this when copying jobs from a specific instance rather than piping job objects with InputObject. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SourceSqlCredential Alternative credentials for connecting to the source SQL Server instance. Accepts PowerShell credentials (Get-Credential). Use this when the source server requires different authentication than your current Windows session, such as SQL authentication or cross-domain scenarios. Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Alternative credentials for connecting to the destination SQL Server instance. Accepts PowerShell credentials (Get-Credential). Use this when the destination server requires different authentication than your current Windows session, such as SQL authentication or cross-domain scenarios. Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies which SQL Agent jobs to copy by name. Accepts wildcards and multiple job names. Use this to copy specific jobs instead of all jobs, such as during selective migrations or when testing job deployments. If unspecified, all jobs will be processed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJob Specifies which SQL Agent jobs to skip during the copy operation. Accepts wildcards and multiple job names. Use this to exclude specific jobs from bulk operations, such as skipping environment-specific jobs or maintenance tasks that shouldn't be migrated. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DisableOnSource Disables the job on the source server after successfully copying it to the destination. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisableOnDestination Creates the job on the destination server but leaves it disabled. Use this when deploying jobs to test environments or when you need to review and modify job steps before enabling them in the new environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Overwrites existing jobs on the destination server and automatically sets missing job owners to the 'sa' login. Use this when you need to replace existing jobs or when source job owners don't exist on the destination server during migrations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NewName The new name for the job on the destination server. Required when source and destination are the same server instance. Use this to create a copy of a job under a different name on the same or a different server. Cannot be used when copying multiple jobs simultaneously. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -UseLastModified When enabled, compares the last modification date (date_modified) from msdb.dbo.sysjobs between source and destination instances. Jobs are only copied or updated if the source job is newer than the destination job. This provides intelligent synchronization: If job doesn't exist on destination: creates it If source date_modified is newer: drops and recreates the job If dates are equal: skips the job If destination is newer: skips with a warning Use this for incremental synchronization scenarios where you want to keep jobs up-to-date without unconditionally overwriting them. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts SQL Agent job objects from the pipeline, typically from Get-DbaAgentJob. Use this to copy pre-filtered jobs or when combining with other job management cmdlets for complex workflows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs MigrationObject (PSCustomObject) Returns 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. Properties: DateTime: Timestamp when the operation was attempted (DbaDateTime type) SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The name of the SQL Agent job Type: Always \"Agent Job\" indicating the type of object being migrated Status: The outcome of the operation - \"Successful\", \"Skipped\", or \"Failed\" Notes: Descriptive message explaining the status (reason for skip, error details, etc.) &nbsp;"
  },
  {
    "name": "Copy-DbaAgentJobCategory",
    "description": "Migrates custom SQL Agent categories from a source SQL Server to one or more destination servers, so you don't have to manually recreate organizational structures during server migrations or environment setups.\nThis function copies only user-defined categories (ID >= 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.",
    "category": "Migration",
    "tags": [
      "migration",
      "agent"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaAgentJobCategory",
    "popularityRank": 187,
    "synopsis": "Copies custom SQL Agent categories for jobs, alerts, and operators between SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaAgentJobCategory View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies custom SQL Agent categories for jobs, alerts, and operators between SQL Server instances. Description Migrates custom SQL Agent categories from a source SQL Server to one or more destination servers, so you don't have to manually recreate organizational structures during server migrations or environment setups. This function copies only user-defined categories (ID >= 100), preserving built-in system categories on the destination. Essential for maintaining consistent job categorization across multiple SQL Server instances in enterprise environments. You can copy all categories at once or filter by category type (Job, Alert, Operator) or specify individual category names. Categories that already exist on the destination will be skipped unless you use -Force to drop and recreate them. The function uses SQL Server Management Objects (SMO) to script category definitions and recreate them on the target server. Syntax Copy-DbaAgentJobCategory -Source [-SourceSqlCredential ] -Destination [-DestinationSqlCredential ] [-JobCategory ] [-AgentCategory ] [-OperatorCategory ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Copy-DbaAgentJobCategory -Source [-SourceSqlCredential ] -Destination [-DestinationSqlCredential ] [-CategoryType ] [-JobCategory ] [-AgentCategory ] [-OperatorCategory ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all operator categories from sqlserver2014a to sqlcluster using Windows authentication PS C:\\> Copy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster Copies all operator categories from sqlserver2014a to sqlcluster using Windows authentication. If operator categories with the same name exist on sqlcluster, they will be skipped. Example 2: Copies a single operator category, the PSOperator operator category from sqlserver2014a to sqlcluster using... PS C:\\> Copy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster -OperatorCategory PSOperator -SourceSqlCredential $cred -Force Copies a single operator category, the PSOperator operator category from sqlserver2014a to sqlcluster using SQL credentials to authenticate to sqlserver2014a and Windows credentials for sqlcluster. If an operator category with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaAgentJobCategory -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -Source The source SQL Server instance from which to copy Agent job categories. Requires sysadmin permissions to access MSDB and read category definitions. Use this to specify the server that has the custom categories you want to replicate to other instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. Requires sysadmin permissions to create categories in each destination server's MSDB database. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Alternative credentials for connecting to the source SQL Server instance. Use this when your current Windows authentication doesn't have sufficient permissions on the source server. Accepts credentials created with Get-Credential for SQL authentication or different Windows accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Accepts credentials created with Get-Credential and applies to all destination servers specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this for bulk migration of entire category types rather than individual category names. Leave empty to copy all category types. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Supports tab completion from the source server's existing job categories for convenience. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AgentCategory Specific alert category names to copy from the source server. Use this for selective migration when you only need certain alert categories. Note: This parameter is currently not implemented in the function code and will be ignored if used. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OperatorCategory Specific operator category names to copy from the source server. Use this for selective migration when you only need certain operator categories. Supports tab completion from the source server's existing operator categories for convenience. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Without this switch, categories that already exist on the destination will be skipped to prevent data loss. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per category processed (whether skipped, successfully copied, or failed). When multiple categories or multiple destination servers are specified, returns multiple objects. Default display properties (via Select-DefaultView with TypeName MigrationObject): DateTime: The date and time when the category copy was attempted (DbaDateTime object) SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The name of the category being copied Type: The type of category (\"Agent Job Category\", \"Agent Operator Category\", or \"Agent Alert Category\") Status: The outcome of the copy operation (Successful, Failed, or Skipped) Notes: Additional context about the operation result (e.g., \"Already exists on destination\") All properties are accessible using Select-Object * even though only the above default properties are displayed. &nbsp;"
  },
  {
    "name": "Copy-DbaAgentJobStep",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "agent",
      "job"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaAgentJobStep",
    "popularityRank": 0,
    "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",
    "windowsOnly": false,
    "fullContent": "Copy-DbaAgentJobStep View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies job steps from one SQL Server Agent job to another, preserving job history by synchronizing steps without dropping the job itself. 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. The 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. Syntax Copy-DbaAgentJobStep [[-Source] ] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Job] ] [[-ExcludeJob] ] [[-Step] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all job steps from the &quot;MaintenanceJob&quot; on PrimaryAG to the same job on SecondaryAG1 and SecondaryAG2... PS C:\\> Copy-DbaAgentJobStep -Source PrimaryAG -Destination SecondaryAG1, SecondaryAG2 -Job \"MaintenanceJob\" Copies all job steps from the \"MaintenanceJob\" on PrimaryAG to the same job on SecondaryAG1 and SecondaryAG2, preserving job history on the destination servers. Example 2: Retrieves the BackupJob from PrimaryAG and synchronizes its steps to the same job on SecondaryAG1 using... PS C:\\> Get-DbaAgentJob -SqlInstance PrimaryAG -Job \"BackupJob\" | Copy-DbaAgentJobStep -Destination SecondaryAG1 Retrieves the BackupJob from PrimaryAG and synchronizes its steps to the same job on SecondaryAG1 using pipeline input. Example 3: Copies job steps for the &quot;DataETL&quot; job from sqlserver2014a to sqlcluster, using SQL credentials for the... PS C:\\> Copy-DbaAgentJobStep -Source sqlserver2014a -Destination sqlcluster -Job \"DataETL\" -SourceSqlCredential $cred Copies job steps for the \"DataETL\" job from sqlserver2014a to sqlcluster, using SQL credentials for the source server and Windows credentials for the destination. Example 4: Synchronizes all job steps from Primary to multiple AG replicas, ensuring all replicas have identical job... PS C:\\> Copy-DbaAgentJobStep -Source Primary -Destination Replica1, Replica2, Replica3 Synchronizes all job steps from Primary to multiple AG replicas, ensuring all replicas have identical job step definitions while preserving their individual job execution histories. Required Parameters -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. Supports multiple destinations to copy job steps to multiple servers simultaneously, such as syncing all AG replicas or DR servers. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. Use this when copying job steps from a specific instance rather than piping job objects with InputObject. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SourceSqlCredential Alternative credentials for connecting to the source SQL Server instance. Accepts PowerShell credentials (Get-Credential). Use this when the source server requires different authentication than your current Windows session, such as SQL authentication or cross-domain scenarios. Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Alternative credentials for connecting to the destination SQL Server instance. Accepts PowerShell credentials (Get-Credential). Use this when the destination server requires different authentication than your current Windows session, such as SQL authentication or cross-domain scenarios. Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies which SQL Agent jobs to process by name. Accepts wildcards and multiple job names. Use this to synchronize steps for specific jobs, such as copying modified steps from a primary AG replica to secondary replicas. If unspecified, all jobs will be processed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJob Specifies which SQL Agent jobs to skip during the copy operation. Accepts wildcards and multiple job names. Use this to exclude specific jobs from bulk operations, such as skipping environment-specific jobs that shouldn't be synchronized. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Step Specifies which job steps to copy by name. If not specified, all steps are copied. Use this to synchronize specific steps rather than all steps from a job. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts SQL Agent job objects from the pipeline, typically from Get-DbaAgentJob. Use this to copy steps for pre-filtered jobs or when combining with other job management cmdlets for complex workflows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (MigrationObject) Returns one object per job processed with the following properties: Default display properties (via Select-DefaultView): DateTime: The timestamp when the job step copy operation was executed SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The name of the SQL Agent job Type: The operation type, always \"Agent Job Steps\" 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 Notes: Additional information about the operation, such as the number of steps synchronized or reason for skipping/failure All properties are always available on the returned object even though Select-DefaultView limits the display. &nbsp;"
  },
  {
    "name": "Copy-DbaAgentOperator",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "agent",
      "operator"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaAgentOperator",
    "popularityRank": 70,
    "synopsis": "Copies SQL Server Agent operators between instances for migration and standardization.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaAgentOperator View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies SQL Server Agent operators between instances for migration and standardization. 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. All 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. Each 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. Syntax Copy-DbaAgentOperator [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Operator] ] [[-ExcludeOperator] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all operators from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster Copies all operators from sqlserver2014a to sqlcluster using Windows credentials. If operators with the same name exist on sqlcluster, they will be skipped. Example 2: Copies only the PSOperator operator from sqlserver2014a to sqlcluster using SQL credentials for... PS C:\\> Copy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster -Operator PSOperator -SourceSqlCredential $cred -Force Copies 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 sqlcluster, it will be dropped and recreated because -Force was used. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaAgentOperator -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -Source The SQL Server instance containing the operators you want to copy from. Must be SQL Server 2000 or higher. Use this to specify which instance has the existing operators that need to be migrated or replicated to other instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination One or more SQL Server instances where the operators will be copied to. Must be SQL Server 2000 or higher. Accepts multiple instances to copy operators to several servers at once during migrations or standardization projects. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Credentials for connecting to the source SQL Server instance when Windows Authentication is not available. Use this when the source server requires SQL Server Authentication or when running under a different user context than your current Windows session. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instances when Windows Authentication is not available. Use this when the destination servers require SQL Server Authentication or when running under a different user context than your current Windows session. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Operator Specifies which operators to copy by name. Accepts wildcards and multiple operator names. Use this when you only need to migrate specific operators instead of copying all operators from the source instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeOperator Operators to skip during the copy operation. Accepts wildcards and multiple operator names. Use this to copy most operators while excluding specific ones, such as development-only or temporary operators. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Drops and recreates operators that already exist on the destination instances. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs MigrationObject (PSCustomObject) Returns one object per operator processed, containing the migration status for that operator. Default display properties: DateTime: Timestamp when the copy operation was executed SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Name: The name of the Agent Operator that was copied Type: Always set to \"Agent Operator\" Status: Result of the copy operation (Successful, Skipped, or Failed) Notes: Additional details about the operation result (e.g., \"Already exists on destination\") All properties from the object are accessible via Select-Object * if needed. &nbsp;"
  },
  {
    "name": "Copy-DbaAgentProxy",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "agent"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaAgentProxy",
    "popularityRank": 0,
    "synopsis": "Copies SQL Server Agent proxy accounts from one instance to another.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaAgentProxy View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies SQL Server Agent proxy accounts from one instance to another. 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. Syntax Copy-DbaAgentProxy [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-ProxyAccount] ] [[-ExcludeProxyAccount] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all proxy accounts from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster Copies all proxy accounts from sqlserver2014a to sqlcluster using Windows credentials. If proxy accounts with the same name exist on sqlcluster, they will be skipped. Example 2: Copies only the PSProxy proxy account from sqlserver2014a to sqlcluster using SQL credentials for... PS C:\\> Copy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster -ProxyAccount PSProxy -SourceSqlCredential $cred -Force Copies 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 on sqlcluster, it will be dropped and recreated because -Force was used. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaAgentProxy -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -Source Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ProxyAccount Specifies which proxy accounts to copy from the source server. Accepts an array of proxy account names. Use this when you only need to migrate specific proxy accounts instead of all available accounts on the source server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeProxyAccount Specifies proxy accounts to skip during migration. Accepts an array of proxy account names to exclude. Use this when you want to copy most proxy accounts but need to avoid migrating specific ones that may conflict or aren't needed on the destination. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Forces overwriting of existing proxy accounts on the destination server by dropping and recreating them. Use this when you need to update proxy accounts that already exist on the destination with the current configuration from the source server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (MigrationObject) Returns one object per proxy account processed, showing the migration status and details. Default display properties (via Select-DefaultView): DateTime: The timestamp when the operation was performed (DbaDateTime type) SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The name of the proxy account or associated credential being migrated Type: The object type being migrated (Agent Proxy, Credential, or ProxyAccount) Status: The migration status (Successful, Skipped, Failed, or Skipping) Notes: Additional details about the operation outcome or reason for skipping &nbsp;"
  },
  {
    "name": "Copy-DbaAgentSchedule",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "agent"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaAgentSchedule",
    "popularityRank": 150,
    "synopsis": "Migrates SQL Agent shared job schedules between SQL Server instances for job schedule standardization.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaAgentSchedule View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Migrates SQL Agent shared job schedules between SQL Server instances for job schedule standardization. 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. Syntax Copy-DbaAgentSchedule [[-Source] ] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Schedule] ] [[-Id] ] [[-InputObject] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all shared job schedules from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaAgentSchedule -Source sqlserver2014a -Destination sqlcluster Copies 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. Example 2: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaAgentSchedule -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Example 3: Gets a list of schedule, outputs to a gridview which can be selected from, then copies to SqlInstance PS C:\\> Get-DbaAgentSchedule -SqlInstance sql2016 | Out-GridView -Passthru | Copy-DbaAgentSchedule -Destination sqlcluster Required Parameters -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 simultaneously. Use this when standardizing schedules across multiple instances or when migrating Agent configurations to new servers. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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 instance. Use this parameter when copying schedules from a specific server, or omit it when piping schedules from Get-DbaAgentSchedule. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 authentication. Accepts credentials created with Get-Credential or saved credential objects. Required when copying from instances that don't accept your current Windows authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 with SQL Server authentication. Accepts credentials created with Get-Credential or saved credential objects. Required when copying to instances that don't accept your current Windows authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schedule Filters the operation to copy only schedules with specific names. Accepts an array of schedule names using wildcard patterns for flexible matching. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Id Filters the operation to copy only schedules with specific numeric IDs. Accepts an array of schedule IDs for targeting multiple specific schedules. Use this instead of schedule names when you need precise identification, especially when duplicate schedule names exist on the source instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this for advanced scenarios like selective copying based on complex filtering or when working with schedules from multiple source instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Force Forces the overwrite of existing schedules on the destination instances by dropping and recreating them. Without this switch, existing schedules are skipped. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per schedule copied, with migration status details for each operation. Properties: SourceServer: Name of the source SQL Server instance containing the original schedule DestinationServer: Name of the destination SQL Server instance where the schedule was copied Name: The name of the job schedule that was copied Type: The type of object copied (always \"Agent Schedule\") Status: The result of the copy operation (\"Successful\", \"Skipped\", or \"Failed\") Notes: Additional context explaining the status (e.g., \"Already exists on destination\", \"Schedule has associated jobs\") DateTime: Timestamp (UTC) when the copy operation was performed Default display order: DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes &nbsp;"
  },
  {
    "name": "Copy-DbaAgentServer",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "sqlserveragent",
      "sqlagent"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaAgentServer",
    "popularityRank": 131,
    "synopsis": "Copies all SQL Server Agent objects and server properties between instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaAgentServer View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies all SQL Server Agent objects and server properties between instances. 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. You must have sysadmin access and server version must be SQL Server version 2000 or greater. Syntax Copy-DbaAgentServer [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [-DisableJobsOnDestination] [-DisableJobsOnSource] [-ExcludeServerProperties] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all job server objects from sqlserver2014a to sqlcluster using Windows credentials for authentication PS C:\\> Copy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster Copies 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. Example 2: Copies all job objects from sqlserver2014a to sqlcluster using SQL credentials to authentication to... PS C:\\> Copy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred Copies all job objects from sqlserver2014a to sqlcluster using SQL credentials to authentication to sqlserver2014a and Windows credentials to authenticate to sqlcluster. Example 3: Shows what would happen if the command were executed PS C:\\> Copy-DbaAgentServer -Source sqlserver2014a -Destination sqlcluster -WhatIf Required Parameters -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. Must have sysadmin access and be SQL Server 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. Must have sysadmin access and be SQL Server 2000 or higher. Useful for standardizing Agent configurations across development, test, and production environments. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Authentication credentials for connecting to the Source SQL Server instance. Use this when you need SQL Server authentication instead of Windows authentication. Create credentials using Get-Credential and pass them to this parameter. Common when source server is in different domain or requires SQL login. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Authentication credentials for connecting to the Destination SQL Server instance(s). Use this when you need SQL Server authentication instead of Windows authentication. Create credentials using Get-Credential and pass them to this parameter. Required when destination servers use different authentication than your current context. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DisableJobsOnDestination Disables all copied jobs on the destination instance after migration completes. Jobs will exist but won't run until manually enabled. Use this when copying to test environments where you don't want production jobs running automatically, or during staged migrations where jobs should remain inactive initially. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisableJobsOnSource Disables all jobs on the source instance after copying them to destination. Jobs will exist but won't run until manually re-enabled. Use this during server migrations when you want to prevent jobs from running on the old server after moving them to the new instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeServerProperties Skips copying SQL Agent server-level configuration like job history retention settings, error log locations, database mail profiles, and service restart preferences. Use this when you only want to copy jobs and schedules but keep the destination server's existing Agent configuration settings intact. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Overwrites existing Agent objects on destination that have matching names from source. Objects are dropped first, then recreated with source configuration. Use this when you want to ensure destination matches source exactly, replacing any existing jobs, operators, or schedules with conflicting names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (MigrationObject type) Returns one object per destination instance. The object contains details about the Agent server properties migration status. Default display properties: DateTime: The timestamp when the copy operation was executed (DbaDateTime) SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: Description of what was copied (\"Server level properties\") Type: Category of objects copied (\"Agent Properties\") Status: Result of the copy operation (Skipped, Successful, or Failed) Notes: Error message if the operation failed; null if successful or skipped When -ExcludeServerProperties is specified, Status will be \"Skipped\". Otherwise, Status will be \"Successful\" unless an error occurred during the copy operation. &nbsp;"
  },
  {
    "name": "Copy-DbaBackupDevice",
    "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't exist on the destination, files are automatically placed in SQL Server's default backup directory. Existing backup devices are skipped unless -Force is specified to overwrite them.",
    "category": "Migration",
    "tags": [
      "migration",
      "backup"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaBackupDevice",
    "popularityRank": 260,
    "synopsis": "Migrates SQL Server backup devices between instances including both device definitions and physical files",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Copy-DbaBackupDevice View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Migrates SQL Server backup devices between instances including both device definitions and physical files 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. Physical backup files are transferred using admin shares, and if the original directory structure doesn't exist on the destination, files are automatically placed in SQL Server's default backup directory. Existing backup devices are skipped unless -Force is specified to overwrite them. Syntax Copy-DbaBackupDevice [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-BackupDevice] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all server backup devices from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster Copies 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. Example 2: Copies only the backup device named backup01 from sqlserver2014a to sqlcluster using SQL credentials for... PS C:\\> Copy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster -BackupDevice backup01 -SourceSqlCredential $cred -Force Copies 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 name exists on sqlcluster, it will be dropped and recreated because -Force was used. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaBackupDevice -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -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. Use this when migrating backup devices from an existing SQL Server to consolidate backup infrastructure or during server migrations. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. Use this to specify target servers during migrations, disaster recovery setup, or when standardizing backup device configurations across multiple instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Specifies alternative credentials for connecting to the source SQL Server instance. Accepts PowerShell credentials created with Get-Credential. Use this when the source server requires different authentication than your current Windows session, such as SQL Server authentication or a different domain account. Supports Windows Authentication, SQL Server Authentication, Active Directory Password, and Active Directory Integrated. For MFA support, use Connect-DbaInstance first. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Specifies alternative credentials for connecting to the destination SQL Server instances. Accepts PowerShell credentials created with Get-Credential. Use this when destination servers require different authentication than your current Windows session, such as SQL Server authentication or different domain accounts. Supports Windows Authentication, SQL Server Authentication, Active Directory Password, and Active Directory Integrated. For MFA support, use Connect-DbaInstance first. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per backup device processed, containing the status and details of the copy operation. Properties: DateTime: Timestamp when the operation was processed (DbaDateTime object) SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Name: Name of the backup device Type: Always returns \"Backup Device\" Status: Result of the operation (Successful, Skipped, or Failed) Notes: Additional information about the operation (e.g., \"Already exists on destination\" or error details) The 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 additional fields are needed. &nbsp;"
  },
  {
    "name": "Copy-DbaCredential",
    "description": "Copies SQL Server credentials from source to destination instances without losing the original passwords, which normally can't 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/",
    "category": "Migration",
    "tags": [
      "wsman",
      "migration"
    ],
    "verb": "Copy",
    "popular": true,
    "url": "/Copy-DbaCredential",
    "popularityRank": 30,
    "synopsis": "Migrates SQL Server credentials between instances while preserving encrypted passwords.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Copy-DbaCredential View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Migrates SQL Server credentials between instances while preserving encrypted passwords. Description Copies SQL Server credentials from source to destination instances without losing the original passwords, which normally can't 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. This 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. The 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). Credit: Based on password decryption techniques by Antti Rantasaari (NetSPI, 2014) https://blog.netspi.com/decrypting-mssql-database-link-server-passwords/ Syntax Copy-DbaCredential [-Source] [[-SourceSqlCredential] ] [[-Credential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Name] ] [[-ExcludeName] ] [[-Identity] ] [[-ExcludeIdentity] ] [-ExcludePassword] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all SQL Server Credentials on sqlserver2014a to sqlcluster PS C:\\> Copy-DbaCredential -Source sqlserver2014a -Destination sqlcluster Copies all SQL Server Credentials on sqlserver2014a to sqlcluster. If Credentials exist on destination, they will be skipped. Example 2: Copies over one SQL Server Credential (PowerShell Proxy Account) from sqlserver to sqlcluster PS C:\\> Copy-DbaCredential -Source sqlserver2014a -Destination sqlcluster -Name \"PowerShell Proxy Account\" -Force Copies 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. Required Parameters -Source Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2005 or higher. You must be able to open a dedicated admin connection (DAC) to the source SQL Server. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2005 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential) Only used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies the credential names to copy from the source server. Does not supports wildcards for pattern matching. Use this when you only need to migrate specific credentials instead of all credentials on the server. Note: if spaces exist in the credential name, you will have to type \"\" or '' around it. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeName Specifies credential names to exclude from the copy operation. Does not support wildcards for pattern matching. Use this when you want to copy most credentials but skip specific ones like test accounts or deprecated credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Identity Specifies the credential identities (user accounts) to copy from the source server. Does not support wildcards for pattern matching. Use this when you need to migrate credentials for specific service accounts or domain users rather than filtering by credential name. Note: if spaces exist in the credential identity, you will have to type \"\" or '' around it. | Property | Value | | --- | --- | | Alias | CredentialIdentity | | Required | False | | Pipeline | false | | Default Value | | -ExcludeIdentity Specifies credential identities (user accounts) to exclude from the copy operation. Does not support wildcards for pattern matching. Use this when you want to copy most credentials but skip those associated with specific service accounts or domain users. | Property | Value | | --- | --- | | Alias | ExcludeCredentialIdentity | | Required | False | | Pipeline | false | | Default Value | | -ExcludePassword Copies credential definitions without the actual password values. Use this in security-conscious environments where password decryption is restricted or when passwords should be manually reset after migration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Overwrites existing credentials on the destination server by dropping and recreating them with the source values. Use this when you need to update credential passwords or identities that have changed on the source server since the last migration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (MigrationObject type) Returns one object per credential copy operation (successful, skipped, or failed). Properties: DateTime: Timestamp of when the operation was executed (DbaDateTime) SourceServer: The name of the source SQL Server instance where the credential was copied from DestinationServer: The name of the destination SQL Server instance where the credential was copied to Name: The name of the credential that was migrated Type: The type of object migrated (always \"Credential\" for this command) Status: The result of the operation (Successful, Skipping, or Failed) Notes: Additional details about the operation result, such as why a credential was skipped or the reason for failure &nbsp;"
  },
  {
    "name": "Copy-DbaCustomError",
    "description": "Copies user-defined error messages from the source server's 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.",
    "category": "Migration",
    "tags": [
      "migration",
      "customerror"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaCustomError",
    "popularityRank": 406,
    "synopsis": "Migrates custom error messages and their language translations between SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaCustomError View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Migrates custom error messages and their language translations between SQL Server instances Description Copies user-defined error messages from the source server's 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. Custom 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. By 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. Syntax Copy-DbaCustomError [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-CustomError] ] [[-ExcludeCustomError] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all server custom errors from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster Copies 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. Example 2: Copies only the custom error with ID number 60000 from sqlserver2014a to sqlcluster using SQL credentials for... PS C:\\> Copy-DbaCustomError -Source sqlserver2014a -SourceSqlCredential $scred -Destination sqlcluster -DestinationSqlCredential $dcred -CustomError 60000 -Force Copies 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 name exists on sqlcluster, it will be updated because -Force was used. Example 3: Copies all the custom errors found on sqlserver2014a except the custom error with ID number 60000 to... PS C:\\> Copy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster -ExcludeCustomError 60000 -Force Copies 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 -Force was used. Example 4: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaCustomError -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -Source Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CustomError Specifies which custom error message IDs to migrate from the source server. Only the specified error numbers will be copied to the destination. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeCustomError Specifies which custom error message IDs to skip during migration. All custom errors except the excluded ones will be copied. Use this when you want to migrate most custom errors but exclude problematic ones, or when certain error IDs are environment-specific and shouldn't be copied. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Overwrites existing custom errors on the destination server by dropping and recreating them with source values. Use this when you need to update custom error messages that have changed on the source, or when synchronizing error definitions across environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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. Default display properties (via Select-DefaultView): DateTime: Timestamp when the operation occurred SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The custom error ID being migrated Type: The type of object migrated (always \"Custom error\") Status: The outcome of the operation (Successful, Skipped, or Failed) Notes: Additional details about the operation (error message if failed, reason if skipped) &nbsp;"
  },
  {
    "name": "Copy-DbaDatabase",
    "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's 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.",
    "category": "Migration",
    "tags": [
      "migration",
      "backup",
      "restore"
    ],
    "verb": "Copy",
    "popular": true,
    "url": "/Copy-DbaDatabase",
    "popularityRank": 4,
    "synopsis": "Migrates SQL Server databases between instances using backup/restore or detach/attach methods.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaDatabase View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Migrates SQL Server databases between instances using backup/restore or detach/attach methods. 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. Offers 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. Automatically 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's default data and log directories, but you can preserve the original folder structure. Works 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. If you are experiencing issues with Copy-DbaDatabase, please use Backup-DbaDatabase | Restore-DbaDatabase instead. Syntax Copy-DbaDatabase [-Source ] [-SourceSqlCredential ] -Destination [-DestinationSqlCredential ] [-Database ] [-ExcludeDatabase ] [-AllDatabases] -BackupRestore [-AdvancedBackupParams ] [-SharedPath ] [-AzureCredential ] [-WithReplace] [-NoRecovery] [-NoBackupCleanup] [-NumberFiles ] [-SetSourceReadOnly] [-SetSourceOffline] [-ReuseSourceFolderStructure] [-IncludeSupportDbs] [-UseLastBackup] [-Continue] [-InputObject ] [-NoCopyOnly] [-KeepCDC] [-KeepReplication] [-NewName ] [-Prefix ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Copy-DbaDatabase [-Source ] [-SourceSqlCredential ] -Destination [-DestinationSqlCredential ] [-Database ] [-ExcludeDatabase ] [-AllDatabases] [-AzureCredential ] -DetachAttach [-Reattach] [-SetSourceReadOnly] [-SetSourceOffline] [-ReuseSourceFolderStructure] [-IncludeSupportDbs] [-InputObject ] [-NoCopyOnly] [-NewName ] [-Prefix ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Migrates a single user database TestDB using Backup and restore from instance sql2014a to sql2014b PS C:\\> Copy-DbaDatabase -Source sql2014a -Destination sql2014b -Database TestDB -BackupRestore -SharedPath \\\\fileshare\\sql\\migration Migrates a single user database TestDB using Backup and restore from instance sql2014a to sql2014b. Backup files are stored in \\\\fileshare\\sql\\migration. Example 2: Databases will be migrated from sql2012 to both sql2014 and sql2016 using the detach/copy files/attach method PS C:\\> Copy-DbaDatabase -Source sql2012 -Destination sql2014, sql2016 -DetachAttach -Reattach Databases 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 files, 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 destination* exist and aren't in use, they will be overwritten. Example 3: Migrates all user databases to sqlcluster and sql2016 using the last Full, Diff and Log backups from sql204a PS C:\\> Copy-DbaDatabase -Source sql2014a -Destination sqlcluster, sql2016 -BackupRestore -UseLastBackup -Force Migrates 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. Note that the backups must exist in a location accessible by all destination servers, such a network share. Example 4: Migrates all user databases except for Northwind and pubs by using backup/restore (copy-only) PS C:\\> Copy-DbaDatabase -Source sql2014a -Destination sqlcluster -ExcludeDatabase Northwind, pubs -IncludeSupportDbs -Force -BackupRestore -SharedPath \\\\fileshare\\sql\\migration Migrates 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 be dropped prior to attach. It also includes the support databases (ReportServer, ReportServerTempDb, SSISDB, distribution). Example 5: https://someblob.blob.core.windows.net/sql Migrate all user databases from instance sql2014 to the specified... PS C:\\> Copy-DbaDatabase -Source sql2014 -Destination managedinstance.cus19c972e4513d6.database.windows.net -DestinationSqlCredential $cred -AllDatabases -BackupRestore -SharedPath https://someblob.blob.core.windows.net/sql Migrate 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 (SAS) credential with a name matching the blob storage account Example 6: -SharedPath https://someblob.blob.core.windows.net/sql -AzureCredential AzBlobCredential Migrates Mydb from... PS C:\\> Copy-DbaDatabase -Source sql2014 -Destination managedinstance.cus19c972e4513d6.database.windows.net -DestinationSqlCredential $cred -Database MyDb -NewName AzureDb -WithReplace -BackupRestore -SharedPath https://someblob.blob.core.windows.net/sql -AzureCredential AzBlobCredential Migrates 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 https://someblob.blob.core.windows.net/sql using the Sql Server Credential AzBlobCredential Example 7: Migrates all user databases to sqlcluster PS C:\\> Copy-DbaDatabase -Source sql2014a -Destination sqlcluster -BackupRestore -SharedPath \\\\FS\\Backup -AdvancedBackupParams @{ CompressBackup = $true } Migrates all user databases to sqlcluster. Uses the parameter CompressBackup with the backup command to save some space on the shared path. Example 8: Copies database t from sqlcs to the same server (sqlcs) using the detach/copy/attach method PS C:\\> Copy-DbaDatabase -Source sqlcs -Destination sqlcs -Database t -DetachAttach -NewName t_copy -Reattach Copies 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. Required Parameters -Destination Specifies one or more destination SQL Server instances where databases will be migrated. Supports on-premises instances and Azure SQL Managed Instances for cloud migrations. When targeting multiple destinations, backups are performed once and shared across all targets. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -BackupRestore Uses backup and restore method for database migration, creating copy-only backups to preserve existing backup chains. This is the safest method for cross-version migrations and works with Azure blob storage. Requires either -SharedPath for backup location or -UseLastBackup to use existing backups. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | False | -DetachAttach Uses detach/copy/attach method for database migration by moving physical database files. This method is faster than backup/restore but requires same SQL Server versions and administrative share access. Source databases are automatically reattached if destination attachment fails. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | False | Optional Parameters -Source Specifies the source SQL Server instance containing the databases to migrate. Supports named instances, clusters, and SQL Server Express editions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SourceSqlCredential Specifies credentials for connecting to the source SQL Server instance when Windows authentication is not available. Use this when the source server requires SQL authentication or when running under a different security context. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Specifies credentials for connecting to the destination SQL Server instance when Windows authentication is not available. Required for Azure SQL Managed Instance destinations or when destination requires SQL authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which user databases to migrate by name. Use this when you need to migrate specific databases rather than all databases on the instance. Supports tab completion from the source instance and accepts multiple database names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to exclude when using -AllDatabases. Use this to skip problematic databases like those in use, under maintenance, or containing sensitive data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllDatabases Migrates all user databases from the source instance, excluding system databases (master, model, msdb, tempdb). Use this for full server migrations or when moving all business databases to a new instance. | Property | Value | | --- | --- | | Alias | All | | Required | False | | Pipeline | false | | Default Value | False | -AdvancedBackupParams Specifies additional parameters for the backup operation as a hashtable. Use this to enable compression (@{CompressBackup = $true}), checksum verification, or other backup options. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SharedPath Specifies the storage location accessible by both source and destination SQL Server instances. Accepts local paths (C:\\Backups), UNC shares (\\\\server\\backups), or Azure blob storage URLs. SQL Server service accounts on both instances must have read/write permissions to this location. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AzureCredential Specifies the SQL Server credential name for Azure blob storage authentication. Required when using storage access keys with Azure blob storage paths. For SAS tokens, the credential name should match the Azure storage URL. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -WithReplace Overwrites existing databases at the destination with the same name. Use this when refreshing existing databases or when you want to replace destination databases completely. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoRecovery Restores databases in NORECOVERY mode, leaving them ready for additional transaction log restores. Use this for staging environments or when setting up log shipping scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoBackupCleanup Preserves backup files after migration instead of automatically deleting them. Use this when you want to keep backups for additional restores or compliance requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NumberFiles Specifies how many backup files to create for each database backup to improve performance. Default is 3 files, which provides good parallelism for most databases. Increase for very large databases or high-performance storage systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 3 | -Reattach Reattaches databases to the source instance after successful detach/attach migration. Required when using -DetachAttach with multiple destination servers to restore source functionality. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SetSourceReadOnly Sets source databases to read-only before migration to prevent data changes during the process. Use this to ensure data consistency when databases must remain accessible at the source during migration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SetSourceOffline Sets source databases offline before migration to prevent any connections during the process. Use this to ensure complete isolation when databases must be completely inaccessible at the source during migration. When combined with -Reattach, databases are brought back online after being reattached to the source. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ReuseSourceFolderStructure Maintains the exact file path structure from the source instance on the destination. Use this when destination servers have identical drive layouts or when preserving specific organizational folder structures. The destination instance must have matching directory paths available. | Property | Value | | --- | --- | | Alias | ReuseFolderStructure | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSupportDbs Migrates SQL Server feature databases including ReportServer, ReportServerTempDB, SSISDB, and distribution databases. Use this when migrating servers that host Reporting Services, Integration Services, or replication components. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UseLastBackup Uses existing backups from backup history instead of creating new ones. The most recent full, differential, and log backups must be accessible to all destination servers. Useful for migration scenarios where fresh backups already exist. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Continue Continues restoration by applying transaction log backups to databases in RECOVERING or STANDBY states. Use this with -UseLastBackup when resuming interrupted restore operations or applying additional log backups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database objects piped from Get-DbaDatabase for migration. Use this to migrate databases filtered by specific criteria like size, compatibility level, or other properties. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -NoCopyOnly Creates regular backups instead of copy-only backups, which affects the database's backup chain. Only use this when you want migration backups to be part of the regular backup sequence. Default copy-only behavior preserves existing backup chains and is recommended for migrations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepCDC Preserves Change Data Capture (CDC) configuration and data during migration. Use this when destination databases need to maintain CDC tracking for auditing or replication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepReplication Preserves replication configuration during database migration. Use this when migrating publisher or subscriber databases that participate in replication topologies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NewName Renames the database during migration when copying a single database. The database name and physical file names are updated to use the new name. Cannot be used with multiple databases or together with -Prefix parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Prefix Adds a prefix to all migrated database names and their physical file names. Use this to distinguish migrated databases (e.g., 'DEV_' prefix for development copies). Cannot be used together with -NewName parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Forcibly overwrites existing databases at the destination and bypasses safety checks. Breaks database mirroring, removes databases from Availability Groups, and rolls back blocking transactions. Use with caution as this will permanently destroy existing destination databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database migrated, with the following properties: DateTime: The timestamp when the migration status was recorded (DbaDateTime) SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The original database name on the source instance DestinationDatabase: The database name on the destination instance (may differ if -NewName or -Prefix was used) Type: The migration method used - either \"Database (BackupRestore)\" or \"Database (DetachAttach)\" Status: The outcome of the migration operation (Successful, Failed, or Skipped) Notes: Additional details about the migration, including reasons for failure or skip conditions &nbsp;"
  },
  {
    "name": "Copy-DbaDataCollector",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "datacollection"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaDataCollector",
    "popularityRank": 331,
    "synopsis": "Copies SQL Data Collector collection sets from one instance to another",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Copy-DbaDataCollector View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies SQL Data Collector collection sets from one instance to another 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. By 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. The -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. Syntax Copy-DbaDataCollector [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-CollectionSet] ] [[-ExcludeCollectionSet] ] [-NoServerReconfig] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all Data Collector Objects and Configurations from sqlserver2014a to sqlcluster, using Windows... PS C:\\> Copy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster Copies all Data Collector Objects and Configurations from sqlserver2014a to sqlcluster, using Windows credentials. Example 2: Copies all Data Collector Objects and Configurations from sqlserver2014a to sqlcluster, using SQL credentials... PS C:\\> Copy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred Copies all Data Collector Objects and Configurations from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. Example 3: Shows what would happen if the command were executed PS C:\\> Copy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -WhatIf Example 4: Copies two Collection Sets, Server Activity and Table Usage Analysis, from sqlserver2014a to sqlcluster PS C:\\> Copy-DbaDataCollector -Source sqlserver2014a -Destination sqlcluster -CollectionSet 'Server Activity', 'Table Usage Analysis' Required Parameters -Source Source SQL Server instance containing the Data Collector collection sets to copy. Requires sysadmin access and SQL Server 2008 or higher. The Data Collector feature must be configured on this instance for collection sets to exist. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Destination SQL Server instance(s) where collection sets will be created. Requires sysadmin access and SQL Server 2008 or higher. The Data Collector feature must already be configured and enabled on the destination before running this command. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Login credentials for the source SQL Server instance. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login credentials for the destination SQL Server instance(s). Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CollectionSet Specific collection set names to copy from the source instance. Supports tab completion with available collection sets. When omitted, all user-defined collection sets are copied (system collection sets are always excluded). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeCollectionSet Collection set names to exclude from the copy operation. Supports tab completion with available collection sets. Useful when you want to copy most collection sets but skip specific ones due to environment differences. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoServerReconfig Reserved parameter for future Data Collector server configuration copying functionality. Currently has no effect as server-level configuration copying is not yet implemented. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Drops and recreates collection sets that already exist on the destination server. Without this switch, existing collection sets are skipped to prevent accidental data loss. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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 destination instance. Properties: DateTime: The date and time the operation was performed (DbaDateTime type) SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The name of the collection set or configuration item being copied Type: The type of object being copied (e.g., \"Collection Set\", \"Data Collection Server Config\") Status: Result of the operation (Successful, Skipped, Failed, etc.) Notes: Additional information about the operation, such as skip reasons or error details &nbsp;"
  },
  {
    "name": "Copy-DbaDbAssembly",
    "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're 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.",
    "category": "Migration",
    "tags": [
      "migration",
      "assembly"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaDbAssembly",
    "popularityRank": 297,
    "synopsis": "Copies CLR assemblies from source databases to destination SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaDbAssembly View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies CLR assemblies from source databases to destination SQL Server instances 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. Designed for database migration scenarios where applications rely on custom .NET assemblies registered in SQL Server. If assemblies already exist on the destination, they're skipped unless you use -Force to drop and recreate them. The function does not copy assembly dependencies or dependent objects like CLR stored procedures, functions, or user-defined types that reference the assemblies. Syntax Copy-DbaDbAssembly [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Assembly] ] [[-ExcludeAssembly] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all assemblies from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster Copies all assemblies from sqlserver2014a to sqlcluster using Windows credentials. If assemblies with the same name exist on sqlcluster, they will be skipped. Example 2: Copies two assemblies, the dbname.assemblyname and dbname3.anotherassembly from sqlserver2014a to sqlcluster... PS C:\\> Copy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster -Assembly dbname.assemblyname, dbname3.anotherassembly -SourceSqlCredential $cred -Force Copies two assemblies, the dbname.assemblyname and dbname3.anotherassembly from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. If an assembly with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used. In this example, anotherassembly will be copied to the dbname3 database on the server sqlcluster. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaDbAssembly -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -Source Source SQL Server instance containing the CLR assemblies to copy. Requires sysadmin access to scan all accessible databases for user-created assemblies. The function will inventory all custom assemblies across every database on this instance for migration. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Target SQL Server instance(s) where CLR assemblies will be created. Accepts multiple destinations to copy assemblies to several servers simultaneously. Requires sysadmin access and corresponding databases must already exist on the destination for assembly migration to succeed. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Alternative credentials for connecting to the source SQL Server instance. Use this when your current Windows credentials don't have sysadmin access to the source server. Accepts PowerShell credential objects created with Get-Credential and supports SQL Server Authentication or Active Directory authentication methods. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Alternative credentials for connecting to the destination SQL Server instance(s). Use this when your current Windows credentials don't have sysadmin access to the target servers. Accepts PowerShell credential objects created with Get-Credential and supports SQL Server Authentication or Active Directory authentication methods. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Assembly Specific CLR assemblies to copy instead of migrating all assemblies. Use the format 'DatabaseName.AssemblyName' to target assemblies in specific databases. This is useful when you only need to migrate certain assemblies rather than performing a full assembly migration across all databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeAssembly CLR assemblies to skip during the migration process. Use the format 'DatabaseName.AssemblyName' to exclude specific assemblies from specific databases. This is helpful when you want to migrate most assemblies but need to skip problematic or obsolete ones that shouldn't be copied to the destination. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Drops existing assemblies on the destination before recreating them from the source. By default, assemblies that already exist are skipped. Use this when you need to overwrite destination assemblies with updated versions from the source, but be aware that assemblies with dependencies cannot be dropped. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs MigrationObject (PSCustomObject) Returns one object per assembly processed, documenting the copy operation result for each assembly migration attempt. Default display properties (via Select-DefaultView): DateTime: Timestamp when the operation was performed SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Name: Name of the assembly being copied Type: Always \"Database Assembly\" indicating the object type Status: Result of the operation (Successful, Skipped, or Failed) Notes: Additional information about why the operation was skipped or failed (null if successful) Additional properties available: SourceDatabase: Database name on the source server containing the assembly SourceDatabaseID: Unique identifier of the source database DestinationDatabase: Database name on the destination server DestinationDatabaseID: Unique identifier of the destination database &nbsp;"
  },
  {
    "name": "Copy-DbaDbCertificate",
    "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's 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't 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.",
    "category": "Migration",
    "tags": [
      "migration",
      "certificate"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaDbCertificate",
    "popularityRank": 105,
    "synopsis": "Copies database-level certificates from source SQL Server to destination servers, including private keys and master key dependencies.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaDbCertificate View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies database-level certificates from source SQL Server to destination servers, including private keys and master key dependencies. 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's essential when moving databases with Transparent Data Encryption (TDE) or other certificate-based security features. The 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't exist and you provide the MasterKeyPassword parameter. Existing certificates are skipped unless you use the Force parameter to overwrite them. This 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. Syntax Copy-DbaDbCertificate [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Certificate] ] [[-ExcludeCertificate] ] [[-SharedPath] ] [[-MasterKeyPassword] ] [[-EncryptionPassword] ] [[-DecryptionPassword] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies database certificates for matching databases on sql02 and creates master keys if needed Uses password... PS C:\\> Copy-DbaDbCertificate -Source sql01 -Destination sql02 -EncryptionPassword $cred.Password -MasterKeyPassword $cred.Password -SharedPath \\\\nas\\sql\\shared Copies database certificates for matching databases on sql02 and creates master keys if needed Uses password from $cred object created by Get-Credential Example 2: Copies database certificates for matching databases on sql02 and creates master keys if needed PS C:\\> $params1 = @{ >> Source = \"sql01\" >> Destination = \"sql02\" >> EncryptionPassword = $passwd >> MasterKeyPassword = $passwd >> SharedPath = \"\\\\nas\\sql\\shared\" >> } PS C:\\> Copy-DbaDbCertificate @params1 -Confirm:$false -OutVariable results Required Parameters -Source The source SQL Server instance containing the database certificates to copy. Requires sysadmin privileges to access certificate metadata and backup operations. Use this to specify where the certificates currently exist that need to be migrated to other servers. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination The destination SQL Server instance(s) where certificates will be restored. Accepts multiple servers for bulk certificate deployment. Requires sysadmin privileges to create master keys and restore certificates to matching databases. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. Essential for cross-domain scenarios or when running under service accounts that don't have source server access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Alternative credentials for connecting to destination SQL Server instance(s). Required when destination servers are in different domains or when using SQL authentication. Must have permissions to create database master keys and restore certificates in target databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to include when copying certificates. Only certificates from these databases will be migrated to matching databases on destination servers. Use this to limit certificate copying to specific databases rather than processing all databases with certificates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from certificate copying operations. Certificates in these databases will be skipped even if they exist on the source. Useful when you want to copy most database certificates but exclude system databases or specific application databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Certificate Specifies which certificates to copy by name. Only these named certificates will be processed across all included databases. Use this to migrate specific certificates like TDE certificates while leaving other database certificates untouched. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeCertificate Excludes specific certificates from the copying process by name. These certificates will be skipped in all databases. Commonly used to exclude system-generated certificates or certificates that should remain environment-specific. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Required because certificates cannot be directly transferred between instances and must be backed up to disk first. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MasterKeyPassword Password for creating database master keys on destination servers when they don't exist. Required for certificates that use master key encryption. Essential for TDE scenarios where certificates depend on database master keys for private key protection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EncryptionPassword Secure password used to encrypt the private key during certificate backup operations. If not provided, a random password is generated automatically. Specify this when you need consistent encryption passwords across multiple certificate operations or for compliance requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when copying certificates that were previously backed up with a specific encryption password. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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 destination database. Default display properties (via Select-DefaultView with TypeName MigrationObject): DateTime: The date and time when the copy operation occurred SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The name of the certificate being copied Type: Always \"Database Certificate\" indicating the object type Status: The result of the operation (Successful, Skipped, or Failed) Notes: Additional information about the operation (reason for skipping, error details, etc.) Additional properties available (not shown by default): SourceDatabase: The name of the source database containing the certificate SourceDatabaseID: The ID of the source database DestinationDatabase: The name of the destination database where the certificate was restored DestinationDatabaseID: The ID of the destination database All properties from the PSCustomObject are accessible via Select-Object * even though only default properties display without explicitly using Select-Object. &nbsp;"
  },
  {
    "name": "Copy-DbaDbMail",
    "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's enabled on the source. You can migrate specific component types or the entire configuration in one operation.",
    "category": "Migration",
    "tags": [
      "migration",
      "mail"
    ],
    "verb": "Copy",
    "popular": true,
    "url": "/Copy-DbaDbMail",
    "popularityRank": 35,
    "synopsis": "Copies Database Mail configuration including profiles, accounts, mail servers and settings between SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaDbMail View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies Database Mail configuration including profiles, accounts, mail servers and settings between SQL Server instances. 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. Database 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. The 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's enabled on the source. You can migrate specific component types or the entire configuration in one operation. Syntax Copy-DbaDbMail -Source [-SourceSqlCredential ] -Destination [-DestinationSqlCredential ] [-Credential ] [-ExcludePassword] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Copy-DbaDbMail -Source [-SourceSqlCredential ] -Destination [-DestinationSqlCredential ] [-Credential ] [-Type ] [-ExcludePassword] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all database mail objects from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster Copies 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. Example 2: Copies all database mail objects from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a... PS C:\\> Copy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred Copies all database mail objects from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. Example 3: Shows what would happen if the command were executed PS C:\\> Copy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -WhatIf Example 4: Performs execution of function, and will throw a terminating exception if something breaks PS C:\\> Copy-DbaDbMail -Source sqlserver2014a -Destination sqlcluster -EnableException Required Parameters -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. You must have sysadmin privileges to access the MSDB database where Database Mail settings are stored. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. You must have sysadmin privileges on each destination to create mail profiles, accounts, and server configurations in MSDB. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential) Only used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Limits migration to specific Database Mail component types instead of copying everything. Choose 'ConfigurationValues' for global settings like retry attempts and file size limits, 'Profiles' for mail profile definitions, 'Accounts' for SMTP account configurations, or 'MailServers' for SMTP server details. Use this when you only need to sync specific components or when troubleshooting individual Database Mail layers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | ConfigurationValues,Profiles,Accounts,MailServers | -ExcludePassword Copies credential definitions without the actual password values. Use this in security-conscious environments where password decryption is restricted or when passwords should be manually reset after migration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 accidental data loss. Use this when updating existing Database Mail configurations or when you need to replace outdated settings with current ones from the source server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (MigrationObject) Returns one object per Database Mail component migrated (configuration, profile, account, or mail server). Each object tracks the migration status of a single component. Properties: DateTime: Timestamp when the migration operation was performed (Dataplat.Dbatools.Utility.DbaDateTime) SourceServer: The source SQL Server instance name DestinationServer: The destination SQL Server instance name Name: The name of the Database Mail component being migrated (profile name, account name, server name, or \"Server Configuration\") Type: Category of the component migrated - \"Mail Configuration\", \"Mail Profile\", \"Mail Account\", or \"Mail Server\" Status: Migration result status - \"Successful\", \"Skipped\", or \"Failed\" Notes: Additional details about the migration outcome (reason for skip, error message, etc.). Null if no additional notes. &nbsp;"
  },
  {
    "name": "Copy-DbaDbQueryStoreOption",
    "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.",
    "category": "Migration",
    "tags": [
      "querystore"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaDbQueryStoreOption",
    "popularityRank": 424,
    "synopsis": "Replicates Query Store configuration settings from one database to multiple target databases across instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaDbQueryStoreOption View Source Enrico van de Laar (@evdlaar) , Tracy Boggiano (@Tracy Boggiano) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Replicates Query Store configuration settings from one database to multiple target databases across instances. 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. Syntax Copy-DbaDbQueryStoreOption [-Source] [[-SourceSqlCredential] ] [-SourceDatabase] [-Destination] [[-DestinationSqlCredential] ] [[-DestinationDatabase] ] [[-Exclude] ] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copy the Query Store configuration of the AdventureWorks database in the ServerA\\SQL instance and apply it on... PS C:\\> Copy-DbaDbQueryStoreOption -Source ServerA\\SQL -SourceDatabase AdventureWorks -Destination ServerB\\SQL -AllDatabases Copy 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. Example 2: Copy the Query Store configuration of the AdventureWorks database in the ServerA\\SQL instance and apply it to... PS C:\\> Copy-DbaDbQueryStoreOption -Source ServerA\\SQL -SourceDatabase AdventureWorks -Destination ServerB\\SQL -DestinationDatabase WorldWideTraders Copy 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. Required Parameters -Source The SQL Server instance containing the database with Query Store configuration you want to copy from. You must have sysadmin access and server version must be SQL Server 2016 or higher since Query Store was introduced in SQL Server 2016. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -SourceDatabase The database containing the Query Store configuration you want to replicate to other databases. This database should have Query Store enabled with settings you've tested and want to standardize across your environment. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Destination The SQL Server instance(s) where you want to apply the Query Store configuration to target databases. You must have sysadmin access and the server must be SQL Server 2016 or higher. Supports multiple destination instances for bulk configuration deployment. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SourceSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationDatabase Specifies which specific databases should receive the Query Store configuration from the source database. Use this when you want to apply settings to selected databases rather than all databases on the destination instance. Cannot be used together with AllDatabases parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Exclude Databases to skip when copying Query Store configuration, useful when using AllDatabases but want to exclude specific databases. System databases are automatically excluded since Query Store cannot be enabled on them. Commonly used to exclude test databases or databases with special Query Store requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllDatabases Applies the Query Store configuration to all user databases on the destination instance. System databases are automatically excluded since Query Store is not supported on them. Use this for standardizing Query Store settings across an entire instance, optionally combined with Exclude parameter for exceptions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per destination database processed, representing the status of copying Query Store configuration to that database. Default display properties (via Select-DefaultView): DateTime: Timestamp of the operation (Dataplat.Dbatools.Utility.DbaDateTime) SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Name: Name of the destination database receiving the configuration Type: Always \"QueryStore Configuration\" Status: Result of the operation (\"Skipped\", \"Successful\", or \"Failed\") Notes: Error message if Status is \"Failed\", otherwise null *Additional properties available via Select-Object :** SourceDatabase: Name of the source database containing the Query Store configuration to copy SourceDatabaseID: Database ID of the source database DestinationDatabaseID: Database ID of the destination database &nbsp;"
  },
  {
    "name": "Copy-DbaDbTableData",
    "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.",
    "category": "Migration",
    "tags": [
      "table",
      "data"
    ],
    "verb": "Copy",
    "popular": true,
    "url": "/Copy-DbaDbTableData",
    "popularityRank": 12,
    "synopsis": "Streams table data between SQL Server instances using high-performance bulk copy operations.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaDbTableData View Source Simone Bizzotto (@niphlod) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Streams table data between SQL Server instances using high-performance bulk copy operations. Description Copies data between SQL Server tables using SQL Bulk Copy for maximum performance and minimal memory usage. Unlike Invoke-DbaQuery and Write-DbaDbTableData which buffer entire table contents in memory, this function streams data directly from source to destination. This approach prevents memory exhaustion when copying large tables and provides the fastest data transfer method available. Supports copying between different servers, databases, and schemas while preserving data integrity options like identity values, constraints, and triggers. Can automatically create destination tables based on source table structure, making it ideal for data migration, ETL processes, and table replication tasks. Note: System-versioned temporal tables require special handling. The -AutoCreateTable parameter does not support temporal table creation. When copying to an existing temporal table, use the -Query parameter to exclude GENERATED ALWAYS columns (e.g., ValidFrom, ValidTo). Temporal version history cannot be preserved as these values are system-managed. Syntax Copy-DbaDbTableData [[-SqlInstance] ] [[-SqlCredential] ] [[-Destination] ] [[-DestinationSqlCredential] ] [[-Database] ] [[-DestinationDatabase] ] [[-Table] ] [[-View] ] [[-Query] ] [-ForceExplicitMapping] [-AutoCreateTable] [[-BatchSize] ] [[-NotifyAfter] ] [[-DestinationTable] ] [-NoTableLock] [-CheckConstraints] [-FireTriggers] [-KeepIdentity] [-KeepNulls] [-Truncate] [[-BulkCopyTimeout] ] [[-CommandTimeout] ] [-UseDefaultFileGroup] [[-ScriptingOptionsObject] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all the data from table dbo.test_table (2-part name) in database dbatools_from on sql1 to table... PS C:\\> Copy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -Table dbo.test_table Copies 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. Example 2: Copies all the data from table [Schema].[test table] (2-part name) in database dbatools_from on sql1 to table... PS C:\\> Copy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -DestinationDatabase dbatools_dest -Table [Schema].[test table] Copies 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 Example 3: Copies all data from tables tb1 and tb2 in tempdb on sql1 to tb3 in tempdb on sql1 PS C:\\> Get-DbaDbTable -SqlInstance sql1 -Database tempdb -Table tb1, tb2 | Copy-DbaDbTableData -DestinationTable tb3 Example 4: Copies data from tb1 and tb2 in tempdb on sql1 to the same table in tempdb on sql2 PS C:\\> Get-DbaDbTable -SqlInstance sql1 -Database tempdb -Table tb1, tb2 | Copy-DbaDbTableData -Destination sql2 Example 5: Copies all the data in table test_table from sql1 to sql2, using the database dbatools_from, keeping identity... PS C:\\> Copy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -Table test_table -KeepIdentity -Truncate Copies all the data in table test_table from sql1 to sql2, using the database dbatools_from, keeping identity columns and truncating the destination Example 6: Copies all the data from table [Schema].[Table] (2-part name) in database dbatools_from on sql1 to table... PS C:\\> $params = @{ >> SqlInstance = 'sql1' >> Destination = 'sql2' >> Database = 'dbatools_from' >> DestinationDatabase = 'dbatools_dest' >> Table = '[Schema].[Table]' >> DestinationTable = '[dbo].[Table.Copy]' >> KeepIdentity = $true >> KeepNulls = $true >> Truncate = $true >> BatchSize = 10000 >> } >> PS C:\\> Copy-DbaDbTableData @params Copies 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 Keeps identity columns and Nulls, truncates the destination and processes in BatchSize of 10000. Example 7: Copies data returned from the query on server1 into the AdventureWorks2017 on server1, using a 3-part name... PS C:\\> $params = @{ >> SqlInstance = 'server1' >> Destination = 'server1' >> Database = 'AdventureWorks2017' >> DestinationDatabase = 'AdventureWorks2017' >> DestinationTable = '[AdventureWorks2017].[Person].[EmailPromotion]' >> BatchSize = 10000 >> Table = '[OtherDb].[Person].[Person]' >> Query = \"SELECT * FROM [OtherDb].[Person].[Person] where EmailPromotion = 1\" >> } >> PS C:\\> Copy-DbaDbTableData @params Copies 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. See the Query param documentation for more details. Example 8: Copies all data from [tempdb].[dbo].[vw1] (3-part name) view on instance sql1 to an auto-created table... PS C:\\> Copy-DbaDbTableData -SqlInstance sql1 -Database tempdb -View [tempdb].[dbo].[vw1] -DestinationTable [SampleDb].[SampleSchema].[SampleTable] -AutoCreateTable Copies all data from [tempdb].[dbo].[vw1] (3-part name) view on instance sql1 to an auto-created table [SampleDb].[SampleSchema].[SampleTable] on instance sql1 Example 9: Copies all data from dbo.MyTable in db1 on sql1 to an auto-created table on sql2, scripting the destination... PS C:\\> $so = New-DbaScriptingOption PS C:\\> $so.DriAll = $true PS C:\\> $so.Indexes = $true PS C:\\> $so.NoFileGroup = $true PS C:\\> Copy-DbaDbTableData -SqlInstance sql1 -Destination sql2 -Database db1 -Table dbo.MyTable -AutoCreateTable -ScriptingOptionsObject $so Copies all data from dbo.MyTable in db1 on sql1 to an auto-created table on sql2, scripting the destination table with all constraints, indexes, and using the default filegroup. Example 10: Copies schema data from sys.schemas to a table with an identity column PS C:\\> $params = @{ >> SqlInstance = \"SERVER001\" >> Database = \"MyDatabaseName\" >> View = \"sys.schemas\" >> Query = \"SELECT 0, DB_NAME(), [name] FROM sys.schemas\" >> Destination = \"SERVER002\" >> DestinationDatabase = \"MyOtherDatabaseName\" >> DestinationTable = \"syscollect.stage_map_schema_id\" >> } >> PS C:\\> Copy-DbaDbTableData @params Copies schema data from sys.schemas to a table with an identity column. The first SELECT column (0) is a placeholder for the destination's identity column. Since -KeepIdentity is not specified, the destination auto-generates identity values and ignores the placeholder. Columns are mapped by position: 0 â†’ ID (ignored), DB_NAME() â†’ database_name, [name] â†’ schema_name. Optional Parameters -SqlInstance Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the source instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Destination Target SQL Server instance where table data will be copied to. Accepts one or more SQL Server instances. Specify this when copying data to a different server than the source, or when doing cross-instance data transfers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Alternative credentials for authenticating to the destination instance. Required when your current Windows credentials don't have access to the target server. Use this for cross-domain scenarios, SQL authentication, or when the destination requires different security context than the source. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Source database containing the table or view to copy data from. Required when not using pipeline input. Must exist on the source instance and your account must have read permissions on the specified objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationDatabase Target database where copied data will be inserted. Defaults to the same database name as the source. Use this when copying data to a different database name on the destination instance or for cross-database copies within the same server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Source table name to copy data from. Accepts 2-part ([schema].[table]) or 3-part ([database].[schema].[table]) names. Use square brackets for names with spaces or special characters. Cannot be used simultaneously with the View parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -View Source view name to copy data from. Accepts 2-part ([schema].[view]) or 3-part ([database].[schema].[view]) names. Use square brackets for names with spaces or special characters. Cannot be used simultaneously with the Table parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. Note: 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. The placeholder will be ignored and the identity value auto-generated unless -KeepIdentity is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Default 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 not copying. The 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AutoCreateTable Automatically creates the destination table if it doesn't exist, using the same structure as the source table. Essential for initial data migrations or when copying to new environments where destination tables haven't been created yet. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BatchSize Number of rows to process in each bulk copy batch. Defaults to 50000 rows. Reduce this value for memory-constrained systems or increase it for faster transfers when copying large tables with sufficient memory. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 50000 | -NotifyAfter Number of rows to process before displaying progress updates. Defaults to 5000 rows. Set to a lower value for frequent updates on small tables or higher for less verbose output on large table copies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 5000 | -DestinationTable Target table name where data will be inserted. Defaults to the same name as the source table. Use this when copying to a table with a different name or schema, or when specifying 3-part names for cross-database operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoTableLock Disables the default table lock (TABLOCK) on the destination table during bulk copy operations. Use this when you need to allow concurrent read access to the destination table, though it may reduce bulk copy performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CheckConstraints Enables constraint checking during bulk copy operations. By default, constraints are ignored for performance. Use this when data integrity validation is more important than copy speed, particularly when copying from untrusted sources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FireTriggers Enables INSERT triggers to fire during bulk copy operations. By default, triggers are bypassed for performance. Use this when you need audit trails, logging, or other trigger-based business logic to execute during the data copy. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepIdentity Preserves the original identity column values from the source table. By default, the destination generates new identity values. Essential when copying reference tables or when you need to maintain exact ID relationships across systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepNulls Preserves NULL values from the source data instead of replacing them with destination column defaults. Use this when you need exact source data reproduction, especially when NULL has specific business meaning versus default values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Truncate Removes all existing data from the destination table before copying new data. Prompts for confirmation unless -Force is used. Essential for refresh scenarios where you want to replace all destination data with current source data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BulkCopyTimeout Maximum time in seconds to wait for bulk copy operations to complete. Defaults to 5000 seconds (83 minutes). Increase this value when copying very large tables that may take longer than the default timeout period. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 5000 | -CommandTimeout Maximum time in seconds to wait for the source query execution before timing out. Defaults to 0 (no timeout). Set this when querying large tables or complex views that may take longer to read than typical query timeouts allow. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -UseDefaultFileGroup Creates new tables using the destination database's default filegroup instead of matching the source table's filegroup name. Use this when the destination database has different filegroup configurations or when you want all copied tables in the PRIMARY filegroup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ScriptingOptionsObject A scripting options object created by New-DbaScriptingOption that controls how the destination table is scripted when -AutoCreateTable is used. Use this to control which table properties are included in the CREATE TABLE script, such as indexes, constraints, triggers, and extended properties. When specified, this takes precedence over -UseDefaultFileGroup. Use New-DbaScriptingOption to create the object and set the desired properties. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts table or view objects from Get-DbaDbTable or Get-DbaDbView for pipeline operations. Use this to copy multiple tables efficiently by piping them from discovery commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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 object per table. Properties: SourceInstance: The name of the source SQL Server instance SourceDatabase: The name of the source database SourceDatabaseID: The unique identifier (ID) of the source database SourceSchema: The schema name of the source table or view SourceTable: The name of the source table or view DestinationInstance: The name of the destination SQL Server instance DestinationDatabase: The name of the destination database DestinationDatabaseID: The unique identifier (ID) of the destination database DestinationSchema: The schema name of the destination table DestinationTable: The name of the destination table RowsCopied: The total number of rows that were successfully copied (Int64). Supports values greater than 2.1 billion rows. Elapsed: The elapsed time as a TimeSpan object representing the duration of the copy operation &nbsp;"
  },
  {
    "name": "Copy-DbaDbViewData",
    "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.",
    "category": "Migration",
    "tags": [
      "table",
      "data"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaDbViewData",
    "popularityRank": 154,
    "synopsis": "Copies data from SQL Server views to destination tables using high-performance bulk copy operations.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaDbViewData View Source Stephen Swan (@jaxnoth) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies data from SQL Server views to destination tables using high-performance bulk copy operations. Description Extracts data from SQL Server views and bulk copies it to destination tables, either on the same instance or across different servers. Uses SqlBulkCopy for optimal performance when migrating view data, materializing view results, or creating data snapshots from complex views. Supports custom queries against views, identity preservation, constraint checking, and automatic destination table creation. Handles large datasets efficiently with configurable batch sizes and minimal resource overhead compared to traditional INSERT statements. Syntax Copy-DbaDbViewData [[-SqlInstance] ] [[-SqlCredential] ] [[-Destination] ] [[-DestinationSqlCredential] ] [[-Database] ] [[-DestinationDatabase] ] [[-View] ] [[-Query] ] [-AutoCreateTable] [[-BatchSize] ] [[-NotifyAfter] ] [[-DestinationTable] ] [-NoTableLock] [-CheckConstraints] [-FireTriggers] [-KeepIdentity] [-KeepNulls] [-Truncate] [[-BulkCopyTimeOut] ] [[-ScriptingOptionsObject] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all the data from view dbo.test_view (2-part name) in database dbatools_from on sql1 to view test_view... PS C:\\> Copy-DbaDbViewData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -View dbo.test_view Copies 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. Example 2: Copies all the data from view [Schema].[test view] (2-part name) in database dbatools_from on sql1 to table... PS C:\\> Copy-DbaDbViewData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -DestinationDatabase dbatools_dest -DestinationTable [Schema].[test table] Copies 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 Example 3: Copies all data from Views vw1 and vw2 in tempdb on sql1 to tb3 in tempdb on sql1 PS C:\\> Get-DbaDbView -SqlInstance sql1 -Database tempdb -View vw1, vw2 | Copy-DbaDbViewData -DestinationTable tb3 Example 4: Copies data from tbl1 in tempdb on sql1 to tbl1 in tempdb on sql2 then Copies data from tbl2 in tempdb on... PS C:\\> Get-DbaDbView -SqlInstance sql1 -Database tempdb -View vw1, vw2 | Copy-DbaDbViewData -Destination sql2 Copies data from tbl1 in tempdb on sql1 to tbl1 in tempdb on sql2 then Copies data from tbl2 in tempdb on sql1 to tbl2 in tempdb on sql2 Example 5: Copies all the data in view test_view from sql1 to sql2, using the database dbatools_from, keeping identity... PS C:\\> Copy-DbaDbViewData -SqlInstance sql1 -Destination sql2 -Database dbatools_from -View test_view -KeepIdentity -Truncate Copies all the data in view test_view from sql1 to sql2, using the database dbatools_from, keeping identity columns and truncating the destination Example 6: Copies all the data from view [Schema].[View] in database dbatools_from on sql1 to table [dbo].[Table.Copy]... PS C:\\> $params = @{ >> SqlInstance = 'sql1' >> Destination = 'sql2' >> Database = 'dbatools_from' >> DestinationDatabase = 'dbatools_dest' >> View = '[Schema].[View]' >> DestinationTable = '[dbo].[View.Copy]' >> KeepIdentity = $true >> KeepNulls = $true >> Truncate = $true >> BatchSize = 10000 >> } >> PS C:\\> Copy-DbaDbViewData @params Copies all the data from view [Schema].[View] in database dbatools_from on sql1 to table [dbo].[Table.Copy] in database dbatools_dest on sql2 Keeps identity columns and Nulls, truncates the destination and processes in BatchSize of 10000. Example 7: Copies data returned from the query on server1 into the AdventureWorks2017 on server1 PS C:\\> $params = @{ >> SqlInstance = 'server1' >> Destination = 'server1' >> Database = 'AdventureWorks2017' >> DestinationDatabase = 'AdventureWorks2017' >> View = '[AdventureWorks2017].[Person].[EmailPromotion]' >> BatchSize = 10000 >> Query = \"SELECT * FROM [OtherDb].[Person].[Person] where EmailPromotion = 1\" >> } >> PS C:\\> Copy-DbaDbViewData @params Copies data returned from the query on server1 into the AdventureWorks2017 on server1. This 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\". Copy is processed in BatchSize of 10000 rows. See the -Query param documentation for more details. Optional Parameters -SqlInstance Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the source instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Destination Target SQL Server instance where view data will be copied to. Accepts one or more SQL Server instances. Specify this when copying view data to a different server than the source, or when doing cross-instance data transfers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Alternative credentials for authenticating to the destination instance. Required when your current Windows credentials don't have access to the target server. Use this for cross-domain scenarios, SQL authentication, or when the destination requires different security context than the source. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Source database containing the view to copy data from. Required when not using pipeline input. Must exist on the source instance and your account must have read permissions on the specified view. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationDatabase Target database where copied view data will be inserted. Defaults to the same database name as the source. Use this when copying data to a different database name on the destination instance or for cross-database copies within the same server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -View Source view name to copy data from. Accepts 2-part ([schema].[view]) or 3-part ([database].[schema].[view]) names. Use square brackets for names with spaces or special characters. Required to specify which view's data to extract and copy. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Query Custom SQL SELECT query to use as the data source instead of copying the entire view. Supports 3 or 4-part object names. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AutoCreateTable Automatically creates the destination table if it doesn't exist, using the same structure as the source view. Essential for initial data migrations or when materializing view data into new tables where destination tables haven't been created yet. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BatchSize Number of rows to process in each bulk copy batch. Defaults to 50000 rows. Reduce this value for memory-constrained systems or increase it for faster transfers when copying large view result sets with sufficient memory. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 50000 | -NotifyAfter Number of rows to process before displaying progress updates. Defaults to 5000 rows. Set to a lower value for frequent updates on small view datasets or higher for less verbose output on large view copies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 5000 | -DestinationTable Target table name where view data will be inserted. Defaults to the same name as the source view. Use this when copying to a table with a different name or schema, or when materializing view data into a permanent table structure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoTableLock Disables the default table lock (TABLOCK) on the destination table during bulk copy operations. Use this when you need to allow concurrent read access to the destination table, though it may reduce bulk copy performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CheckConstraints Enables constraint checking during bulk copy operations. By default, constraints are ignored for performance. Use this when data integrity validation is more important than copy speed, particularly when copying view data to tables with strict business rules. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FireTriggers Enables INSERT triggers to fire during bulk copy operations. By default, triggers are bypassed for performance. Use this when you need audit trails, logging, or other trigger-based business logic to execute during the view data copy. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepIdentity Preserves the original identity column values from the source view. By default, the destination generates new identity values. Essential when copying view data that includes identity columns and you need to maintain exact ID relationships in the destination table. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepNulls Preserves NULL values from the source view data instead of replacing them with destination column defaults. Use this when you need exact source data reproduction from the view, especially when NULL has specific business meaning versus default values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Truncate Removes all existing data from the destination table before copying new view data. Prompts for confirmation unless -Force is used. Essential for refresh scenarios where you want to replace all destination data with current view data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BulkCopyTimeOut Maximum time in seconds to wait for bulk copy operations to complete. Defaults to 5000 seconds (83 minutes). Increase this value when copying very large view result sets that may take longer than the default timeout period. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 5000 | -ScriptingOptionsObject A scripting options object created by New-DbaScriptingOption that controls how the destination table is scripted when -AutoCreateTable is used. Use this to control which table properties are included in the CREATE TABLE script, such as indexes, constraints, triggers, and extended properties. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts view objects from Get-DbaDbView for pipeline operations. Use this to copy data from multiple views by piping them from Get-DbaDbView, allowing batch processing of view data copies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per successful bulk copy operation, with details about the source and destination of the copied data. Properties: SourceInstance: The name of the source SQL Server instance where the view data was read from SourceDatabase: The name of the source database containing the view SourceDatabaseID: The unique identifier of the source database SourceSchema: The schema name of the source view (e.g., dbo) SourceTable: The name of the source view being copied DestinationInstance: The name of the destination SQL Server instance where data was written DestinationDatabase: The name of the destination database where data was inserted DestinationDatabaseID: The unique identifier of the destination database DestinationSchema: The schema name of the destination table (e.g., dbo) DestinationTable: The name of the destination table receiving the copied data RowsCopied: The total number of rows successfully copied from the view to the destination table Elapsed: The total elapsed time for the bulk copy operation (displayed as a formatted timespan, e.g., 00:01:23.456) &nbsp;"
  },
  {
    "name": "Copy-DbaEndpoint",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "endpoint"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaEndpoint",
    "popularityRank": 330,
    "synopsis": "Copies SQL Server endpoints from source instance to destination instances for migration scenarios.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaEndpoint View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies SQL Server endpoints from source instance to destination instances for migration scenarios. 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. Existing 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. Syntax Copy-DbaEndpoint [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Endpoint] ] [[-ExcludeEndpoint] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all server endpoints from sqlserver2014a to sqlcluster, using Windows credentials PS C:\\> Copy-DbaEndpoint -Source sqlserver2014a -Destination sqlcluster Copies all server endpoints from sqlserver2014a to sqlcluster, using Windows credentials. If endpoints with the same name exist on sqlcluster, they will be skipped. Example 2: Copies only the tg_noDbDrop endpoint from sqlserver2014a to sqlcluster using SQL credentials for... PS C:\\> Copy-DbaEndpoint -Source sqlserver2014a -SourceSqlCredential $cred -Destination sqlcluster -Endpoint tg_noDbDrop -Force Copies 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 sqlcluster, it will be dropped and recreated because -Force was used. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaEndpoint -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -Source Specifies the source SQL Server instance containing endpoints to copy. Must have sysadmin access to enumerate and script endpoint definitions. Use this to identify the server containing Service Broker, Database Mirroring, or Availability Group endpoints needed on other instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Specifies one or more destination SQL Server instances where endpoints will be created. Must have sysadmin access to create endpoint objects. Use this to deploy endpoints across multiple servers in Always On configurations or Service Broker scenarios requiring identical endpoint definitions. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Specifies alternative credentials for connecting to the source SQL Server instance. Required when Windows Authentication is not available or sufficient. Use this when the source server requires SQL authentication or when running under a service account that lacks access to the source instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Specifies alternative credentials for connecting to destination SQL Server instances. Applied to all destination servers when Windows Authentication is insufficient. Use this when destination servers require SQL authentication or when deploying endpoints across environments with different security contexts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Endpoint Specifies which endpoints to copy from the source instance. Accepts endpoint names and supports wildcards for pattern matching. Use this when you need to migrate specific endpoints like Database Mirroring or Service Broker endpoints rather than copying all user-defined endpoints. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeEndpoint Specifies which endpoints to skip during the copy operation. Takes precedence over the Endpoint parameter when both are specified. Use this to exclude problematic or environment-specific endpoints while copying most other endpoints from the source instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Drops and recreates existing endpoints on destination instances when name conflicts occur. By default, existing endpoints are skipped to prevent disruption. Use this when updating endpoint configurations or when you need to overwrite outdated endpoint definitions on destination servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per endpoint copy operation with migration status information. Default display properties (via Select-DefaultView): DateTime: The date and time when the endpoint operation was performed SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The name of the endpoint being copied Type: The type of object (always \"Endpoint\" for this command) Status: The result of the operation (Successful, Skipped, or Failed) Notes: Additional details about the operation result (e.g., reason for skipping or error message) All properties are accessible using Select-Object * for advanced scripting scenarios. &nbsp;"
  },
  {
    "name": "Copy-DbaExtendedStoredProcedure",
    "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's 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.",
    "category": "Migration",
    "tags": [
      "migration",
      "extendedstoredprocedure",
      "xp"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaExtendedStoredProcedure",
    "popularityRank": 0,
    "synopsis": "Copies custom Extended Stored Procedures (XPs) and their associated DLL files between SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaExtendedStoredProcedure View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies custom Extended Stored Procedures (XPs) and their associated DLL files between SQL Server instances 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. This 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's Binn directory. Due to OS and .NET version differences, DLLs may require recompilation when migrating between different Windows versions or SQL Server versions. By 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. WARNING: 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. Syntax Copy-DbaExtendedStoredProcedure [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-ExtendedProcedure] ] [[-ExcludeExtendedProcedure] ] [[-DestinationPath] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all custom Extended Stored Procedures from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaExtendedStoredProcedure -Source sqlserver2014a -Destination sqlcluster Copies 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 associated DLL files. Example 2: Copies only the Extended Stored Procedure xp_custom_proc from sqlserver2014a to sqlcluster using SQL... PS C:\\> Copy-DbaExtendedStoredProcedure -Source sqlserver2014a -SourceSqlCredential $scred -Destination sqlcluster -DestinationSqlCredential $dcred -ExtendedProcedure xp_custom_proc -Force Copies 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 used. Example 3: Copies all custom Extended Stored Procedures found on sqlserver2014a except xp_old_proc to sqlcluster PS C:\\> Copy-DbaExtendedStoredProcedure -Source sqlserver2014a -Destination sqlcluster -ExcludeExtendedProcedure xp_old_proc -Force Copies 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 used. Example 4: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaExtendedStoredProcedure -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Example 5: Copies all custom Extended Stored Procedures and attempts to copy DLL files to C:\\CustomPath on the... PS C:\\> Copy-DbaExtendedStoredProcedure -Source sqlserver2014a -Destination sqlcluster -DestinationPath \"C:\\CustomPath\" Copies all custom Extended Stored Procedures and attempts to copy DLL files to C:\\CustomPath on the destination server instead of the default Binn directory. Required Parameters -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. Use this to specify which server has the Extended Stored Procedures you want to migrate or standardize across your environment. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. Accepts multiple destinations to deploy Extended Stored Procedures across several servers simultaneously for standardization. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Credentials for connecting to the source SQL Server instance when Windows authentication is not available or desired. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instance(s) when Windows authentication is not available or desired. Use this when deploying to servers that require different authentication credentials or when your current context lacks destination access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExtendedProcedure Specifies which Extended Stored Procedures to copy from the source server instead of copying all available custom XPs. Use this when you only need specific procedures migrated, such as copying just certain legacy integrations while leaving others behind. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeExtendedProcedure Specifies which Extended Stored Procedures to skip during the copy operation while processing all others from the source. Use this when most Extended Stored Procedures should be copied but specific ones need to remain server-specific or are problematic. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationPath Specifies the destination path where DLL files should be copied. By default, uses the destination SQL Server's Binn directory. Use this when you need to copy DLLs to a non-standard location or when the destination Binn directory is not accessible. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Overwrites existing Extended Stored Procedures on the destination server instead of skipping them when name conflicts occur. Use this when updating existing procedures with newer versions or when you need to ensure destination procedures match the source exactly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (MigrationObject) Returns one object per Extended Stored Procedure processed. The object contains information about the success or failure of the copy operation. Properties: DateTime: The date and time when the copy operation was processed (DbaDateTime) SourceServer: The name of the source SQL Server instance (string) DestinationServer: The name of the destination SQL Server instance (string) Name: The name of the Extended Stored Procedure (string) Type: Always \"Extended Stored Procedure\" (string) Status: The result of the operation - Successful, Skipped, Failed, or \"Successful (DLL not copied)\" (string) Notes: Additional information about the operation result, such as reason for skip, error message, or DLL copy status (string) Schema: The schema in which the Extended Stored Procedure was created (string) &nbsp;"
  },
  {
    "name": "Copy-DbaInstanceAudit",
    "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.",
    "category": "Migration",
    "tags": [
      "migration"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaInstanceAudit",
    "popularityRank": 181,
    "synopsis": "Copies SQL Server audit objects from source to destination instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaInstanceAudit View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies SQL Server audit objects from source to destination instances 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. Syntax Copy-DbaInstanceAudit [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Audit] ] [[-ExcludeAudit] ] [[-Path] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all server audits from sqlserver2014a to sqlcluster, using Windows credentials PS C:\\> Copy-DbaInstanceAudit -Source sqlserver2014a -Destination sqlcluster Copies all server audits from sqlserver2014a to sqlcluster, using Windows credentials. If audits with the same name exist on sqlcluster, they will be skipped. Example 2: Copies a single audit, the tg_noDbDrop audit from sqlserver2014a to sqlcluster, using SQL credentials for... PS C:\\> Copy-DbaInstanceAudit -Source sqlserver2014a -Destination sqlcluster -Audit tg_noDbDrop -SourceSqlCredential $cred -Force Copies 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 on sqlcluster, it will be dropped and recreated because -Force was used. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaInstanceAudit -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Example 4: Copies audit audit1 from sqlserver-0 to sqlserver-1 PS C:\\> Copy-DbaInstanceAudit -Source sqlserver-0 -Destination sqlserver-1 -Audit audit1 -Path 'C:\\audit1' Copies audit audit1 from sqlserver-0 to sqlserver-1. The file path on sqlserver-1 will be set to 'C:\\audit1'. Required Parameters -Source Source SQL Server instance containing the audit objects to copy. Requires sysadmin access to read audit configurations and their associated file paths. Must be SQL Server 2008 or higher since server audits were introduced in SQL Server 2008. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Destination SQL Server instance where audit objects will be created. Requires sysadmin access to create audits and potentially create audit file directories. Must be SQL Server 2008 or higher since server audits were introduced in SQL Server 2008. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Login credentials for the source SQL Server instance. Use this when the current Windows user doesn't have sysadmin access to read audit objects. Must have sysadmin privileges since audit configurations require elevated permissions to access. Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login credentials for the destination SQL Server instance. Use this when the current Windows user doesn't have sysadmin access to create audit objects. Must have sysadmin privileges since creating audits and directories requires elevated permissions. Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Supports tab completion with audit names from the source server. If not specified, all audits will be copied. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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't be migrated. Supports tab completion with audit names from the source server. Cannot be used with the -Audit parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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't exist on the destination. If not specified, the function attempts to use the source audit's original file path, or falls back to the default data directory if the path doesn't exist. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Drops and recreates audits that already exist on the destination server. Also creates missing audit file directories if they don't exist. Without this switch, existing audits are skipped and missing directories cause the operation to fail. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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. Default display properties (via Select-DefaultView): DateTime: The timestamp when the copy operation was attempted SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The name of the server audit being copied Type: Always \"Server Audit\" indicating the type of object being copied Status: The result status of the copy operation (Successful, Skipped, or Failed) Notes: Additional information about the copy operation (reason for skip, error details, etc.) The object type is set to \"MigrationObject\" for proper display formatting. All properties are always available using Select-Object *. &nbsp;"
  },
  {
    "name": "Copy-DbaInstanceAuditSpecification",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "serveraudit",
      "auditspecification"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaInstanceAuditSpecification",
    "popularityRank": 383,
    "synopsis": "Copies server audit specifications from one SQL Server instance to another for compliance standardization.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaInstanceAuditSpecification View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies server audit specifications from one SQL Server instance to another for compliance standardization. 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. By 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. Syntax Copy-DbaInstanceAuditSpecification [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-AuditSpecification] ] [[-ExcludeAuditSpecification] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all server audits from sqlserver2014a to sqlcluster using Windows credentials to connect PS C:\\> Copy-DbaInstanceAuditSpecification -Source sqlserver2014a -Destination sqlcluster Copies 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. Example 2: Copies a single audit, the tg_noDbDrop audit from sqlserver2014a to sqlcluster using SQL credentials to... PS C:\\> Copy-DbaInstanceAuditSpecification -Source sqlserver2014a -Destination sqlcluster -AuditSpecification tg_noDbDrop -SourceSqlCredential $cred -Force Copies 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 specification with the same name exists on sqlcluster, it will be dropped and recreated because -Force was used. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaInstanceAuditSpecification -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -Source Source SQL Server instance containing the server audit specifications to copy. Requires sysadmin access and SQL Server 2008 or higher. The function will read all existing audit specifications from this instance to migrate to the destination. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Destination SQL Server instance where audit specifications will be created. Requires sysadmin access and SQL Server 2008 or higher. The corresponding server audits must already exist on this instance before audit specifications can be successfully copied. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Credentials for connecting to the source SQL Server instance to read audit specifications. Use when Windows Authentication is not available. Accepts PowerShell credentials (Get-Credential) and supports SQL Server Authentication, Active Directory authentication modes. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instance to create audit specifications. Use when Windows Authentication is not available. Accepts PowerShell credentials (Get-Credential) and supports SQL Server Authentication, Active Directory authentication modes. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AuditSpecification Specifies which server audit specifications to copy by name. Accepts multiple specification names as an array. Use this when you need to migrate specific audit specifications rather than all specifications from the source instance. If not specified, all audit specifications from the source will be processed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeAuditSpecification Specifies which server audit specifications to skip during the copy operation. Accepts multiple specification names as an array. Use this to copy all audit specifications except those you want to exclude, such as environment-specific or test specifications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Drops and recreates existing audit specifications on the destination instance instead of skipping them. Use this when you need to overwrite existing audit specifications with updated configurations from the source. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs MigrationObject Returns one object per audit specification processed, with the results of the copy operation for each specification. Properties: DateTime: Timestamp when the copy operation was executed (DbaDateTime) SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Name: Name of the audit specification that was copied or processed Type: Always returns \"Server Audit Specification\" Status: Result of the operation - \"Successful\", \"Skipped\", or \"Failed\" Notes: Additional details about the operation result (e.g., why it was skipped or failure reason) &nbsp;"
  },
  {
    "name": "Copy-DbaInstanceTrigger",
    "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.",
    "category": "Migration",
    "tags": [
      "migration"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaInstanceTrigger",
    "popularityRank": 325,
    "synopsis": "Copies server-level triggers between SQL Server instances for migration or standardization",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaInstanceTrigger View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies server-level triggers between SQL Server instances for migration or standardization 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. Server 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. By 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. Syntax Copy-DbaInstanceTrigger [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-ServerTrigger] ] [[-ExcludeServerTrigger] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all server triggers from sqlserver2014a to sqlcluster, using Windows credentials PS C:\\> Copy-DbaInstanceTrigger -Source sqlserver2014a -Destination sqlcluster Copies all server triggers from sqlserver2014a to sqlcluster, using Windows credentials. If triggers with the same name exist on sqlcluster, they will be skipped. Example 2: Copies a single trigger, the tg_noDbDrop trigger from sqlserver2014a to sqlcluster, using SQL credentials for... PS C:\\> Copy-DbaInstanceTrigger -Source sqlserver2014a -Destination sqlcluster -ServerTrigger tg_noDbDrop -SourceSqlCredential $cred -Force Copies 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 exists on sqlcluster, it will be dropped and recreated because -Force was used. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaInstanceTrigger -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -Source Source SQL Server instance containing the server triggers to copy. Must be SQL Server 2005 or later. Requires sysadmin privileges to access server-level triggers and their definitions. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Destination SQL Server instance(s) where server triggers will be created. Must be SQL Server 2005 or later. Requires sysadmin privileges to create server-level triggers and cannot be a lower version than the source. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Credentials for connecting to the source SQL Server instance when Windows Authentication is not available. Use this when copying triggers from instances in different domains or when using SQL Server authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instance(s) when Windows Authentication is not available. Use this when copying triggers to instances in different domains or when using SQL Server authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ServerTrigger Specific server trigger name(s) to copy from the source instance. Tab completion shows available triggers. Use this when you need to copy only specific triggers instead of all server triggers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeServerTrigger Server trigger name(s) to skip during the copy operation. Tab completion shows available triggers. Use this when copying most triggers but need to exclude specific ones due to environment differences. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Drops and recreates server triggers that already exist on the destination instance. Without this switch, existing triggers are skipped to prevent accidental overwrites. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (MigrationObject) Returns one object per server trigger processed, showing the status of each trigger copy operation. Properties: SourceServer: The name of the source SQL Server instance where the trigger was copied from DestinationServer: The name of the destination SQL Server instance where the trigger was copied to Name: The name of the server trigger Type: Always \"Server Trigger\" Status: The result of the copy operation (Successful, Skipped, or Failed) Notes: Additional details about the operation (e.g., \"Already exists on destination\", error message if failed) DateTime: The date and time when the copy operation was processed &nbsp;"
  },
  {
    "name": "Copy-DbaLinkedServer",
    "description": "Migrates SQL Server linked servers including all authentication credentials and connection settings from a source instance to one or more destination instances. The function preserves usernames and passwords by using password decryption techniques, eliminating the need to manually recreate linked server configurations and re-enter sensitive credentials.\n\nThis is particularly useful during server migrations, disaster recovery scenarios, or when consolidating environments where maintaining external data connections is critical. The function handles various provider types and can optionally upgrade older SQL Client providers to current versions during migration.\n\nWhen upgrading from older versions to SQL Server 2025+, MSOLEDBSQL is changed to MSOLEDBSQL19 and provider string for encrypt and trustservercertificate settings is added if not already included to ensure compatibility with the breaking changes in the new driver.\n\nCredit: Password decryption techniques provided by Antti Rantasaari (NetSPI, 2014) - https://blog.netspi.com/decrypting-mssql-database-link-server-passwords/",
    "category": "Migration",
    "tags": [
      "wsman",
      "migration",
      "linkedserver"
    ],
    "verb": "Copy",
    "popular": true,
    "url": "/Copy-DbaLinkedServer",
    "popularityRank": 23,
    "synopsis": "Migrates linked servers and their authentication credentials from one SQL Server instance to another",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Copy-DbaLinkedServer View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Migrates linked servers and their authentication credentials from one SQL Server instance to another 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. This 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. When upgrading from older versions to SQL Server 2025+, MSOLEDBSQL is changed to MSOLEDBSQL19 and provider string for encrypt and trustservercertificate settings is added if not already included to ensure compatibility with the breaking changes in the new driver. Credit: Password decryption techniques provided by Antti Rantasaari (NetSPI, 2014) - https://blog.netspi.com/decrypting-mssql-database-link-server-passwords/ Syntax Copy-DbaLinkedServer [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Credential] ] [[-LinkedServer] ] [[-ExcludeLinkedServer] ] [-UpgradeSqlClient] [-ExcludePassword] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all SQL Server Linked Servers on sqlserver2014a to sqlcluster PS C:\\> Copy-DbaLinkedServer -Source sqlserver2014a -Destination sqlcluster Copies all SQL Server Linked Servers on sqlserver2014a to sqlcluster. If Linked Server exists on destination, it will be skipped. Example 2: Copies over two SQL Server Linked Servers (SQL2K and SQL2K2) from sqlserver to sqlcluster PS C:\\> Copy-DbaLinkedServer -Source sqlserver2014a -Destination sqlcluster -LinkedServer SQL2K5,SQL2k -Force Copies 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. Required Parameters -Source Source SQL Server (2005 and above). You must have sysadmin access to both SQL Server and Windows. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Destination SQL Server (2005 and above). You must have sysadmin access to both SQL Server and Windows. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential) Only used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LinkedServer Specifies which linked servers to copy from the source instance. Accepts an array of linked server names. Use this when you only need to migrate specific linked servers rather than all of them. If omitted, all linked servers from the source will be copied to the destination. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeLinkedServer Specifies linked servers to skip during the copy operation. Accepts an array of linked server names. Use this when you want to copy most linked servers but exclude problematic ones or those that shouldn't be migrated. This parameter is ignored if LinkedServer is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -UpgradeSqlClient Updates older SQL Server Native Client providers (SQLNCLI) to the newest version available on the destination server. Use this when migrating from older SQL Server versions to ensure linked servers use current client libraries. The function automatically detects and upgrades to the highest numbered SQLNCLI provider found on the destination. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludePassword Copies linked server definitions without migrating stored passwords or sensitive authentication data. Use this in security-conscious environments where password decryption is restricted or when passwords should be manually reset after migration. Linked servers will be created but authentication credentials will need to be reconfigured. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Drops and recreates linked servers that already exist on the destination instance. Use this when you need to overwrite existing linked server configurations with updated settings from the source. Without this parameter, existing linked servers on the destination are skipped to prevent accidental overwrites. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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. Default display properties (via Select-DefaultView): DateTime: Timestamp when the linked server was processed (DbaDateTime object) SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Name: Name of the linked server being migrated Type: Initially \"Linked Server\", then set to the remote login identity being configured Status: Status of the operation (Successful, Skipped, or Failed) Notes: Provider name, or reason for skip/failure (e.g., \"Missing provider\", \"Already exists on destination\", or error message) &nbsp;"
  },
  {
    "name": "Copy-DbaLogin",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "login"
    ],
    "verb": "Copy",
    "popular": true,
    "url": "/Copy-DbaLogin",
    "popularityRank": 1,
    "synopsis": "Copies SQL Server logins between instances with passwords, permissions, and role memberships intact",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaLogin View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies SQL Server logins between instances with passwords, permissions, and role memberships intact 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. Handles 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. Version 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. Syntax Copy-DbaLogin [-SourceSqlCredential ] [-DestinationSqlCredential ] [-Login ] [-ExcludeLogin ] [-ExcludeSystemLogins] [-LoginRenameHashtable ] [-KillActiveConnection] [-NewSid] [-Force] [-ObjectLevel] [-ExcludePermissionSync] [-ExcludeDatabaseMapping] [-EnableException] [-WhatIf] [-Confirm] [ ] Copy-DbaLogin -Source [-SourceSqlCredential ] -Destination [-DestinationSqlCredential ] [-Login ] [-ExcludeLogin ] [-ExcludeSystemLogins] [-SyncSaName] [-LoginRenameHashtable ] [-KillActiveConnection] [-NewSid] [-Force] [-ObjectLevel] [-ExcludePermissionSync] [-ExcludeDatabaseMapping] [-EnableException] [-WhatIf] [-Confirm] [ ] Copy-DbaLogin -Source [-SourceSqlCredential ] [-DestinationSqlCredential ] [-Login ] [-ExcludeLogin ] [-ExcludeSystemLogins] -OutFile [-LoginRenameHashtable ] [-KillActiveConnection] [-NewSid] [-Force] [-ObjectLevel] [-ExcludePermissionSync] [-ExcludeDatabaseMapping] [-EnableException] [-WhatIf] [-Confirm] [ ] Copy-DbaLogin [-SourceSqlCredential ] -Destination [-DestinationSqlCredential ] [-Login ] [-ExcludeLogin ] [-ExcludeSystemLogins] [-InputObject ] [-LoginRenameHashtable ] [-KillActiveConnection] [-NewSid] [-Force] [-ObjectLevel] [-ExcludePermissionSync] [-ExcludeDatabaseMapping] [-EnableException] [-WhatIf] [-Confirm] [ ] Copy-DbaLogin [-SourceSqlCredential ] [-DestinationSqlCredential ] [-Login ] [-ExcludeLogin ] [-ExcludeSystemLogins] [-SyncSaName] [-LoginRenameHashtable ] [-KillActiveConnection] [-NewSid] [-Force] [-ObjectLevel] [-ExcludePermissionSync] [-ExcludeDatabaseMapping] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all logins from Source Destination PS C:\\> Copy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Force Copies all logins from Source Destination. If a SQL Login on Source exists on the Destination, the Login on Destination will be dropped and recreated. If active connections are found for a login, the copy of that Login will fail as it cannot be dropped. Example 2: Copies all logins from Source Destination PS C:\\> Copy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Force -KillActiveConnection Copies all logins from Source Destination. If a SQL Login on Source exists on the Destination, the Login on Destination will be dropped and recreated. If any active connections are found they will be killed. Example 3: Copies all Logins from Source to Destination except for realcajun using SQL Authentication to connect to both... PS C:\\> Copy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -ExcludeLogin realcajun -SourceSqlCredential $scred -DestinationSqlCredential $dcred Copies all Logins from Source to Destination except for realcajun using SQL Authentication to connect to both instances. If a Login already exists on the destination, it will not be migrated. Example 4: Copies ONLY Logins netnerds and realcajun PS C:\\> Copy-DbaLogin -Source sqlserver2014a -Destination sqlcluster -Login realcajun, netnerds -force Copies ONLY Logins netnerds and realcajun. If Login realcajun or netnerds exists on Destination, the existing Login(s) will be dropped and recreated. Example 5: Copies PreviousUser as newlogin PS C:\\> Copy-DbaLogin -LoginRenameHashtable @{ \"PreviousUser\" = \"newlogin\" } -Source $Sql01 -Destination Localhost -SourceSqlCredential $sqlcred -Login PreviousUser Example 6: Clones OldLogin as NewLogin onto the same server, generating a new SID for the login PS C:\\> Copy-DbaLogin -LoginRenameHashtable @{ OldLogin = \"NewLogin\" } -Source Sql01 -Destination Sql01 -Login ORG\\OldLogin -ObjectLevel -NewSid Clones OldLogin as NewLogin onto the same server, generating a new SID for the login. Also clones object-level permissions. Example 7: Displays all available logins on sql2016 in a grid view, then copies all selected logins to sql2017 PS C:\\> Get-DbaLogin -SqlInstance sql2016 | Out-GridView -Passthru | Copy-DbaLogin -Destination sql2017 Example 8: Copies the three specified logins to &#39;localhost&#39; and renames them according to the LoginRenameHashTable PS C:\\> $loginSplat = @{ >> Source = $Sql01 >> Destination = \"Localhost\" >> SourceSqlCredential = $sqlcred >> Login = 'ReadUserP', 'ReadWriteUserP', 'AdminP' >> LoginRenameHashtable = @{ >> \"ReadUserP\" = \"ReadUserT\" >> \"ReadWriteUserP\" = \"ReadWriteUserT\" >> \"AdminP\" = \"AdminT\" >> } >> } PS C:\\> Copy-DbaLogin @loginSplat Required Parameters -Source Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -OutFile Exports login creation scripts to a T-SQL file instead of copying directly to a destination instance. Use this to generate scripts for manual review, version control, or deployment through automated processes rather than performing immediate migration. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Specifies which SQL Server logins to copy from the source instance. Accepts wildcards and arrays of login names. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeLogin Specifies which logins to skip during the copy operation. Accepts wildcards and arrays of login names. Useful for excluding test accounts, service accounts that should remain environment-specific, or logins that already exist on the destination with different configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemLogins Excludes NT SERVICE accounts and other system-generated logins from the copy operation. Use this during server migrations when you don't want to copy OS-level service accounts that may differ between environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SyncSaName Renames the destination sa account to match the source sa account name if they differ. Use this during migrations when your organization has renamed the sa account for security purposes and you need consistent naming across instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts login objects from Get-DbaLogin or other dbatools commands through the pipeline. Use this when you want to filter or manipulate login objects before copying, such as selecting logins through Out-GridView or combining multiple sources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -LoginRenameHashtable Renames logins during copy using a hashtable with old names as keys and new names as values. Use this for login consolidation, environment-specific naming conventions, or when resolving naming conflicts during migrations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -KillActiveConnection Terminates active sessions for logins being replaced when using -Force, allowing the drop and recreate operation to proceed. Use this during maintenance windows when you need to force login replacement despite active connections, but ensure users are notified of potential disruption. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NewSid Forces generation of new Security Identifiers (SIDs) for copied logins instead of preserving original SIDs. Use this when copying logins to the same instance (login cloning) or when SID conflicts exist on the destination server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Drops and recreates existing logins on the destination server, transferring ownership of databases and SQL Agent jobs to 'sa' first. Use this when you need to update login passwords or properties that can't be modified in place, but ensure job ownership changes are acceptable. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ObjectLevel Copies granular object-level permissions (table, view, procedure permissions) in addition to database and server roles. Use this for complete security replication when applications rely on specific object permissions rather than just role memberships. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludePermissionSync Skips copying server roles, database permissions, and security mappings for the login accounts. Use this when you only need the login accounts created but plan to configure permissions separately, or when copying logins for testing purposes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeDatabaseMapping Skips copying database-level permissions and role memberships, syncing only server-level roles and securables. Use this when you want to sync server permissions (sysadmin membership, server securables, etc.) without iterating through all databases, which significantly improves performance on instances with many databases. When used with -OutFile, generated scripts also exclude database user mappings and permissions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per login migration attempt. Each object represents the result of copying a single login to a destination instance. Default display properties (via Select-DefaultView with TypeName MigrationObject): DateTime: Timestamp when the migration operation occurred (DbaDateTime) SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Name: Login name that was copied (or renamed login name if -LoginRenameHashtable was used) Type: Login type (e.g., \"Login - SqlLogin\", \"Login - WindowsUser\", \"Login - WindowsGroup\") Status: Result of the migration attempt (Successful, Skipped, or Failed) Notes: Additional details about the operation or reason for skipping/failure All properties available on the returned object: SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Type: Login type classification Name: Destination login name (post-rename if applicable) DestinationLogin: Destination login name (same as Name) SourceLogin: Original login name from source server Status: Operation result Notes: Operation details or error message DateTime: Operation timestamp System.String (when -OutFile is specified) When exporting login scripts to a file using -OutFile, the function returns the file path where the T-SQL scripts were written. &nbsp;"
  },
  {
    "name": "Copy-DbaPolicyManagement",
    "description": "Transfers your entire Policy-Based Management framework from one SQL Server instance to another, including custom policies, conditions, object sets, and categories. This streamlines environment standardization and disaster recovery scenarios where you need identical compliance policies across multiple servers.\n\nBy default, all non-system policies, conditions, and object sets are copied. Object sets are migrated after conditions and before policies to ensure policy dependencies are satisfied. Existing objects on the destination are skipped unless -Force is used to overwrite them. You can selectively copy specific policies or conditions using the include/exclude parameters, which provide auto-completion from the source server.",
    "category": "Migration",
    "tags": [
      "migration"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaPolicyManagement",
    "popularityRank": 447,
    "synopsis": "Copies Policy-Based Management policies, conditions, and categories between SQL Server instances",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Copy-DbaPolicyManagement View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies Policy-Based Management policies, conditions, and categories between SQL Server instances Description Transfers your entire Policy-Based Management framework from one SQL Server instance to another, including custom policies, conditions, object sets, and categories. This streamlines environment standardization and disaster recovery scenarios where you need identical compliance policies across multiple servers. By default, all non-system policies, conditions, and object sets are copied. Object sets are migrated after conditions and before policies to ensure policy dependencies are satisfied. Existing objects on the destination are skipped unless -Force is used to overwrite them. You can selectively copy specific policies or conditions using the include/exclude parameters, which provide auto-completion from the source server. Syntax Copy-DbaPolicyManagement [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Policy] ] [[-ExcludePolicy] ] [[-Condition] ] [[-ExcludeCondition] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all policies and conditions from sqlserver2014a to sqlcluster, using Windows credentials PS C:\\> Copy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster Example 2: Copies all policies and conditions from sqlserver2014a to sqlcluster, using SQL credentials for... PS C:\\> Copy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred Copies all policies and conditions from sqlserver2014a to sqlcluster, using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. Example 3: Shows what would happen if the command were executed PS C:\\> Copy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -WhatIf Example 4: Copies only one policy, &#39;xp_cmdshell must be disabled&#39; from sqlserver2014a to sqlcluster PS C:\\> Copy-DbaPolicyManagement -Source sqlserver2014a -Destination sqlcluster -Policy 'xp_cmdshell must be disabled' Copies only one policy, 'xp_cmdshell must be disabled' from sqlserver2014a to sqlcluster. No conditions are migrated. Required Parameters -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. Use this to identify which server contains your existing policies, conditions, and categories that need to be replicated to other instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. Use this when standardizing compliance policies across multiple environments like development, staging, and production servers. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Alternative credentials for connecting to the source SQL Server instance. Use when the current Windows credentials don't have access to the source. Commonly needed when copying from production servers that require SQL Authentication or different Active Directory accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Alternative credentials for connecting to the destination SQL Server instances. Use when the current Windows credentials don't have access to the destination servers. Particularly useful when copying to servers in different domains or when using SQL Authentication on destination instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need to copy specific compliance policies rather than the entire Policy-Based Management framework, such as copying only security-related policies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludePolicy Specifies which policies to skip during the copy operation, with auto-completion from the source server. All other policies will be copied. Use this to exclude environment-specific policies or policies that shouldn't be replicated, such as development-only or deprecated policies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need to copy reusable conditions that can be referenced by multiple policies, such as server configuration or database naming conditions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeCondition Specifies which conditions to skip during the copy operation, with auto-completion from the source server. All other conditions will be copied. Use this to exclude conditions that are environment-specific or no longer needed, while copying the rest of your condition library. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Overwrites existing policies and conditions on the destination server by dropping and recreating them. Without this switch, existing objects are skipped. Use this when updating existing Policy-Based Management objects or when you need to ensure destination objects match the source exactly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per policy category, condition, object set, and policy successfully copied or skipped. All objects use a common schema with the following properties: Default display properties (via Select-DefaultView): DateTime: Timestamp of when the copy operation was attempted (DbaDateTime) SourceServer: The source SQL Server instance name where the object was copied from DestinationServer: The destination SQL Server instance name where the object was copied to Name: The name of the policy category, condition, object set, or policy that was processed Type: The type of object being copied - one of \"Policy Category\", \"Policy Condition\", \"Policy ObjectSet\", or \"Policy\" Status: The result of the operation - \"Successful\", \"Skipped\", or \"Failed\" Notes: Additional information about the operation result, such as \"Already exists on destination\" or error details &nbsp;"
  },
  {
    "name": "Copy-DbaRegServer",
    "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.",
    "category": "Migration",
    "tags": [
      "migration"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaRegServer",
    "popularityRank": 267,
    "synopsis": "Copies Central Management Server groups and registered server instances between SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaRegServer View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies Central Management Server groups and registered server instances between SQL Server instances. 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. Syntax Copy-DbaRegServer [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Group] ] [-SwitchServerName] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: All groups, subgroups, and server instances are copied from sqlserver2014a CMS to sqlcluster CMS PS C:\\> Copy-DbaRegServer -Source sqlserver2014a -Destination sqlcluster Example 2: Top-level groups Group1 and Group3 along with their subgroups and server instances are copied from sqlserver... PS C:\\> Copy-DbaRegServer -Source sqlserver2014a -Destination sqlcluster -Group Group1,Group3 Top-level groups Group1 and Group3 along with their subgroups and server instances are copied from sqlserver to sqlcluster. Example 3: $DestinationSqlCredential Top-level groups Group1 and Group3 along with their subgroups and server instances... PS C:\\> Copy-DbaRegServer -Source sqlserver2014a -Destination sqlcluster -Group Group1,Group3 -SwitchServerName -SourceSqlCredential $SourceSqlCredential -DestinationSqlCredential $DestinationSqlCredential Top-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 migrating instance is \"sqlcluster\", it will be switched to \"sqlserver\". If SwitchServerName is not specified, \"sqlcluster\" will be skipped. Required Parameters -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. This is where your existing CMS groups and registered servers are currently stored. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. This instance will become the new Central Management Server containing the migrated server registrations. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Credentials for connecting to the source SQL Server instance when Windows Authentication is not available. Accepts PowerShell credentials (Get-Credential). Use this when the source server requires SQL Authentication or different Windows credentials than your current session. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instance when Windows Authentication is not available. Accepts PowerShell credentials (Get-Credential). Use this when the destination server requires SQL Authentication or different Windows credentials than your current session. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Group Specifies which top-level CMS groups to copy from the source server. Accepts one or more group names as an array. When omitted, all groups and their registered servers are copied. Use this to selectively migrate specific environments like 'Production' or 'Development' groups. | Property | Value | | --- | --- | | Alias | CMSGroup | | Required | False | | Pipeline | false | | Default Value | | -SwitchServerName Replaces source server name references with the destination server name during migration. Use 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 server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Drops and recreates existing groups and registered servers at the destination instead of skipping them. Use this to overwrite conflicting CMS configurations when consolidating multiple Central Management Servers or updating existing registrations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per migration action (group creation, instance addition, etc.). The command returns multiple objects representing the status of different CMS components being migrated. Properties: DateTime: The timestamp when the migration action occurred (DbaDateTime object) SourceServer: Name of the source SQL Server instance from which items are being copied DestinationServer: Name of the destination SQL Server instance to which items are being copied Name: The name of the CMS group or registered server instance that was migrated Type: The type of object migrated - one of \"CMS Destination Group\", \"CMS Group\", or \"CMS Instance\" Status: Result of the migration action (\"Successful\", \"Skipped\", or \"Failed\") Notes: Additional information about the migration result, typically explains why an action was skipped or the error message if failed &nbsp;"
  },
  {
    "name": "Copy-DbaResourceGovernor",
    "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've 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.",
    "category": "Migration",
    "tags": [
      "migration",
      "resourcegovernor"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaResourceGovernor",
    "popularityRank": 461,
    "synopsis": "Copies SQL Server Resource Governor configuration including pools, workload groups, and classifier functions between instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaResourceGovernor View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies SQL Server Resource Governor configuration including pools, workload groups, and classifier functions between instances 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. The 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've configured to automatically assign incoming requests to appropriate resource pools. If 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. Note 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. Syntax Copy-DbaResourceGovernor [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-ResourcePool] ] [[-ExcludeResourcePool] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all all non-system resource pools from sqlserver2014a to sqlcluster using Windows credentials to... PS C:\\> Copy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster Copies all all non-system resource pools from sqlserver2014a to sqlcluster using Windows credentials to connect to the SQL Server instances.. Example 2: Copies all all non-system resource pools from sqlserver2014a to sqlcluster using SQL credentials to connect... PS C:\\> Copy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred Copies all all non-system resource pools from sqlserver2014a to sqlcluster using SQL credentials to connect to sqlserver2014a and Windows credentials to connect to sqlcluster. Example 3: Shows what would happen if the command were executed PS C:\\> Copy-DbaResourceGovernor -Source sqlserver2014a -Destination sqlcluster -WhatIf Required Parameters -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. Use this to identify which server contains the Resource Governor setup you want to migrate to other instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. Use this to define which servers should receive the migrated Resource Governor pools, workload groups, and classifier functions. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Provides alternative credentials for connecting to the source SQL Server instance. Accepts PowerShell credential objects from Get-Credential. Use this when your current Windows credentials don't have access to the source server or when you need to use SQL Server authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Provides alternative credentials for connecting to the destination SQL Server instance(s). Accepts PowerShell credential objects from Get-Credential. Use this when your current Windows credentials don't have access to the destination servers or when you need to use SQL Server authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ResourcePool Specifies which resource pools to copy by name. Supports tab completion with pools from the source server and accepts multiple pool names. Use this when you only want to migrate specific resource pools rather than the entire Resource Governor configuration. Excludes system pools (internal, default) automatically. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeResourcePool Specifies which resource pools to skip during the copy operation. Supports tab completion and accepts multiple pool names. Use this when you want to migrate most of your Resource Governor configuration but exclude certain pools that shouldn't be copied to the destination. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Drops and recreates existing resource pools, workload groups, and classifier functions on the destination server. Use this when you need to overwrite existing Resource Governor objects that would otherwise be skipped due to name conflicts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (MigrationObject) Returns one object per item migrated (Resource Governor settings, pools, workload groups, and classifier functions). Each object represents the migration status of a single component. Properties: DateTime: Timestamp when the object was created (DbaDateTime) SourceServer: The name of the source SQL Server instance (string) DestinationServer: The name of the destination SQL Server instance (string) Name: The name of the object being migrated (string) - examples: \"Classifier Function\", \"PoolName\", \"WorkgroupName\", \"Reconfigure Resource Governor\" Type: The type of object being migrated (string) - one of: \"Resource Governor Settings\", \"Resource Governor Pool\", \"Resource Governor Pool Workgroup\", \"Reconfigure Resource Governor\" Status: The migration status (string) - one of: \"Successful\", \"Skipped\", \"Failed\", or $null 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 All properties are displayed by default through Select-DefaultView. &nbsp;"
  },
  {
    "name": "Copy-DbaServerRole",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "serverrole",
      "security"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaServerRole",
    "popularityRank": 0,
    "synopsis": "Migrates custom server roles and their permissions between SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaServerRole View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Migrates custom server roles and their permissions between SQL Server instances 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. Only 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. Server 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. By 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. Syntax Copy-DbaServerRole [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-ServerRole] ] [[-ExcludeServerRole] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all custom server roles from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaServerRole -Source sqlserver2014a -Destination sqlcluster Copies all custom server roles from sqlserver2014a to sqlcluster using Windows credentials. If roles with the same name exist on sqlcluster, they will be skipped. Example 2: Copies only the custom server role named &quot;CustomRole1&quot; from sqlserver2014a to sqlcluster using SQL credentials PS C:\\> Copy-DbaServerRole -Source sqlserver2014a -SourceSqlCredential $scred -Destination sqlcluster -DestinationSqlCredential $dcred -ServerRole \"CustomRole1\" -Force Copies 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 used. Example 3: Copies all custom server roles found on sqlserver2014a except &quot;TestRole&quot; to sqlcluster PS C:\\> Copy-DbaServerRole -Source sqlserver2014a -Destination sqlcluster -ExcludeServerRole \"TestRole\" -Force Copies 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. Example 4: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaServerRole -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -Source Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Destination SQL Server. You must have sysadmin access and the server must be SQL Server 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ServerRole Specifies which server roles to migrate from the source server. Only the specified roles will be copied to the destination. Use this when you need to migrate specific custom roles rather than all of them, such as when standardizing only certain security roles across environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeServerRole Specifies which server roles to skip during migration. All custom server roles except the excluded ones will be copied. Use this when you want to migrate most roles but exclude problematic ones, or when certain roles are environment-specific and shouldn't be copied. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Drops and recreates existing custom server roles on the destination server, reapplying all permissions and memberships from the source. Use this when you need to update server role permissions that have changed on the source, or when synchronizing role definitions across environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (MigrationObject) Returns one object per server role processed. The object contains the result of attempting to copy each role from the source to the destination server. Properties: DateTime: Timestamp when the role copy operation was executed (DbaDateTime) SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Name: Name of the server role being copied Type: Always \"Server Role\" Status: Result of the copy operation (Successful, Skipped, or Failed) Notes: Additional details about the operation or error message if the status is Failed &nbsp;"
  },
  {
    "name": "Copy-DbaSpConfigure",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "configure",
      "spconfigure"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaSpConfigure",
    "popularityRank": 97,
    "synopsis": "Copies SQL Server configuration settings (sp_configure values) from source to destination instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaSpConfigure View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies SQL Server configuration settings (sp_configure values) from source to destination instances. 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. Syntax Copy-DbaSpConfigure [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-ConfigName] ] [[-ExcludeConfigName] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all sp_configure settings from sqlserver2014a to sqlcluster PS C:\\> Copy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster Example 2: Copies the values for IsSqlClrEnabled and DefaultBackupCompression from sqlserver2014a to sqlcluster using... PS C:\\> Copy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -ConfigName DefaultBackupCompression, IsSqlClrEnabled -SourceSqlCredential $cred Copies the values for IsSqlClrEnabled and DefaultBackupCompression from sqlserver2014a to sqlcluster using SQL credentials to authenticate to sqlserver2014a and Windows credentials to authenticate to sqlcluster. Example 3: Copies all configs except for IsSqlClrEnabled and DefaultBackupCompression, from sqlserver2014a to sqlcluster PS C:\\> Copy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -ExcludeConfigName DefaultBackupCompression, IsSqlClrEnabled Example 4: Shows what would happen if the command were executed PS C:\\> Copy-DbaSpConfigure -Source sqlserver2014a -Destination sqlcluster -WhatIf Required Parameters -Source The source SQL Server instance from which sp_configure settings will be copied. Must have sysadmin access to read configuration values. Use this as your template server when standardizing configurations across multiple instances or when setting up new servers to match production standards. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination One or more destination SQL Server instances where sp_configure settings will be applied. Must have sysadmin access to modify configuration values. Accepts multiple instances for bulk configuration updates across your environment. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Credentials for connecting to the source SQL Server instance. Accepts PowerShell credentials (Get-Credential). Use this when the source server requires different authentication than your current Windows session, such as SQL Server authentication or domain service accounts. Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instances. Accepts PowerShell credentials (Get-Credential). Use this when destination servers require different authentication than your current Windows session, such as SQL Server authentication or domain service accounts. Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ConfigName Specifies which sp_configure settings to copy from source to destination. Accepts one or more configuration names such as 'max server memory (MB)' or 'backup compression default'. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeConfigName Specifies which sp_configure settings to skip during the copy operation. Accepts one or more configuration names to exclude from processing. Use this when copying most settings but need to preserve specific destination values, such as excluding 'max server memory (MB)' when servers have different hardware specifications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per sp_configure setting processed, regardless of whether the setting was updated, skipped, or failed. Properties: DateTime: Timestamp when the operation was performed (DbaDateTime object) SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Name: The name of the sp_configure setting that was copied Type: Always \"Configuration Value\" Status: The result of the operation - either \"Skipped\", \"Successful\", or \"Failed\" Notes: Additional details about the operation (e.g., \"Configuration does not exist on destination\", \"Requires restart\", or error message if failed) &nbsp;"
  },
  {
    "name": "Copy-DbaSsisCatalog",
    "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't 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.",
    "category": "Migration",
    "tags": [
      "migration",
      "ssis"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaSsisCatalog",
    "popularityRank": 100,
    "synopsis": "Migrates SSIS catalogs including folders, projects, and environments between SQL Server instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Copy-DbaSsisCatalog View Source Phil Schwartz (philschwartz.me, @pschwartzzz), the dbatools team + Claude Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Migrates SSIS catalogs including folders, projects, and environments between SQL Server instances. 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. By 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't exist, and automatically enable SQL CLR if required. The 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. Syntax Copy-DbaSsisCatalog [-Source] [-Destination] [[-SourceSqlCredential] ] [[-DestinationSqlCredential] ] [[-Project] ] [[-Folder] ] [[-Environment] ] [[-CreateCatalogPassword] ] [-EnableSqlClr] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all folders, environments and SSIS Projects from sqlserver2014a to sqlcluster, using Windows... PS C:\\> Copy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster Copies 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 destination they will be skipped, but projects will be redeployed. Example 2: Copies a single Project, the Archive_Tables Project, from sqlserver2014a to sqlcluster using SQL credentials... PS C:\\> Copy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -Project Archive_Tables -SourceSqlCredential $cred -Force Copies 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. If a Project with the same name exists on sqlcluster, it will be deleted and recreated because -Force was used. Example 3: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Example 4: Deploy entire SSIS catalog to an instance without a destination catalog PS C:\\> $SecurePW = Read-Host \"Enter password\" -AsSecureString PS C:\\> Copy-DbaSsisCatalog -Source sqlserver2014a -Destination sqlcluster -CreateCatalogPassword $SecurePW Deploy entire SSIS catalog to an instance without a destination catalog. User prompts for creating the catalog on Destination will be bypassed. Required Parameters -Source Source SQL Server instance containing the SSISDB catalog to copy from. Requires sysadmin privileges and SQL Server 2012 or higher. This instance must have Integration Services installed with an existing SSISDB catalog containing the folders, projects, and environments you want to migrate. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Destination SQL Server instances where the SSISDB catalog will be copied to. Requires sysadmin privileges and SQL Server 2012 or higher. If SSISDB doesn't exist on the destination, the function will offer to create it automatically including enabling CLR integration if needed. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. Accepts PowerShell credential objects created with Get-Credential and supports SQL Authentication, Windows Authentication, and Active Directory authentication modes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Accepts PowerShell credential objects created with Get-Credential and supports SQL Authentication, Windows Authentication, and Active Directory authentication modes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you only need to migrate a specific Integration Services project rather than the entire catalog structure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this to limit the migration scope when you only need to move contents of a specific organizational folder. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Environment Specifies a single SSIS environment to copy instead of migrating all environments. The environment will be deployed from whichever source folder contains it. Use this when you only need to migrate specific environment configurations that contain your parameter values and connection strings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CreateCatalogPassword Password for creating a new SSISDB catalog on the destination as a SecureString object. Required when the destination doesn't have an existing SSISDB catalog. Use this in automated scripts to avoid interactive password prompts during catalog creation. The password encrypts sensitive data within the SSISDB catalog. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableSqlClr Automatically enables CLR integration on the destination without prompting for confirmation. CLR integration is required for SSISDB catalog functionality. Use this in automated scenarios where you want to avoid interactive prompts when the destination server doesn't have CLR enabled. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Without this parameter, the function will skip objects that already exist at the destination and display warning messages. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per migration operation attempt. Each object represents the result of copying a single folder, project, or environment to a destination instance. Default display properties (via Select-DefaultView with TypeName MigrationObject): DateTime: Timestamp when the migration operation occurred (DbaDateTime) SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Name: Name of the object that was copied (folder, project, or environment name) Type: Object type (Folder, Project, or Environment) Status: Result of the migration attempt (Successful, Skipped, or Failed) Notes: Additional details about the operation or reason for skipping/failure &nbsp;"
  },
  {
    "name": "Copy-DbaStartupProcedure",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "procedure",
      "startup",
      "startupprocedure"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaStartupProcedure",
    "popularityRank": 355,
    "synopsis": "Copies startup procedures from master database between SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaStartupProcedure View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies startup procedures from master database between SQL Server instances 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. This 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. By 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. Syntax Copy-DbaStartupProcedure [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Procedure] ] [[-ExcludeProcedure] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all startup procedures from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaStartupProcedure -Source sqlserver2014a -Destination sqlcluster Copies 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. Example 2: Copies only the startup procedure, logstartup, from sqlserver2014a to sqlcluster using SQL credentials for... PS C:\\> Copy-DbaStartupProcedure -Source sqlserver2014a -SourceSqlCredential $scred -Destination sqlcluster -DestinationSqlCredential $dcred -Procedure logstartup -Force Copies 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 sqlcluster, it will be updated because -Force was used. Example 3: Copies all the startup procedures found on sqlserver2014a except logstartup to sqlcluster PS C:\\> Copy-DbaStartupProcedure -Source sqlserver2014a -Destination sqlcluster -ExcludeProcedure logstartup -Force Copies 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. Example 4: Shows what would happen if the command were executed using force PS C:\\> Copy-DbaStartupProcedure -Source sqlserver2014a -Destination sqlcluster -WhatIf -Force Required Parameters -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. Use this to specify which server has the startup procedures you want to migrate or standardize across your environment. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. Accepts multiple destinations to deploy startup procedures across several servers simultaneously for standardization. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Credentials for connecting to the source SQL Server instance when Windows authentication is not available or desired. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instance(s) when Windows authentication is not available or desired. Use this when deploying to servers that require different authentication credentials or when your current context lacks destination access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Procedure Specifies which startup procedures to copy from the source server instead of copying all available startup procedures. Use this when you only need specific procedures migrated, such as copying just monitoring or initialization procedures while leaving others behind. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeProcedure Specifies which startup procedures to skip during the copy operation while processing all others from the source. Use this when most startup procedures should be copied but specific ones need to remain server-specific or are problematic. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Overwrites existing startup procedures on the destination server instead of skipping them when name conflicts occur. Use this when updating existing startup procedures with newer versions or when you need to ensure destination procedures match the source exactly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per startup procedure copy operation. The object represents the outcome of copying a single startup procedure from source to destination. Default display properties (via Select-DefaultView): DateTime: Timestamp when the copy operation occurred SourceServer: Name of the source SQL Server instance DestinationServer: Name of the destination SQL Server instance Name: Name of the startup procedure Type: Type of object being copied (always \"Startup Stored Procedure\") Status: Result of the copy operation (Successful, Skipped, or Failed) Notes: Additional information or error message if applicable Additional properties available: Schema: Schema that the stored procedure belongs to in the master database &nbsp;"
  },
  {
    "name": "Copy-DbaSystemDbUserObject",
    "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's particularly valuable during server migrations or when standardizing DBA tooling across multiple instances.",
    "category": "Migration",
    "tags": [
      "migration",
      "systemdatabase",
      "userobject"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaSystemDbUserObject",
    "popularityRank": 320,
    "synopsis": "Copies user-created objects from system databases (master, msdb, model) between SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaSystemDbUserObject View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies user-created objects from system databases (master, msdb, model) between SQL Server instances. 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. This function handles schemas, tables, views, stored procedures, functions, triggers, and other user-defined objects while preserving dependencies and permissions. It's particularly valuable during server migrations or when standardizing DBA tooling across multiple instances. Syntax Copy-DbaSystemDbUserObject [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [-Force] [-Classic] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies user objects found in system databases master, msdb and model from sqlserver2014a instance to the... PS C:\\> Copy-DbaSystemDbUserObject -Source sqlserver2014a -Destination sqlcluster Copies user objects found in system databases master, msdb and model from sqlserver2014a instance to the sqlcluster instance. Required Parameters -Source Specifies the source SQL Server instance containing the user objects to copy from system databases. Requires sysadmin permissions to access master, msdb, and model databases for object extraction. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Specifies one or more destination SQL Server instances where the user objects will be copied to. Requires sysadmin permissions to modify master, msdb, and model databases on the destination servers. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Specifies credentials for connecting to the source SQL Server instance when Windows Authentication is not available. Required when accessing source instances across domains or using SQL Server Authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Specifies credentials for connecting to destination SQL Server instances when Windows Authentication is not available. Required when accessing destination instances across domains or using SQL Server Authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Drops existing objects on destination instances before creating new ones to resolve naming conflicts. Only works with the default modern method, not with Classic mode, and may fail with objects that have dependencies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Classic Uses the legacy migration method that copies all object types in bulk using SQL Server Management Objects Transfer class. The default modern method provides better error handling and granular object control but this option may resolve compatibility issues with older SQL Server versions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (default when -Classic is not specified) Returns one object per user-defined object (schema, table, view, function, trigger, etc.) copied from system databases. The Classic mode returns no output. Properties: DateTime: The date and time the operation completed (DbaDateTime) SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The name of the object copied (schema name, table name, or fully qualified object name with schema) Type: The type of object and system database (e.g., \"User schema in master\", \"User table in msdb\", \"User stored procedure in master\") Status: The result of the copy operation (Successful, Skipped, or Failed) Notes: Additional context about the operation result (e.g., \"Already exists on destination\", \"May have also created dependencies\", error details) &nbsp;"
  },
  {
    "name": "Copy-DbaXESession",
    "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're 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.",
    "category": "Migration",
    "tags": [
      "migration",
      "extendedevent",
      "xevent"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaXESession",
    "popularityRank": 373,
    "synopsis": "Copies Extended Event sessions from one SQL Server instance to another, excluding system sessions.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaXESession View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies Extended Event sessions from one SQL Server instance to another, excluding system sessions. 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. System sessions (AlwaysOn_health and system_health) are automatically excluded since they're 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. Perfect 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. Syntax Copy-DbaXESession [-Source] [-Destination] [[-SourceSqlCredential] ] [[-DestinationSqlCredential] ] [[-XeSession] ] [[-ExcludeXeSession] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all Extended Event sessions from sqlserver2014a to sqlcluster using Windows credentials PS C:\\> Copy-DbaXESession -Source sqlserver2014a -Destination sqlcluster Example 2: Copies all Extended Event sessions from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a... PS C:\\> Copy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred Copies all Extended Event sessions from sqlserver2014a to sqlcluster using SQL credentials for sqlserver2014a and Windows credentials for sqlcluster. Example 3: Shows what would happen if the command were executed PS C:\\> Copy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -WhatIf Example 4: Copies only the Extended Events named CheckQueries and MonitorUserDefinedException from sqlserver2014a to... PS C:\\> Copy-DbaXESession -Source sqlserver2014a -Destination sqlcluster -XeSession CheckQueries, MonitorUserDefinedException Copies only the Extended Events named CheckQueries and MonitorUserDefinedException from sqlserver2014a to sqlcluster. Required Parameters -Source The source SQL Server instance containing the Extended Event sessions to copy. Requires sysadmin privileges and SQL Server 2012 or higher. This is typically your production server or template instance where you've configured custom monitoring and auditing sessions. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination One or more destination SQL Server instances where Extended Event sessions will be recreated. Accepts arrays for bulk deployment to multiple servers. Common scenarios include disaster recovery sites, development environments, or new production servers that need the same monitoring configuration. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential SQL Server authentication credentials for connecting to the source instance. Required when Windows authentication is disabled or unavailable. Use Get-Credential to securely prompt for credentials or pass an existing PSCredential object for automated scripts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential SQL Server authentication credentials for connecting to all destination instances. Used when destination servers require different authentication than the source. Single credential object applies to all destinations - use separate commands if different destinations need different credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -XeSession Specific Extended Event session names to copy instead of all custom sessions. Accepts arrays of session names for selective migration. Use this when you only need specific monitoring sessions, such as copying just audit-related sessions to a compliance server or performance sessions to development. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeXeSession Extended Event session names to exclude from the copy operation. Use this to skip sessions inappropriate for the destination environment. Common use cases include excluding production-specific auditing sessions when copying to development or excluding resource-intensive sessions on smaller test servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Drops and recreates existing Extended Event sessions with matching names on the destination servers. Without this parameter, existing sessions are skipped. Use this when you need to update session configurations or when consolidating monitoring setups from multiple sources requires overwriting existing sessions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (with TypeName: MigrationObject) Returns one object per Extended Event session processed, documenting the migration status for each session copy attempt. Properties: DateTime: Timestamp (DbaDateTime) when the migration operation occurred SourceServer: Name of the source SQL Server instance from which the session was copied DestinationServer: Name of the destination SQL Server instance where the session was copied to Name: Name of the Extended Event session being migrated Type: Always \"Extended Event\" indicating the object type being migrated Status: Migration result (Successful, Skipped, or Failed) Notes: Additional information; null for successful migrations, error message for failed operations or \"Already exists on destination\" for skipped sessions &nbsp;"
  },
  {
    "name": "Copy-DbaXESessionTemplate",
    "description": "Installs curated Extended Event session templates into SQL Server Management Studio's 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.",
    "category": "Migration",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Copy",
    "popular": false,
    "url": "/Copy-DbaXESessionTemplate",
    "popularityRank": 549,
    "synopsis": "Copies Extended Event session templates from dbatools repository to SSMS template directory for GUI access.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Copy-DbaXESessionTemplate View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies Extended Event session templates from dbatools repository to SSMS template directory for GUI access. Description Installs curated Extended Event session templates into SQL Server Management Studio's template directory so you can access them through the SSMS GUI. The templates include common monitoring scenarios like deadlock detection, query performance tracking, connection monitoring, and database health checks. Only copies non-Microsoft templates, preserving any custom templates already in your SSMS directory while adding the community-contributed ones from the dbatools collection. Syntax Copy-DbaXESessionTemplate [[-Path] ] [[-Destination] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Copies non-Microsoft templates from the dbatools template repository (/bin/XEtemplates/) to... PS C:\\> Copy-DbaXESessionTemplate Copies non-Microsoft templates from the dbatools template repository (/bin/XEtemplates/) to $home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates. Example 2: Copies your templates from C:\\temp\\XEtemplates to $home\\Documents\\SQL Server Management... PS C:\\> Copy-DbaXESessionTemplate -Path C:\\temp\\XEtemplates Copies your templates from C:\\temp\\XEtemplates to $home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates. Optional Parameters -Path Specifies the directory containing Extended Event session template files to copy from. Defaults to the dbatools template repository (/bin/XEtemplates/). Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \"$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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \"$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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs None This 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 (non-Microsoft templates only by default). Use Write-Message output or monitoring the destination directory to confirm successful completion. &nbsp;"
  },
  {
    "name": "Disable-DbaAgHadr",
    "description": "Disables the HADR service setting at the SQL Server instance level, effectively removing the instance's 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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Disable",
    "popular": false,
    "url": "/Disable-DbaAgHadr",
    "popularityRank": 398,
    "synopsis": "Disables High Availability Disaster Recovery (HADR) capability on SQL Server instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Disable-DbaAgHadr View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Disables High Availability Disaster Recovery (HADR) capability on SQL Server instances. Description Disables the HADR service setting at the SQL Server instance level, effectively removing the instance's 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. The 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. Syntax Disable-DbaAgHadr [-SqlInstance] [[-Credential] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets Hadr service to disabled for the instance sql2016 but changes will not be applied until the next time... PS C:\\> Disable-DbaAgHadr -SqlInstance sql2016 Sets Hadr service to disabled for the instance sql2016 but changes will not be applied until the next time the server restarts. Example 2: Sets Hadr service to disabled for the instance sql2016, and restart the service to apply the change PS C:\\> Disable-DbaAgHadr -SqlInstance sql2016 -Force Example 3: Sets Hadr service to disabled for the instance dev1 on sq2012, and restart the service to apply the change PS C:\\> Disable-DbaAgHadr -SqlInstance sql2012\\dev1 -Force Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Credential object used to connect to the Windows server as a different user | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 restart to take effect. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per successfully processed instance, containing the following properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance (e.g., MSSQLSERVER or named instance) SqlInstance: The full SQL Server instance identifier in the format ComputerName\\InstanceName IsHadrEnabled: Boolean value indicating the HADR status (always $false for successful disable operations) &nbsp;"
  },
  {
    "name": "Disable-DbaDbEncryption",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Disable",
    "popular": false,
    "url": "/Disable-DbaDbEncryption",
    "popularityRank": 315,
    "synopsis": "Disables Transparent Data Encryption (TDE) on SQL Server databases and removes encryption keys",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Disable-DbaDbEncryption View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Disables Transparent Data Encryption (TDE) on SQL Server databases and removes encryption keys 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. This 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. Use 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. Syntax Disable-DbaDbEncryption [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-InputObject] ] [-NoEncryptionKeyDrop] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Disables database encryption on the pubs database on sql2017 and sql2016 PS C:\\> Disable-DbaDbEncryption -SqlInstance sql2017, sql2016 -Database pubs Example 2: Suppresses all prompts to disable database encryption on the db1 database on sql2017 PS C:\\> Disable-DbaDbEncryption -SqlInstance sql2017 -Database db1 -Confirm:$false Example 3: Suppresses all prompts to disable database encryption on the db1 database on sql2017 (using piping) PS C:\\> Get-DbaDatabase -SqlInstance sql2017 -Database db1 | Disable-DbaDbEncryption -Confirm:$false Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to disable TDE encryption on. Accepts multiple database names as an array. Required when using SqlInstance parameter to target specific databases instead of processing all encrypted databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase for pipeline processing. This allows you to filter databases using Get-DbaDatabase criteria before disabling TDE. Useful when you need to disable encryption on databases that match specific conditions like owner, compatibility level, or encryption status. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -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. Use 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 manually removed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Database Returns one Database object for each database where encryption was disabled. The object reflects the database state after TDE was disabled. Default display properties (via Select-DefaultView): ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName) DatabaseName: The name of the database where encryption was disabled (aliased from Name property) EncryptionEnabled: Boolean indicating whether Transparent Data Encryption is enabled (will be $false after execution) Additional properties available from the SMO Database object include all standard database properties such as Owner, Collation, CompatibilityLevel, RecoveryModel, Status, Size, and many others. Access these using Select-Object * if needed. &nbsp;"
  },
  {
    "name": "Disable-DbaFilestream",
    "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.",
    "category": "Utilities",
    "tags": [
      "filestream"
    ],
    "verb": "Disable",
    "popular": false,
    "url": "/Disable-DbaFilestream",
    "popularityRank": 588,
    "synopsis": "Disables SQL Server FileStream functionality at both the service and instance levels",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Disable-DbaFilestream View Source Stuart Moore (@napalmgram) , Chrissy LeMaire (@cl) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Disables SQL Server FileStream functionality at both the service and instance levels 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. The 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. By 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. Syntax Disable-DbaFilestream [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Prompts for confirmation PS C:\\> Disable-DbaFilestream -SqlInstance server1\\instance2 Prompts for confirmation. Disables filestream on the service and instance levels. Example 2: Does not prompt for confirmation PS C:\\> Disable-DbaFilestream -SqlInstance server1\\instance2 -Confirm:$false Does not prompt for confirmation. Disables filestream on the service and instance levels. Example 3: Using this pipeline you can scan a range of SQL instances and disable filestream on only those on which it&#39;s... PS C:\\> Get-DbaFilestream -SqlInstance server1\\instance2, server5\\instance5, prod\\hr | Where-Object InstanceAccessLevel -gt 0 | Disable-DbaFilestream -Force Using this pipeline you can scan a range of SQL instances and disable filestream on only those on which it's enabled. Required Parameters -SqlInstance The target SQL Server instance or instances. Defaults to localhost. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Credential Login to the target server using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Force Bypasses confirmation prompts and automatically restarts the SQL Server service to apply FileStream configuration changes immediately. Without this parameter, the function makes configuration changes but requires you to manually restart the SQL service later for changes to take effect. Use with caution in production environments as it causes service downtime during the restart. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command runs. The command is not run unless Force is specified. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL instance showing the FileStream configuration status after the disabling operation completes. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) InstanceAccess: Description of FileStream access level at the instance (should be \"Disabled\" after successful execution) ServiceAccess: Description of FileStream access level at the service level (should be \"Disabled\" after successful execution) ServiceShareName: The Windows share name used for FileStream data access (if configured) *Additional properties available (use Select-Object ):** InstanceAccessLevel: Numeric instance-level FileStream access level (0 = Disabled, 1 = T-SQL access, 2 = Full access) 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) Credential: The Windows credential used to access the server SqlCredential: The SQL Server credential used for the connection &nbsp;"
  },
  {
    "name": "Disable-DbaForceNetworkEncryption",
    "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't 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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Disable",
    "popular": false,
    "url": "/Disable-DbaForceNetworkEncryption",
    "popularityRank": 162,
    "synopsis": "Disables Force Network Encryption setting in SQL Server Configuration Manager",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Disable-DbaForceNetworkEncryption View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Disables Force Network Encryption setting in SQL Server Configuration Manager 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't 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. Syntax Disable-DbaForceNetworkEncryption [[-SqlInstance] ] [[-Credential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Disables Force Encryption on the default (MSSQLSERVER) instance on localhost - requires (and checks for)... PS C:\\> Disable-DbaForceNetworkEncryption Disables Force Encryption on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin. Example 2: Disables Force Network Encryption for the SQL2008R2SP2 on sql01 PS C:\\> Disable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2 Disables Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and modify the registry. Example 3: Shows what would happen if the command were executed PS C:\\> Disable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2 -WhatIf Optional Parameters -SqlInstance The target SQL Server instance or instances where Force Network Encryption will be disabled in the Windows registry. Use this to specify which SQL Server instances need their encryption requirements modified, typically for troubleshooting connectivity issues or supporting legacy applications that don't support encrypted connections. Defaults to localhost. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Specifies Windows credentials for connecting to the target computer to modify registry settings. The account must have local administrator privileges on the target server since this function modifies the Windows registry and uses PowerShell remoting. Use this when your current credentials don't have the required administrative access to the target machine. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance processed, indicating whether Force Network Encryption was successfully disabled. Properties: ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The name of the SQL Server instance (e.g., MSSQLSERVER, SQL2008R2SP2) SqlInstance: The full SQL Server instance identifier in the format ComputerName\\InstanceName ForceEncryption: Boolean indicating the current state of Force Encryption setting after the operation (False indicates encryption is not forced) CertificateThumbprint: The thumbprint of the certificate assigned to the SQL Server instance for network encryption &nbsp;"
  },
  {
    "name": "Disable-DbaHideInstance",
    "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't 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 > Protocols for \"InstanceName\".",
    "category": "Server Management",
    "tags": [
      "instance",
      "security"
    ],
    "verb": "Disable",
    "popular": false,
    "url": "/Disable-DbaHideInstance",
    "popularityRank": 575,
    "synopsis": "Makes SQL Server instances visible to network discovery by disabling the Hide Instance registry setting.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Disable-DbaHideInstance View Source Gareth Newman (@gazeranco), ifexists.blog Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Makes SQL Server instances visible to network discovery by disabling the Hide Instance registry setting. 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't respond to browse requests, which is often used for security hardening but makes instances harder to locate. This 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. This 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 > Protocols for \"InstanceName\". Syntax Disable-DbaHideInstance [[-SqlInstance] ] [[-Credential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Disables Hide Instance of SQL Engine on the default (MSSQLSERVER) instance on localhost PS C:\\> Disable-DbaHideInstance Disables Hide Instance of SQL Engine on the default (MSSQLSERVER) instance on localhost. Requires (and checks for) RunAs admin. Example 2: Disables Hide Instance of SQL Engine for the SQL2008R2SP2 on sql01 PS C:\\> Disable-DbaHideInstance -SqlInstance sql01\\SQL2008R2SP2 Disables Hide Instance of SQL Engine for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both connect and modify the registry. Example 3: Shows what would happen if the command were executed PS C:\\> Disable-DbaHideInstance -SqlInstance sql01\\SQL2008R2SP2 -WhatIf Optional Parameters -SqlInstance The target SQL Server instance or instances to make visible to network discovery. Specify the server name and instance name (e.g., 'SQL01\\PROD') to unhide specific named instances, or just the server name for default instances. Accepts multiple instances for bulk operations across your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Windows credentials for accessing the target computer's registry remotely. Required when your current Windows account lacks administrative access to modify the HideInstance registry setting on the remote server. Note this is for Windows authentication, not SQL Server login credentials, since this function modifies the Windows registry. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per instance successfully modified. The object contains the results of disabling the Hide Instance setting. Properties: ComputerName: The name of the computer where the HideInstance setting was modified InstanceName: The SQL Server instance name (e.g., 'PROD', 'SQL2008R2SP2') SqlInstance: The full SQL Server instance identifier (computer\\instancename format) HideInstance: Boolean indicating if the instance is now hidden ($true) or visible ($false) &nbsp;"
  },
  {
    "name": "Disable-DbaReplDistributor",
    "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.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Disable",
    "popular": false,
    "url": "/Disable-DbaReplDistributor",
    "popularityRank": 618,
    "synopsis": "Removes SQL Server replication distribution configuration from target instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Disable-DbaReplDistributor View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Server replication distribution configuration from target instances. 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. Syntax Disable-DbaReplDistributor [-SqlInstance] [[-SqlCredential] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Disables replication distribution for the mssql1 instance PS C:\\> Disable-DbaReplDistributor -SqlInstance mssql1 Example 2: Disables replication distribution for the mssql1 and mssql2 instances using a sql login PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Disable-DbaReplDistributor -SqlInstance mssql1, mssql2 -SqlCredential $cred -Force Disables 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 regardless of whether or not dependent publishing and distribution objects are uninstalled. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Forces removal of the distributor configuration even when dependent replication objects exist or remote publishers cannot be contacted. Use this when decommissioning a distributor that has orphaned publications or when network connectivity to remote publishers is unavailable. Without Force, the command will fail if any local databases are enabled for publishing or if publisher/distribution databases haven't been cleanly removed first. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Replication.ReplicationServer Returns 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; if it is not, a terminating error is raised instead. Default display properties (via Select-DefaultView): ComputerName: The name of the computer running the SQL Server instance InstanceName: The name of the SQL Server instance SqlInstance: The fully qualified SQL Server instance name (ComputerName\\InstanceName) IsDistributor: Boolean indicating whether the instance is configured as a distributor (False after successful removal) IsPublisher: Boolean indicating whether the instance is configured as a publisher DistributionServer: The name of the distribution server (if configured) DistributionDatabase: The name of the distribution database (if configured) Additional properties available (from SMO ReplicationServer object): AgentCheckupInterval: Interval in seconds for replication agent health checks DisruptiveAdministrativeAction: Indicates if a disruptive administrative action was performed DistributionDatabases: Collection of distribution databases DistributionServerName: Name of the distribution server DistributionTables: Collection of distribution tables EnabledReplicationAgentProfile: Name of the enabled replication agent profile DistributionRetention: Number of days distribution data is retained MaxDistributionRetention: Maximum distribution retention in days MinDistributionRetention: Minimum distribution retention in days PublisherName: Name of the publisher SubscriptionCleanupInterval: Interval in seconds for subscription cleanup All properties from the base ReplicationServer object are accessible via Select-Object *. &nbsp;"
  },
  {
    "name": "Disable-DbaReplPublishing",
    "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.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Disable",
    "popular": false,
    "url": "/Disable-DbaReplPublishing",
    "popularityRank": 639,
    "synopsis": "Disables replication publishing on SQL Server instances and removes publisher configuration.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Disable-DbaReplPublishing View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Disables replication publishing on SQL Server instances and removes publisher configuration. 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. Syntax Disable-DbaReplPublishing [-SqlInstance] [[-SqlCredential] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Disables replication distribution for the mssql1 instance PS C:\\> Disable-DbaReplPublishing -SqlInstance mssql1 Example 2: Disables replication distribution for the mssql1 and mssql2 instances using a sql login PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Disable-DbaReplPublishing -SqlInstance mssql1, mssql2 -SqlCredential $cred -Force Disables replication distribution for the mssql1 and mssql2 instances using a sql login. Specifies force so all the replication objects associated with the Publisher are dropped even if the Publisher is on a remote server that cannot be reached. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Forces the removal of publisher configuration without verifying the distributor connection status. Use this when the distributor server is unreachable or when you need to forcibly clean up orphaned replication objects. Without this switch, the function will fail if it cannot communicate with the distributor to perform proper cleanup verification. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Replication.ReplicationServer Returns the ReplicationServer object for each instance after disabling publishing. The instance is returned with its publisher configuration removed from the distributor. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) IsDistributor: Boolean indicating whether this instance is configured as a distributor IsPublisher: Boolean indicating whether this instance is configured as a publisher (will be False after successful execution) DistributionServer: The name of the server hosting the distribution database DistributionDatabase: The name of the distribution database *Additional properties available on the ReplicationServer object (accessible via Select-Object ):** DistributionDatabases: Collection of distribution databases on this distributor DistributionPublishers: Collection of publishers registered with this distributor Subscribers: Collection of subscribers connected to this distributor PublisherDatabases: Collection of databases published from this instance SubscriptionServers: Collection of subscription servers ConnectionContext: The server connection context used for RMO operations &nbsp;"
  },
  {
    "name": "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.",
    "category": "Utilities",
    "tags": [
      "procedure",
      "startup",
      "startupprocedure"
    ],
    "verb": "Disable",
    "popular": false,
    "url": "/Disable-DbaStartupProcedure",
    "popularityRank": 623,
    "synopsis": "Removes stored procedures from SQL Server's automatic startup execution list",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Disable-DbaStartupProcedure View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes stored procedures from SQL Server's automatic startup execution list Description Prevents stored procedures from automatically executing when the SQL Server service starts by clearing their startup designation in the master database. This is essential when troubleshooting startup issues or removing procedures that were previously configured to run at service startup. Equivalent to running sp_procoption with @OptionValue = off, but provides object-based management with detailed status reporting. Returns enhanced SMO StoredProcedure objects showing the action results and current startup status. Syntax Disable-DbaStartupProcedure [[-SqlInstance] ] [[-SqlCredential] ] [[-StartupProcedure] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Attempts to clear the automatic execution of the procedure &#39;[dbo].[StartUpProc1]&#39; in the master database of... PS C:\\> Disable-DbaStartupProcedure -SqlInstance SqlBox1\\Instance2 -StartupProcedure '[dbo].[StartUpProc1]' Attempts to clear the automatic execution of the procedure '[dbo].[StartUpProc1]' in the master database of SqlBox1\\Instance2 when the instance is started. Example 2: Attempts to clear the automatic execution of the procedure &#39;[dbo].[StartUpProc1]&#39; in the master database of... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Disable-DbaStartupProcedure -SqlInstance winserver\\sqlexpress, sql2016 -SqlCredential $cred -StartupProcedure '[dbo].[StartUpProc1]' Attempts to clear the automatic execution of the procedure '[dbo].[StartUpProc1]' in the master database of winserver\\sqlexpress and sql2016 when the instance is started. Connects using sqladmin credential Example 3: Get all startup procedures for the sql2016 instance and disables them by piping to Disable-DbaStartupProcedure PS C:\\> Get-DbaStartupProcedure -SqlInstance sql2016 | Disable-DbaStartupProcedure Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartupProcedure Specifies the stored procedure names to remove from automatic startup execution. Accepts schema-qualified names like '[dbo].[MyStartupProc]'. Use this when you know the specific procedure names that need their startup designation disabled. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts stored procedure objects from Get-DbaStartupProcedure via pipeline input. Use this when working with the results of Get-DbaStartupProcedure to disable multiple startup procedures at once. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.StoredProcedure Returns one StoredProcedure object per procedure that was processed, with the Startup property updated and additional status properties added. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database containing the stored procedure (always 'master') Schema: The schema containing the stored procedure Name: The name of the stored procedure Startup: Boolean indicating if the procedure will run at SQL Server startup (always $false after successful disable) Action: The action performed ('Disable') Status: Boolean indicating if the disable operation succeeded ($true for success, $false for skipped or failed) Note: A string message describing the result ('Action Disable already performed', 'Disable succeeded', 'Disable skipped', or 'Disable failed') Additional properties available (from SMO StoredProcedure object): IsSystemObject: Boolean indicating if this is a system object CreateDate: DateTime when the procedure was created DateLastModified: DateTime when the procedure was last modified Text: The T-SQL source code of the stored procedure Parent: The Database object containing the procedure All properties from the base SMO StoredProcedure object are accessible via Select-Object *. &nbsp;"
  },
  {
    "name": "Disable-DbaTraceFlag",
    "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.",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "traceflag",
      "dbcc"
    ],
    "verb": "Disable",
    "popular": false,
    "url": "/Disable-DbaTraceFlag",
    "popularityRank": 535,
    "synopsis": "Disables globally running trace flags on SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Disable-DbaTraceFlag View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Disables globally running trace flags on SQL Server instances Description Turns off trace flags that are currently enabled globally across SQL Server instances using DBCC TRACEOFF. Useful when you need to disable diagnostic trace flags that were enabled for troubleshooting or testing without requiring a restart. Only affects flags currently running in memory - does not modify startup parameters or persistent trace flag settings. Use Set-DbaStartupParameter to manage trace flags that persist after restarts. Syntax Disable-DbaTraceFlag [-SqlInstance] [[-SqlCredential] ] [-TraceFlag] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Disable the globally running trace flag 3226 on SQL Server instance sql2016 PS C:\\> Disable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 3226 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -TraceFlag Specifies the trace flag numbers to disable globally across all sessions on the SQL Server instance. Only trace flags that are currently running will be disabled - flags not currently active are skipped with a warning. Supports multiple trace flag numbers to disable several flags in a single operation. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per trace flag that was processed. The object contains the status and result of the disable operation. Properties: SourceServer: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) TraceFlag: The trace flag number that was disabled or skipped Status: The result of the operation (Successful, Skipped, or Failed) Notes: Additional details about the operation result or error message DateTime: Timestamp of when the operation was executed &nbsp;"
  },
  {
    "name": "Disconnect-DbaInstance",
    "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",
    "category": "Server Management",
    "tags": [
      "connection"
    ],
    "verb": "Disconnect",
    "popular": false,
    "url": "/Disconnect-DbaInstance",
    "popularityRank": 121,
    "synopsis": "Closes active SQL Server connections and removes them from the dbatools connection cache",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Disconnect-DbaInstance View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Closes active SQL Server connections and removes them from the dbatools connection cache 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. To clear all of your connection pools, use Clear-DbaConnectionPool Syntax Disconnect-DbaInstance [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Disconnects all connected instances PS C:\\> Get-DbaConnectedInstance | Disconnect-DbaInstance Example 2: Disconnects selected SQL Server instances PS C:\\> Get-DbaConnectedInstance | Out-GridView -Passthru | Disconnect-DbaInstance Example 3: Disconnects the $server connection PS C:\\> $server = Connect-DbaInstance -SqlInstance sql01 PS C:\\> $server | Disconnect-DbaInstance Optional Parameters -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 disconnect multiple connections at once. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per connection successfully disconnected. Contains the following properties: Default display properties (via Select-DefaultView): SqlInstance: The name of the SQL Server instance that was disconnected ConnectionType: The full type name of the connection object (e.g., Microsoft.SqlServer.Management.Smo.Server or System.Data.SqlClient.SqlConnection) State: The state of the connection after disconnection (Disconnected or Closed) Additional properties available: ConnectionString: The masked/hidden connection string used for the connection &nbsp;"
  },
  {
    "name": "Dismount-DbaDatabase",
    "description": "Safely detaches databases from SQL Server instances while performing comprehensive validation checks before detachment. This function automatically validates that databases aren't 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.",
    "category": "Database Operations",
    "tags": [
      "detach",
      "database"
    ],
    "verb": "Dismount",
    "popular": false,
    "url": "/Dismount-DbaDatabase",
    "popularityRank": 188,
    "synopsis": "Detaches one or more databases from a SQL Server instance with built-in safety checks and validation.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Dismount-DbaDatabase View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Detaches one or more databases from a SQL Server instance with built-in safety checks and validation. Description Safely detaches databases from SQL Server instances while performing comprehensive validation checks before detachment. This function automatically validates that databases aren't 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. Syntax Dismount-DbaDatabase [-SqlCredential ] [-UpdateStatistics] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Dismount-DbaDatabase -SqlInstance [-SqlCredential ] -Database [-UpdateStatistics] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Dismount-DbaDatabase [-SqlCredential ] -InputObject [-UpdateStatistics] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Detaches SharePoint_Config and WSS_Logging from sql2016b PS C:\\> Detach-DbaDatabase -SqlInstance sql2016b -Database SharePoint_Config, WSS_Logging Example 2: Detaches &#39;PerformancePoint Service Application_10032db0fa0041df8f913f558a5dc0d4&#39; from sql2016b PS C:\\> Get-DbaDatabase -SqlInstance sql2016b -Database 'PerformancePoint Service Application_10032db0fa0041df8f913f558a5dc0d4' | Detach-DbaDatabase -Force Detaches 'PerformancePoint Service Application_10032db0fa0041df8f913f558a5dc0d4' from sql2016b. Since Force was specified, if the database is part of mirror, the mirror will be broken prior to detaching. If the database is part of an Availability Group, it will first be dropped prior to detachment. Example 3: Shows what would happen if the command were to execute (without actually executing the detach/break/remove... PS C:\\> Get-DbaDatabase -SqlInstance sql2016b -Database WSS_Logging | Detach-DbaDatabase -Force -WhatIf Shows what would happen if the command were to execute (without actually executing the detach/break/remove commands). Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Database Specifies the name(s) of databases to detach from the SQL Server instance. Accepts wildcards for pattern matching. Use this when you need to detach specific databases by name rather than passing database objects through the pipeline. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from the pipeline for detachment operations. Typically used with Get-DbaDatabase output. This allows you to filter and select databases using Get-DbaDatabase before detaching them, providing more control over the selection process. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -UpdateStatistics Updates database statistics before detaching the database to ensure optimal performance if the database is later reattached. Use this when you plan to reattach the database later and want to maintain current statistics for query optimization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 user connections. Use this when you need to detach databases that are part of high availability configurations or have active connections that cannot be closed gracefully. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per successfully detached database with the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database that was detached DatabaseID: The unique identifier of the detached database DetachResult: Status of the detach operation (Success) &nbsp;"
  },
  {
    "name": "Enable-DbaAgHadr",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Enable",
    "popular": false,
    "url": "/Enable-DbaAgHadr",
    "popularityRank": 166,
    "synopsis": "Enables HADR service setting on SQL Server instances to allow Availability Group creation.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Enable-DbaAgHadr View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Enables HADR service setting on SQL Server instances to allow Availability Group creation. 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. Syntax Enable-DbaAgHadr [-SqlInstance] [[-Credential] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets Hadr service to enabled for the instance sql2016 but changes will not be applied until the next time the... PS C:\\> Enable-DbaAgHadr -SqlInstance sql2016 Sets Hadr service to enabled for the instance sql2016 but changes will not be applied until the next time the server restarts. Example 2: Sets Hadr service to enabled for the instance sql2016, and restart the service to apply the change PS C:\\> Enable-DbaAgHadr -SqlInstance sql2016 -Force Example 3: Sets Hadr service to disabled for the instance dev1 on sq2012, and restart the service to apply the change PS C:\\> Enable-DbaAgHadr -SqlInstance sql2012\\dev1 -Force Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Windows credential object used to connect to the target server with different authentication context. Required when the current user lacks administrative privileges on the SQL Server host or when connecting across domain boundaries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Automatically restarts the SQL Server Database Engine and SQL Server Agent services to immediately apply the HADR setting change. Without this parameter, the HADR setting change requires a manual service restart before Availability Groups can be created. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance with the status of the HADR setting after the operation. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance or instance for default) IsHadrEnabled: Boolean indicating if HADR is now enabled (always $true on successful completion) &nbsp;"
  },
  {
    "name": "Enable-DbaDbEncryption",
    "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't 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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Enable",
    "popular": false,
    "url": "/Enable-DbaDbEncryption",
    "popularityRank": 203,
    "synopsis": "Enables Transparent Data Encryption (TDE) on SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Enable-DbaDbEncryption View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Enables Transparent Data Encryption (TDE) on SQL Server databases 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't 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. Syntax Enable-DbaDbEncryption [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-EncryptorName] ] [[-InputObject] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Enables database encryption on the pubs database on sql2017 and sql2016 PS C:\\> Enable-DbaDbEncryption -SqlInstance sql2017, sql2016 -Database pubs Example 2: Suppresses all prompts to enable database encryption on the db1 database on sql2017 PS C:\\> Enable-DbaDbEncryption -SqlInstance sql2017 -Database db1 -Confirm:$false Example 3: Suppresses all prompts to enable database encryption on the db1 database on sql2017 PS C:\\> Get-DbaDatabase -SqlInstance sql2017 -Database db1 | Enable-DbaDbEncryption -Confirm:$false Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to enable Transparent Data Encryption (TDE) on. Accepts multiple database names. Use this when you need to enable encryption on specific databases rather than all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EncryptorName Specifies the certificate name in the master database to use for encrypting the Database Encryption Key (DEK). If 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. The certificate must exist in the master database and should be backed up to prevent data loss. | Property | Value | | --- | --- | | Alias | Certificate,CertificateName | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase through the pipeline. Use this when you want to filter databases first with Get-DbaDatabase and then enable TDE on the results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Force Bypasses the certificate backup verification check and enables TDE even if the certificate hasn't been backed up. Use with extreme caution as this could lead to data loss if the certificate is lost without a backup. Only use this in development environments or when you have confirmed the certificate is backed up through other means. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Database Returns one Database object per database where encryption was enabled successfully. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: The name of the database where encryption was enabled (Name property aliased) EncryptionEnabled: Boolean indicating whether Transparent Data Encryption is now enabled on the database Additional properties available (from SMO Database object): CreateDate: DateTime when the database was created LastBackupDate: DateTime of the last database backup Owner: Database owner/principal name RecoveryModel: Database recovery model (Simple, Full, BulkLogged) Status: Current database status Size: Database size in megabytes DatabaseEncryptionKey: The Database Encryption Key object containing encryption details EncryptionAlgorithm: The algorithm used for encryption (AES_128, AES_192, AES_256) All properties from the base SMO Database object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Enable-DbaFilestream",
    "description": "Configures SQL Server's 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.",
    "category": "Utilities",
    "tags": [
      "filestream"
    ],
    "verb": "Enable",
    "popular": false,
    "url": "/Enable-DbaFilestream",
    "popularityRank": 453,
    "synopsis": "Configures FILESTREAM feature at both instance and server levels on SQL Server",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Enable-DbaFilestream View Source Stuart Moore (@napalmgram) , Chrissy LeMaire (@cl) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures FILESTREAM feature at both instance and server levels on SQL Server Description Configures SQL Server's 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. Syntax Enable-DbaFilestream [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [[-FileStreamLevel] ] [[-ShareName] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: These commands are functionally equivalent, both will set Filestream level on server1\\instance2 to T-Sql Only PS C:\\> Enable-DbaFilestream -SqlInstance server1\\instance2 -FileStreamLevel TSql PS C:\\> Enable-DbaFilestream -SqlInstance server1\\instance2 -FileStreamLevel 1 Example 2: Using this pipeline you can scan a range of SQL instances and enable filestream on only those on which it&#39;s... PS C:\\> Get-DbaFilestream -SqlInstance server1\\instance2, server5\\instance5, prod\\hr | Where-Object InstanceAccessLevel -eq 0 | Enable-DbaFilestream -FileStreamLevel TSqlIoStreamingRemoteClient -Force Using this pipeline you can scan a range of SQL instances and enable filestream on only those on which it's disabled. Required Parameters -SqlInstance The target SQL Server instance or instances. Defaults to localhost. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Credential Login to the target server using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -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. Use 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 scenarios. Accepts numeric values (1, 2, 3) or string equivalents (TSql, TSqlIoStreaming, TSqlIoStreamingRemoteClient). Defaults to level 1. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1 | | Accepted Values | 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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Automatically restarts the SQL Server service after enabling FILESTREAM without prompting for confirmation. Required for FILESTREAM changes to take effect immediately. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command runs. The command is not run unless Force is specified. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance with the current FILESTREAM configuration status after the configuration change is applied (or would be applied with -WhatIf). Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance identifier (ComputerName\\InstanceName) InstanceAccess: Human-readable description of the instance-level FILESTREAM access level (Disabled, T-SQL access enabled, or Full access enabled) 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 FileStream enabled for T-SQL, IO streaming, and remote clients) ServiceShareName: The Windows file share name used for FILESTREAM remote client access, if configured Additional properties available (not displayed by default): InstanceAccessLevel: Numeric value representing instance-level access (0 = Disabled, 1 = T-SQL access enabled, 2 = Full access enabled) 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) SqlCredential: The SQL Server credentials used for the connection Credential: The Windows credentials used for the connection All properties are accessible via Select-Object * if needed beyond the default display. &nbsp;"
  },
  {
    "name": "Enable-DbaForceNetworkEncryption",
    "description": "Modifies the Windows registry to force all client connections to SQL Server to use encryption, regardless of the client's 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.",
    "category": "Security",
    "tags": [
      "certificate",
      "encryption",
      "security"
    ],
    "verb": "Enable",
    "popular": false,
    "url": "/Enable-DbaForceNetworkEncryption",
    "popularityRank": 226,
    "synopsis": "Configures SQL Server to require encrypted connections from all clients by modifying the Windows registry",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Enable-DbaForceNetworkEncryption View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures SQL Server to require encrypted connections from all clients by modifying the Windows registry Description Modifies the Windows registry to force all client connections to SQL Server to use encryption, regardless of the client's 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. This 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. Important: 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. Syntax Enable-DbaForceNetworkEncryption [[-SqlInstance] ] [[-Credential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Enables Force Encryption on the default (MSSQLSERVER) instance on localhost PS C:\\> Enable-DbaForceNetworkEncryption Enables Force Encryption on the default (MSSQLSERVER) instance on localhost. Requires (and checks for) RunAs admin. Example 2: Enables Force Network Encryption for the SQL2008R2SP2 on sql01 PS C:\\> Enable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2 Enables Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both connect and modify the registry. Example 3: Shows what would happen if the command were executed PS C:\\> Enable-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2 -WhatIf Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $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. This is used for Windows authentication to the computer, not SQL Server login credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance where Force Encryption was enabled. Properties: ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The SQL Server instance name (e.g., SQL2008R2SP2) SqlInstance: The full SQL Server instance identifier (computer\\instance format) ForceEncryption: Boolean indicating whether Force Encryption was successfully enabled (will be $true on successful execution) CertificateThumbprint: The thumbprint of the SSL certificate configured for the instance, or $null if no certificate is configured &nbsp;"
  },
  {
    "name": "Enable-DbaHideInstance",
    "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.",
    "category": "Server Management",
    "tags": [
      "instance",
      "security"
    ],
    "verb": "Enable",
    "popular": false,
    "url": "/Enable-DbaHideInstance",
    "popularityRank": 519,
    "synopsis": "Enables the Hide Instance setting to prevent SQL Server Browser service from advertising the instance.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Enable-DbaHideInstance View Source Gareth Newman (@gazeranco), ifexists.blog Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Enables the Hide Instance setting to prevent SQL Server Browser service from advertising the instance. 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. The 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. This 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. Syntax Enable-DbaHideInstance [[-SqlInstance] ] [[-Credential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Enables Hide Instance of SQL Engine on the default (MSSQLSERVER) instance on localhost PS C:\\> Enable-DbaHideInstance Enables Hide Instance of SQL Engine on the default (MSSQLSERVER) instance on localhost. Requires (and checks for) RunAs admin. Example 2: Enables Hide Instance of SQL Engine for the SQL2008R2SP2 on sql01 PS C:\\> Enable-DbaHideInstance -SqlInstance sql01\\SQL2008R2SP2 Enables Hide Instance of SQL Engine for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both connect and modify the registry. Example 3: Shows what would happen if the command were executed PS C:\\> Enable-DbaHideInstance -SqlInstance sql01\\SQL2008R2SP2 -WhatIf Optional Parameters -SqlInstance The target SQL Server instance or instances where you want to enable the Hide Instance setting. This parameter accepts server names, server\\instance combinations, or fully qualified domain names. When not specified, defaults to the local computer's default instance (MSSQLSERVER). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Windows credentials used to connect to the target computer and modify the registry settings. This is required when running against remote servers where your current Windows account lacks administrative access. Note that this connects to the Windows computer, not the SQL Server instance itself. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance processed, with information about the Hide Instance setting change. Properties: ComputerName: The name of the computer where the registry change was made InstanceName: The SQL Server instance name (e.g., MSSQLSERVER, SQL2008R2SP2) SqlInstance: The full SQL Server instance identifier (computer\\instance format) HideInstance: Boolean indicating whether the Hide Instance setting was successfully enabled (true) or not (false) &nbsp;"
  },
  {
    "name": "Enable-DbaReplDistributor",
    "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.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Enable",
    "popular": false,
    "url": "/Enable-DbaReplDistributor",
    "popularityRank": 581,
    "synopsis": "Configures a SQL Server instance as a replication distributor with distribution database",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Enable-DbaReplDistributor View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures a SQL Server instance as a replication distributor with distribution database 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. Syntax Enable-DbaReplDistributor [-SqlInstance] [[-SqlCredential] ] [[-DistributionDatabase] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Enables distribution for the mssql1 instance PS C:\\> Enable-DbaReplDistributor -SqlInstance mssql1 Example 2: Enables distribution for the mssql1 instance and names the distribution database repDatabase PS C:\\> Enable-DbaReplDistributor -SqlInstance mssql1 -DistributionDatabase repDatabase Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DistributionDatabase Specifies the name of the distribution database that will be created to store replication metadata and transaction logs. This database holds subscription information, publication details, and queued transactions for distribution to subscribers. Defaults to 'distribution' if not specified, which is the standard convention for most replication configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | distribution | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Replication.ReplicationServer Returns one ReplicationServer object per instance configured as a distributor. The object shows the distributor configuration and replication server role details after enabling distribution. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) IsDistributor: Boolean indicating whether the instance is configured as a distributor IsPublisher: Boolean indicating whether the instance is configured as a publisher DistributionServer: Name of the distribution server DistributionDatabase: Name of the distribution database that stores replication metadata Additional properties available (from SMO ReplicationServer object): DistributionDatabases: Collection of distribution databases configured on the distributor DistributorSecurity: Distribution agent credentials and security settings LocalPublisher: Boolean indicating if this server can function as a local publisher PublisherIdentity: Identity of the publisher ReplicationDatabases: Collection of databases enabled for replication on this instance SubscriptionServers: List of subscription servers ThirdPartySubscribers: Information about non-SQL Server subscribers All properties from the base SMO ReplicationServer object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Enable-DbaReplPublishing",
    "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.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Enable",
    "popular": false,
    "url": "/Enable-DbaReplPublishing",
    "popularityRank": 599,
    "synopsis": "Configures a SQL Server instance as a replication publisher on an existing distributor.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Enable-DbaReplPublishing View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures a SQL Server instance as a replication publisher on an existing distributor. 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. Syntax Enable-DbaReplPublishing [-SqlInstance] [[-SqlCredential] ] [[-SnapshotShare] ] [[-PublisherSqlLogin] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Enables replication publishing for instance SqlBox1\\Instance2 using Windows Auth and the default... PS C:\\> Enable-DbaReplPublishing -SqlInstance SqlBox1\\Instance2 Enables replication publishing for instance SqlBox1\\Instance2 using Windows Auth and the default InstallDataDirectory\\ReplData as the snapshot folder Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SnapshotShare Specifies the network share path where replication snapshot files will be stored and accessed by subscribers. Use this when you need snapshot files in a specific location for network access or storage requirements. Defaults to InstallDataDirectory\\ReplData if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PublisherSqlLogin SQL Server login credentials to use for publisher security authentication instead of Windows Authentication. Use this when the distributor and publisher are in different domains or when Windows Authentication is not available. Windows Authentication is used by default and is the recommended method for security. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Replication.ReplicationServer Returns one ReplicationServer object per instance specified, representing the publisher configuration. The object is refreshed after the publishing configuration is created, reflecting the updated replication state. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) IsDistributor: Boolean indicating whether this instance is configured as a distributor IsPublisher: Boolean indicating whether this instance is configured as a publisher (should be True after this command completes) DistributionServer: The name of the server configured as the distributor DistributionDatabase: The name of the distribution database Additional properties available (from SMO ReplicationServer object): DistributionDatabases: Collection of distribution databases configured on the instance PublisherConnections: Collection of publishers configured on the distributor Distributors: Collection of distributors configured on this instance RegisteredSubscribers: Collection of registered subscribers Publishers: Collection of publishers configured on the distributor All properties from the base SMO ReplicationServer object are accessible through Select-Object *. &nbsp;"
  },
  {
    "name": "Enable-DbaStartupProcedure",
    "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's Startup property using SMO, which is equivalent to running sp_procoption with @OptionValue = 'on'.\nReturns detailed information about each procedure processed, including success status and any error conditions encountered.",
    "category": "Utilities",
    "tags": [
      "procedure",
      "startup",
      "startupprocedure"
    ],
    "verb": "Enable",
    "popular": false,
    "url": "/Enable-DbaStartupProcedure",
    "popularityRank": 550,
    "synopsis": "Configures stored procedures in the master database to execute automatically when SQL Server service starts",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Enable-DbaStartupProcedure View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures stored procedures in the master database to execute automatically when SQL Server service starts 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. This is essential for DBAs who need to ensure critical maintenance procedures, monitoring setup, or custom configurations are applied consistently every time the instance starts. The function modifies the procedure's Startup property using SMO, which is equivalent to running sp_procoption with @OptionValue = 'on'. Returns detailed information about each procedure processed, including success status and any error conditions encountered. Syntax Enable-DbaStartupProcedure [-SqlInstance] [[-SqlCredential] ] [[-StartupProcedure] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Attempts to set the procedure &#39;[dbo].[StartUpProc1]&#39; in the master database of SqlBox1\\Instance2 for... PS C:\\> Enable-DbaStartupProcedure -SqlInstance SqlBox1\\Instance2 -StartupProcedure '[dbo].[StartUpProc1]' Attempts to set the procedure '[dbo].[StartUpProc1]' in the master database of SqlBox1\\Instance2 for automatic execution when the instance is started. Example 2: Attempts to set the procedure &#39;[dbo].[StartUpProc1]&#39; in the master database of winserver\\sqlexpress and... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Enable-DbaStartupProcedure -SqlInstance winserver\\sqlexpress, sql2016 -SqlCredential $cred -StartupProcedure '[dbo].[StartUpProc1]' Attempts to set the procedure '[dbo].[StartUpProc1]' in the master database of winserver\\sqlexpress and sql2016 for automatic execution when the instance is started. Connects using sqladmin credential Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartupProcedure Specifies the stored procedure(s) in the master database to enable for automatic startup execution. Accepts schema-qualified names like '[dbo].[MyStartupProc]' or simple names. Use this when you need specific procedures to run automatically after SQL Server service restarts, such as initialization scripts, monitoring setup, or custom configuration procedures. Multiple procedures can be specified as an array to enable several startup procedures in a single operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.StoredProcedure Returns one StoredProcedure object per procedure that was processed, with the Startup property updated and additional status properties added. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database containing the stored procedure (always 'master') Schema: The schema containing the stored procedure Name: The name of the stored procedure Startup: Boolean indicating if the procedure will run at SQL Server startup (always $true after successful enable) Action: The action performed ('Enable') Status: Boolean indicating if the enable operation succeeded ($true for success, $false for skipped or failed) Note: A string message describing the result ('Action Enable already performed', 'Enable succeeded', 'Enable skipped', or 'Enable failed') Additional properties available (from SMO StoredProcedure object): IsSystemObject: Boolean indicating if this is a system object CreateDate: DateTime when the procedure was created DateLastModified: DateTime when the procedure was last modified Text: The T-SQL source code of the stored procedure Parent: The Database object containing the procedure All properties from the base SMO StoredProcedure object are accessible via Select-Object *. &nbsp;"
  },
  {
    "name": "Enable-DbaTraceFlag",
    "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.",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "traceflag",
      "dbcc"
    ],
    "verb": "Enable",
    "popular": false,
    "url": "/Enable-DbaTraceFlag",
    "popularityRank": 302,
    "synopsis": "Enables one or more trace flags globally on SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Enable-DbaTraceFlag View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Enables one or more trace flags globally on SQL Server instances Description Activates trace flags at the global level using DBCC TRACEON, affecting all connections and sessions on the target SQL Server instances. Commonly used for troubleshooting performance issues, enabling specific SQL Server behaviors, or applying recommended trace flags for your environment. Changes take effect immediately but are lost after a SQL Server restart - use Set-DbaStartupParameter to make trace flags persistent across restarts. The function automatically checks for already-enabled trace flags to prevent duplicate operations. Syntax Enable-DbaTraceFlag [-SqlInstance] [[-SqlCredential] ] [-TraceFlag] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Enable the trace flag 3226 on SQL Server instance sql2016 PS C:\\> Enable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 3226 Example 2: Enable multiple trace flags on SQL Server instance sql2016 PS C:\\> Enable-DbaTraceFlag -SqlInstance sql2016 -TraceFlag 1117, 1118 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -TraceFlag Specifies one or more trace flag numbers to enable globally across all sessions on the SQL Server instance. Use specific trace flag numbers like 3226 (suppress backup log messages), 1117/1118 (tempdb optimization), or 4199 (query optimizer fixes). Multiple trace flags can be specified as an array to enable several flags in a single operation. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per trace flag operation, indicating the result of enabling each trace flag. Properties: SourceServer: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (service name) SqlInstance: The full SQL Server instance name (computer\\instance) TraceFlag: The trace flag number that was enabled or attempted Status: The operation status (Successful, Skipped, or Failed) Successful: Trace flag was successfully enabled Skipped: Trace flag was already enabled globally Failed: An error occurred while enabling the trace flag Notes: Additional information about the operation result or error message DateTime: Timestamp when the operation was executed &nbsp;"
  },
  {
    "name": "Expand-DbaDbLogFile",
    "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 -> 16384 -> 24576 ... 73728 -> 81920",
    "category": "Utilities",
    "tags": [
      "storage",
      "logfile"
    ],
    "verb": "Expand",
    "popular": false,
    "url": "/Expand-DbaDbLogFile",
    "popularityRank": 195,
    "synopsis": "Grows transaction log files using calculated increment sizes to prevent excessive Virtual Log File (VLF) fragmentation.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Expand-DbaDbLogFile View Source Claudio Silva (@ClaudioESSilva) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Grows transaction log files using calculated increment sizes to prevent excessive Virtual Log File (VLF) fragmentation. 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. Too 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. References: http://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/ http://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx http://www.brentozar.com/blitz/high-virtual-log-file-vlf-count/ In order to get rid of this fragmentation we need to grow the file taking the following into consideration: How many VLFs are created when we perform a grow operation or when an auto-grow is invoked? Note: In SQL Server 2014 this algorithm has changed (http://www.sqlskills.com/blogs/paul/important-change-vlf-creation-algorithm-sql-server-2014/) Attention: We are growing in MB instead of GB because of known issue prior to SQL 2012: More detail here: http://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx and http://connect.microsoft.com/SqlInstance/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately or https://connect.microsoft.com/SqlInstance/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb Understanding related problems: http://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/ http://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx http://www.brentozar.com/blitz/high-virtual-log-file-vlf-count/ Known bug before SQL Server 2012 http://www.sqlskills.com/BLOGS/PAUL/post/Bug-log-file-growth-broken-for-multiples-of-4GB.aspx http://connect.microsoft.com/SqlInstance/feedback/details/481594/log-growth-not-working-properly-with-specific-growth-sizes-vlfs-also-not-created-appropriately https://connect.microsoft.com/SqlInstance/feedback/details/357502/transaction-log-file-size-will-not-grow-exactly-4gb-when-filegrowth-4gb How it works? The transaction log will grow in chunks until it reaches the desired size. Example: 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 -> 16384 -> 24576 ... 73728 -> 81920 Syntax Expand-DbaDbLogFile [-SqlInstance] [[-SqlCredential] ] [-Database ] [[-ExcludeDatabase] ] [-TargetLogSize] [[-IncrementSize] ] [-TargetVlfCount ] [[-LogFileId] ] [-ExcludeDiskSpaceValidation] [-EnableException] [-WhatIf] [-Confirm] [ ] Expand-DbaDbLogFile [-SqlInstance] [[-SqlCredential] ] [-Database ] [[-ExcludeDatabase] ] [-TargetLogSize] [[-IncrementSize] ] [-TargetVlfCount ] [[-LogFileId] ] [-ShrinkLogFile] [-ShrinkSize] [[-BackupDirectory] ] [-ExcludeDiskSpaceValidation] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Grows the transaction log for database db1 on sqlcluster to 50000 MB and calculates the increment size PS C:\\> Expand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 50000 Example 2: Grows the transaction logs for databases db1 and db2 on sqlcluster to 1000MB and sets the growth increment to... PS C:\\> Expand-DbaDbLogFile -SqlInstance sqlcluster -Database db1, db2 -TargetLogSize 10000 -IncrementSize 200 Grows the transaction logs for databases db1 and db2 on sqlcluster to 1000MB and sets the growth increment to 200MB. Example 3: Grows the transaction log file with FileId 9 of the db1 database on sqlcluster instance to 10000MB PS C:\\> Expand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 10000 -LogFileId 9 Example 4: Grows the transaction log of the databases specified in the file &#39;D:\\DBs.txt&#39; on sqlcluster instance to... PS C:\\> Expand-DbaDbLogFile -SqlInstance sqlcluster -Database (Get-Content D:\\DBs.txt) -TargetLogSize 50000 Grows the transaction log of the databases specified in the file 'D:\\DBs.txt' on sqlcluster instance to 50000MB. Example 5: Grows the transaction logs for databases db1 and db2 on SQL server SQLInstance to 100MB, sets the incremental... PS C:\\> Expand-DbaDbLogFile -SqlInstance SqlInstance -Database db1,db2 -TargetLogSize 100 -IncrementSize 10 -ShrinkLogFile -ShrinkSize 10 -BackupDirectory R:\\MSSQL\\Backup Grows 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:\\MSSQL\\Backup for the required backups. Example 6: Grows the transaction log for database db1 on sqlcluster to 10000MB and automatically calculates an increment... PS C:\\> Expand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 10000 -TargetVlfCount 16 Grows the transaction log for database db1 on sqlcluster to 10000MB and automatically calculates an increment size that keeps the total VLF count at or below 16. Example 7: Shrinks the transaction log for db1 to 10MB, then re-grows it to 10000MB using an increment size calculated... PS C:\\> Expand-DbaDbLogFile -SqlInstance sqlcluster -Database db1 -TargetLogSize 10000 -ShrinkLogFile -ShrinkSize 10 -BackupDirectory R:\\MSSQL\\Backup -TargetVlfCount 8 Shrinks the transaction log for db1 to 10MB, then re-grows it to 10000MB using an increment size calculated to keep the final VLF count at or below 8. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -TargetLogSize Sets the final size you want the transaction log to reach, specified in megabytes. This 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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | 0 | -ShrinkLogFile Shrinks the transaction log to the ShrinkSize before expanding it to the target size. This 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 databases. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | False | -ShrinkSize Sets the intermediate size in megabytes to shrink the log file to before re-expanding. This should be small enough to remove VLF fragmentation but large enough to handle active transactions. Typical values are 10-100MB depending on transaction activity. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | 0 | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to expand transaction log files for. Accepts wildcards for pattern matching. If 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during the expansion process when processing all databases on an instance. Use this to exclude system databases, read-only databases, or databases with specific requirements from batch log file expansion operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncrementSize Controls the size of each growth operation in megabytes during the expansion process. If 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 intelligent defaults. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | -1 | -TargetVlfCount Sets the desired maximum number of Virtual Log Files (VLFs) after the expansion completes. When specified, the function calculates the optimal increment size to keep total VLFs at or below this value. If the current VLF count already meets or exceeds this target, a warning is issued and the database is skipped â€” use -ShrinkLogFile to first reduce the VLF count. If the target is mathematically impossible given the required growth, a warning is issued and the database is skipped. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | -1 | -LogFileId Targets a specific transaction log file by its file ID number when databases have multiple log files. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | -1 | -BackupDirectory Sets the directory path where transaction log backups will be created during the shrink process. Transaction log backups are required to shrink log files, so this directory must be accessible to the SQL Server service account. Defaults to the instance's default backup directory if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDiskSpaceValidation Skips the automatic disk space validation that normally ensures sufficient free space exists before expanding log files. Use this when you're confident about available disk space but PowerShell remoting isn't available to check drive capacity, or when working with network storage that may not report correctly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database processed containing the results of the log file expansion operation. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName) Database: The name of the database whose log file was expanded DatabaseID: The unique identifier of the database ID: The file ID of the transaction log file Name: The logical name of the transaction log file InitialSize: The size of the log file at the start of the operation (displayed as formatted size) CurrentSize: The size of the log file after expansion to target size (displayed as formatted size) InitialVLFCount: The number of Virtual Log Files (VLFs) before the expansion operation CurrentVLFCount: The number of Virtual Log Files (VLFs) after the expansion operation Additional properties available: LogFileCount: The total number of log files for the database (available with Select-Object ) All properties are accessible via Select-Object or by accessing individual properties on the returned object. &nbsp;"
  },
  {
    "name": "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't specified, the command will guess based on the datatype (binary/image) for the binary column and a match for \"name\" as the filename column.",
    "category": "Migration",
    "tags": [
      "migration",
      "backup",
      "export"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaBinaryFile",
    "popularityRank": 387,
    "synopsis": "Extracts binary data from SQL Server tables and writes it to physical files.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaBinaryFile View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Extracts binary data from SQL Server tables and writes it to physical files. 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. The 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. If specific filename and binary columns aren't specified, the command will guess based on the datatype (binary/image) for the binary column and a match for \"name\" as the filename column. Syntax Export-DbaBinaryFile [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Table] ] [[-Schema] ] [[-FileNameColumn] ] [[-BinaryColumn] ] [[-Path] ] [[-Query] ] [[-FilePath] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Exports all binary files from the test database on sqlcs to C:\\temp\\exports PS C:\\> Export-DbaBinaryFile -SqlInstance sqlcs -Database test -Path C:\\temp\\exports Exports all binary files from the test database on sqlcs to C:\\temp\\exports. Guesses the columns based on datatype and column name. Example 2: Exports all binary files from the photos table in the employees database on sqlcs to C:\\temp\\exports PS C:\\> Export-DbaBinaryFile -SqlInstance sqlcs -Database employees -Table photos -Path C:\\temp\\exports Exports 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. Example 3: Exports all binary files from the photos table in the employees database on sqlcs to C:\\temp\\exports PS C:\\> Export-DbaBinaryFile -SqlInstance sqlcs -Database employees -Table photos -FileNameColumn fname -BinaryColumn data -Path C:\\temp\\exports Exports 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. Example 4: &#39;Qualitee&#39;&quot; -FilePath C:\\temp\\PotatoQualitee.jpg Exports the binary file from the photos table in the... PS C:\\> Export-DbaBinaryFile -SqlInstance sqlcs -Database employees -Table photos -Query \"SELECT [FileName], [Data] FROM [employees].[dbo].[photos] WHERE FirstName = 'Potato' and LastName = 'Qualitee'\" -FilePath C:\\temp\\PotatoQualitee.jpg Exports 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. Example 5: Allows you to pick tables with columns to be exported by Export-DbaBinaryFile PS C:\\> Get-DbaBinaryFileTable -SqlInstance sqlcs -Database test | Out-GridView -Passthru | Export-DbaBinaryFile -Path C:\\temp Optional Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for tables containing binary data. Accepts wildcards for pattern matching. Use this to limit the export scope when you only need files from specific databases instead of scanning the entire instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Specifies the table(s) containing binary data to export. Supports three-part naming (database.schema.table) and wildcards. Use this when you know exactly which tables contain your stored files, such as document management or attachment tables. Wrap table names with special characters in square brackets, like [Documents.Archive] for tables with periods in the name. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Limits the search to tables within specific schemas. Useful in databases with multiple schemas for organizing different application areas. Common schemas include dbo, app, archive, or custom business schemas where file storage tables are organized. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileNameColumn Identifies which column contains the original filename or file identifier for the stored binary data. The function auto-detects columns with 'name' in the column name, but specify this when your filename column has a different naming pattern like 'DocumentName' or 'FileID'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BinaryColumn Identifies which column contains the actual binary file data to export. The function auto-detects binary, varbinary, and image columns, but specify this when you have multiple binary columns or non-standard column names like 'DocumentData' or 'FileContent'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Sets the target directory where exported files will be saved using their original filenames from the database. The directory will be created if it doesn't exist. Use this when exporting multiple files and want to preserve their original names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Query Provides a custom SQL query to retrieve specific files based on complex criteria or joins. Use this when you need to filter files by metadata, join with other tables, or when the auto-detection doesn't work with your table structure. Your query must return exactly two columns: filename and binary data in that order. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FilePath Specifies the exact path and filename for a single exported file, overriding the stored filename. Use this when exporting one specific file or when you need to rename the output file to a standardized naming convention. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts table objects from the pipeline, typically from Get-DbaDbTable or Get-DbaBinaryFileTable. Use this for advanced scenarios where you need to pre-filter or analyze tables before exporting their binary content. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.IO.FileInfo Returns one FileInfo object for each binary file successfully exported to the filesystem. Properties: FullName: The complete path to the exported file Name: The filename of the exported file (without path) DirectoryName: The directory path where the file was exported Directory: DirectoryInfo object for the parent directory Extension: The file extension (e.g., .jpg, .pdf) Length: Size of the file in bytes CreationTime: When the file was created on disk LastWriteTime: When the file was last written Attributes: File attributes (Archive, ReadOnly, etc.) Files 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. &nbsp;"
  },
  {
    "name": "Export-DbaCredential",
    "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.",
    "category": "Migration",
    "tags": [
      "credential"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaCredential",
    "popularityRank": 107,
    "synopsis": "Exports SQL Server credentials to executable T-SQL CREATE CREDENTIAL scripts",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Export-DbaCredential View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports SQL Server credentials to executable T-SQL CREATE CREDENTIAL scripts 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. The 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. Use the ExcludePassword parameter to export credential definitions without sensitive data for documentation or security-conscious scenarios. Syntax Export-DbaCredential [[-SqlInstance] ] [[-SqlCredential] ] [[-Credential] ] [[-Path] ] [[-FilePath] ] [[-Identity] ] [-ExcludePassword] [-Append] [-Passthru] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports credentials, including passwords, from sql2017 to the file C:\\temp\\cred.sql PS C:\\> Export-DbaCredential -SqlInstance sql2017 -Path C:\\temp\\cred.sql Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential) Only used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory where the exported T-SQL script file will be saved. Defaults to the configured DbatoolsExport path. Use this when you want to control where credential scripts are stored for organization or compliance requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Specifies the complete file path and name for the exported T-SQL script. Overrides the Path parameter when specified. Use this when you need precise control over the output file name and location, especially for automated processes. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -Identity Specifies which credential names to export by filtering on the Identity property. Accepts an array of credential names. Use this to export specific credentials instead of all credentials, particularly useful when migrating only certain application or service accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludePassword Exports credential definitions without the actual password values, replacing them with placeholder text. Use this for documentation purposes or when you need credential structure without sensitive data for security reviews. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Append Adds the exported credential scripts to an existing file instead of overwriting it. Use this when consolidating credentials from multiple instances into a single deployment script. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Passthru Returns the generated T-SQL script to the PowerShell pipeline instead of saving to file. Use this to capture the script in a variable, pipe to other commands, or display directly in the console. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns 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 exported. Properties: FullName: The complete path to the exported script file Name: The name of the exported script file Length: The size of the exported file in bytes LastWriteTime: The date and time the file was created or last modified Directory: The directory containing the exported file &nbsp;"
  },
  {
    "name": "Export-DbaCsv",
    "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.",
    "category": "Migration",
    "tags": [
      "export",
      "csv",
      "data",
      "compression"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaCsv",
    "popularityRank": 0,
    "synopsis": "Exports SQL Server query results or table data to CSV files with optional compression.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaCsv View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports SQL Server query results or table data to CSV files with optional compression. Description Export-DbaCsv provides high-performance CSV export capabilities with support for multiple compression formats including GZip, Deflate, Brotli, and ZLib. The function can export data from SQL queries, tables, or piped objects to CSV files with configurable formatting options. Supports various output formats including custom delimiters, quoting behaviors, date formatting, and encoding options. Compression can significantly reduce file sizes for large exports, making it ideal for archiving, data transfer, or storage-constrained environments. Perfect for ETL processes, data exports, reporting, and creating portable data files from SQL Server. Syntax Export-DbaCsv [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Query] ] [[-Table] ] [[-InputObject] ] [-Path] [[-Delimiter] ] [-NoHeader] [[-Quote] ] [[-QuotingBehavior] ] [[-Encoding] ] [[-NullValue] ] [[-DateTimeFormat] ] [-UseUtc] [[-CompressionType] ] [[-CompressionLevel] ] [-Append] [-NoClobber] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Exports all customers from the Northwind database to a CSV file PS C:\\> Export-DbaCsv -SqlInstance sql001 -Database Northwind -Query \"SELECT FROM Customers\" -Path C:\\temp\\customers.csv Example 2: Exports the Orders table to a GZip-compressed CSV file PS C:\\> Export-DbaCsv -SqlInstance sql001 -Database Northwind -Table \"dbo.Orders\" -Path C:\\temp\\orders.csv.gz -CompressionType GZip Example 3: Pipes table data from Get-DbaDbTable to export as CSV PS C:\\> Get-DbaDbTable -SqlInstance sql001 -Database tempdb -Table \"#MyTempTable\" | Export-DbaCsv -Path C:\\temp\\data.csv Example 4: Exports query results with maximum GZip compression for archival purposes PS C:\\> Export-DbaCsv -SqlInstance sql001 -Database Sales -Query \"SELECT FROM BigTable\" -Path C:\\archive\\data.csv.gz -CompressionType GZip -CompressionLevel SmallestSize Example 5: Exports to a tab-delimited file with all fields quoted PS C:\\> Export-DbaCsv -SqlInstance sql001 -Database HR -Table Employees -Path C:\\temp\\employees.csv -Delimiter \"`t\" -QuotingBehavior Always Example 6: Exports query results with custom date formatting PS C:\\> $results = Invoke-DbaQuery -SqlInstance sql001 -Database master -Query \"SELECT FROM sys.databases\" PS C:\\> $results | Export-DbaCsv -Path C:\\temp\\databases.csv -DateTimeFormat \"yyyy-MM-dd\" Example 7: Exports with Unicode encoding for international character support PS C:\\> Export-DbaCsv -SqlInstance sql001 -Database Sales -Query \"SELECT FROM Orders WHERE Region = 'EMEA'\" -Path C:\\temp\\emea.csv -Encoding Unicode Required Parameters -Path The output file path for the CSV. If the path ends with .gz, .br, .deflate, or .zlib, the appropriate compression will be applied automatically unless -CompressionType is specified. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database to query. Required when using -Query or -Table parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Query The T-SQL query to execute. Results will be exported to CSV. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table The name of the table to export. Can include schema (e.g., \"dbo.Customers\"). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts piped objects to export. Can be used with results from other dbatools commands or any PowerShell objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Delimiter Sets the field separator for the CSV output. Defaults to comma. Common values include comma (,), tab (`t), pipe (|), or semicolon (;). Multi-character delimiters are supported (e.g., \"::\", \"||\"). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | , | -NoHeader Suppresses the header row in the output. Use this when appending to existing files or when the consuming application doesn't expect headers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Quote Specifies the character used to quote fields. Defaults to double-quote (\"). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \" | -QuotingBehavior Controls when field values are quoted. AsNeeded: Quote only when necessary (contains delimiter, quote, or newline). This is the default. Always: Always quote all fields. Never: Never quote fields (may produce invalid CSV with some data). NonNumeric: Quote only non-numeric fields. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | AsNeeded | | Accepted Values | AsNeeded,Always,Never,NonNumeric | -Encoding The text encoding for the output file. Defaults to UTF8. Valid values: ASCII, BigEndianUnicode, Unicode, UTF7, UTF8, UTF32. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UTF8 | | Accepted Values | ASCII,BigEndianUnicode,Unicode,UTF7,UTF8,UTF32 | -NullValue The string to use for NULL values in the output. Defaults to empty string. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DateTimeFormat The format string for DateTime values. Defaults to ISO 8601 format (yyyy-MM-dd HH:mm:ss.fff). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | yyyy-MM-dd HH:mm:ss.fff | -UseUtc Converts DateTime values to UTC before formatting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CompressionType The type of compression to apply to the output file. None: No compression (default) GZip: GZip compression (.gz) Deflate: Deflate compression Brotli: Brotli compression (.br) - .NET 8+ only ZLib: ZLib compression - .NET 8+ only | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | None | | Accepted Values | None,GZip,Deflate,Brotli,ZLib | -CompressionLevel The compression level to use. Defaults to Optimal. Fastest: Compress as fast as possible, even if the resulting file is not optimally compressed. Optimal: Balance between compression speed and file size. SmallestSize: Compress as much as possible, even if it takes longer. NoCompression: No compression. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Optimal | | Accepted Values | Fastest,Optimal,SmallestSize,NoCompression | -Append Appends to an existing file instead of overwriting. Headers are automatically suppressed when appending. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoClobber Prevents overwriting an existing file. Returns an error if the file already exists. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns a single object containing export summary information only when rows are successfully exported. If no rows are exported, no output is returned. Properties: Path: The full file system path where the CSV file was written (string) RowsExported: The total number of rows written to the CSV file (int) FileSizeBytes: The size of the output file in bytes (long) FileSizeMB: The size of the output file in megabytes, rounded to 2 decimal places (double) CompressionType: The compression format applied to the file - None, GZip, Deflate, Brotli, or ZLib (string) Elapsed: A TimeSpan object representing the total time taken to export all data (TimeSpan) RowsPerSecond: The average export throughput calculated as rows written per second (double) &nbsp;"
  },
  {
    "name": "Export-DbaDacPackage",
    "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",
    "category": "Migration",
    "tags": [
      "dacpac",
      "deployment"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaDacPackage",
    "popularityRank": 128,
    "synopsis": "Exports DACPAC or BACPAC packages from SQL Server databases using the DacFx framework",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaDacPackage View Source Richie lee (@richiebzzzt) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports DACPAC or BACPAC packages from SQL Server databases using the DacFx framework 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. Perfect 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. Uses Microsoft DacFx API from dbatools.library. Note that extraction can fail with three-part references to external databases or complex cross-database dependencies. For help with the extract action parameters and properties, refer to https://learn.microsoft.com/en-us/sql/tools/sqlpackage/sqlpackage-extract Syntax Export-DbaDacPackage -SqlInstance [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-AllUserDatabases] [-Path ] [-FilePath ] [-DacOption ] [-Type ] [-Table ] [-EnableException] [ ] Export-DbaDacPackage -SqlInstance [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-AllUserDatabases] [-Path ] [-FilePath ] [-ExtendedParameters ] [-ExtendedProperties ] [-Type ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports the dacpac for SharePoint_Config on sql2016 to C:\\SharePoint_Config.dacpac PS C:\\> Export-DbaDacPackage -SqlInstance sql2016 -Database SharePoint_Config -FilePath C:\\SharePoint_Config.dacpac Example 2: Uses DacOption object to set the CommandTimeout to 0 then extracts the dacpac for DB1 on sql2016 to... PS C:\\> $options = New-DbaDacOption -Type Dacpac -Action Export PS C:\\> $options.ExtractAllTableData = $true PS C:\\> $options.CommandTimeout = 0 PS C:\\> Export-DbaDacPackage -SqlInstance sql2016 -Database DB1 -DacOption $options Uses 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 all 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. Example 3: Exports dacpac packages for all USER databases, excluding &quot;DBMaintenance&quot; &amp; &quot;DBMonitoring&quot;, on sql2016 and... PS C:\\> Export-DbaDacPackage -SqlInstance sql2016 -AllUserDatabases -ExcludeDatabase \"DBMaintenance\",\"DBMonitoring\" -Path \"C:\\temp\" Exports dacpac packages for all USER databases, excluding \"DBMaintenance\" & \"DBMonitoring\", on sql2016 and saves them to C:\\temp. The generated filename(s) will contain the server name, database name, and the current timestamp in the \"%Y%m%d%H%M%S\" format. Example 4: Using extended parameters to over-write the files and performs the extraction in quiet mode to... PS C:\\> $moreparams = \"/OverwriteFiles:$true /Quiet:$true\" PS C:\\> Export-DbaDacPackage -SqlInstance sql2016 -Database SharePoint_Config -Path C:\\temp -ExtendedParameters $moreparams Using 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 instead 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. Required Parameters -SqlInstance The target SQL Server instance or instances. Must be SQL Server 2008 R2 or higher (DAC Framework minimum version 10.50). | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Only SQL authentication is supported. When not specified, uses Trusted Authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to export as DACPAC or BACPAC packages. Accepts multiple database names and supports wildcards. Use this to target specific databases instead of processing all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during export operations. Works with both Database and AllUserDatabases parameters. Use this to exclude system databases, maintenance databases, or any databases you don't want to package. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllUserDatabases Exports packages for all user databases on the instance, automatically excluding system databases. Use this for bulk operations when you want to create deployment packages for every application database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Path Specifies the directory where DACPAC or BACPAC files will be saved. Defaults to the configured DbatoolsExport path. Use this when you want to organize exports in a specific location or when working with multiple databases that need consistent file placement. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Specifies the complete file path including filename for the export package. Overrides both Path and automatic file naming. Use this when you need a specific filename or when exporting a single database to a predetermined location. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -DacOption Configures advanced export settings using a DacExtractOptions or DacExportOptions object created by New-DbaDacOption. Use this to control extraction behavior like command timeouts, table data inclusion, or specific schema elements to include or exclude. | Property | Value | | --- | --- | | Alias | ExtractOptions,ExportOptions,DacExtractOptions,DacExportOptions,Options,Option | | Required | False | | Pipeline | false | | Default Value | | -ExtendedParameters Passes additional command-line parameters directly to SqlPackage.exe for advanced scenarios (e.g., '/OverwriteFiles:true /Quiet:true'). Use this when you need SqlPackage options not available through DacOption or when integrating with existing SqlPackage workflows. Note: This parameter requires SqlPackage.exe to be installed via Install-DbaSqlPackage or locally. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExtendedProperties Passes additional property settings directly to SqlPackage.exe for fine-tuned control over extraction behavior. Use this when you need to set specific SqlPackage properties that aren't exposed through the standard DacOption parameter. Note: This parameter requires SqlPackage.exe to be installed via Install-DbaSqlPackage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies the package type to create: Dacpac (schema-only) or Bacpac (schema and data). Defaults to Dacpac. Use Dacpac for version control and schema deployments, or Bacpac when you need to include table data for migrations or testing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Dacpac | | Accepted Values | Dacpac,Bacpac | -Table Specifies which tables to include in the export package. Provide as schema.table format (e.g., 'dbo.Users', 'Sales.Orders'). Use this when you only need specific tables rather than the entire database, such as for partial deployments or data subsets. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database exported as a DACPAC or BACPAC package. Default display properties (via Select-DefaultView): SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database that was exported Path: The full file path where the package file was saved Elapsed: The elapsed time for the export operation (formatted timespan) Result: The output from the extraction/export operation, typically containing status messages from DacServices or SqlPackage.exe Additional properties available: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name &nbsp;"
  },
  {
    "name": "Export-DbaDbRole",
    "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's post \"Fully Script out a MSSQL Database Role\"\nReference:  https://dbaeyes.wordpress.com/2013/04/19/fully-script-out-a-mssql-database-role/",
    "category": "Migration",
    "tags": [
      "export",
      "role"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaDbRole",
    "popularityRank": 122,
    "synopsis": "Generates T-SQL scripts for database role definitions with their complete permission sets and schema ownership",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaDbRole View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates T-SQL scripts for database role definitions with their complete permission sets and schema ownership 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. This command is based off of John Eisbrener's post \"Fully Script out a MSSQL Database Role\" Reference: https://dbaeyes.wordpress.com/2013/04/19/fully-script-out-a-mssql-database-role/ Syntax Export-DbaDbRole [[-SqlInstance] ] [[-SqlCredential] ] [[-InputObject] ] [[-ScriptingOptionsObject] ] [[-Database] ] [[-Role] ] [[-ExcludeRole] ] [-ExcludeFixedRole] [-IncludeRoleMember] [[-Path] ] [[-FilePath] ] [-Passthru] [[-BatchSeparator] ] [-NoClobber] [-Append] [-NoPrefix] [[-Encoding] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports all the Database Roles for SQL Server &quot;sql2005&quot; and writes them to the file... PS C:\\> Export-DbaDbRole -SqlInstance sql2005 -Path C:\\temp Exports all the Database Roles for SQL Server \"sql2005\" and writes them to the file \"C:\\temp\\sql2005-logins.sql\" Example 2: Authenticates to sqlserver2014a using SQL Authentication PS C:\\> Export-DbaDbRole -SqlInstance sqlserver2014a -ExcludeRole realcajun -SqlCredential $scred -Path C:\\temp\\roles.sql -Append Authenticates 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. Example 3: Exports ONLY roles netnerds and realcajun FROM sqlserver2014a to the file C:\\temp\\roles.sql PS C:\\> Export-DbaDbRole -SqlInstance sqlserver2014a -Role realcajun,netnerds -Path C:\\temp\\roles.sql Example 4: Exports ONLY roles netnerds and realcajun FROM sqlserver2014a with the permissions on databases HR and... PS C:\\> Export-DbaDbRole -SqlInstance sqlserver2014a -Role realcajun,netnerds -Database HR, Accounting Exports ONLY roles netnerds and realcajun FROM sqlserver2014a with the permissions on databases HR and Accounting Example 5: Exports ONLY roles FROM sqlserver2014a with permissions on databases HR and Accounting PS C:\\> Get-DbaDatabase -SqlInstance sqlserver2014a -Database HR, Accounting | Export-DbaDbRole Example 6: Sets the BatchSeparator configuration to null, removing the default &quot;GO&quot; value PS C:\\> Set-DbatoolsConfig -FullName formatting.batchseparator -Value $null PS C:\\> Export-DbaDbRole -SqlInstance sqlserver2008 -Role realcajun,netnerds -Path C:\\temp\\roles.sql Sets the BatchSeparator configuration to null, removing the default \"GO\" value. Exports ONLY roles netnerds and realcajun FROM sqlserver2008 server, to the C:\\temp\\roles.sql file, without the \"GO\" batch separator. Example 7: Exports ONLY roles netnerds and realcajun FROM sqlserver2008 server, to the C:\\temp\\roles.sql file, without... PS C:\\> Export-DbaDbRole -SqlInstance sqlserver2008 -Role realcajun,netnerds -Path C:\\temp\\roles.sql -BatchSeparator $null Exports ONLY roles netnerds and realcajun FROM sqlserver2008 server, to the C:\\temp\\roles.sql file, without the \"GO\" batch separator. Example 8: Exports role realcajun for all databases on sqlserver2008 PS C:\\> Get-DbaDatabase -SqlInstance sqlserver2008 | Export-DbaDbRole -Role realcajun Example 9: Exports all roles from all databases on sqlserver2008, excludes all roles marked as as FixedRole PS C:\\> Get-DbaDbRole -SqlInstance sqlserver2008 -ExcludeFixedRole | Export-DbaDbRole Optional Parameters -SqlInstance The target SQL Server instance or instances. SQL Server 2005 and above supported. Any databases in CompatibilityLevel 80 or lower will be skipped | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database role objects from Get-DbaDbRole, database objects from Get-DbaDatabase, or server instances. Use this when you need to export roles from a filtered set of databases or specific role objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -ScriptingOptionsObject Controls T-SQL script generation options using an SMO ScriptingOptions object from New-DbaScriptingOption. Customize output format, object naming, and scripting behavior to match your deployment requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to export role definitions from. Accepts wildcards for pattern matching. Use this when you need role scripts for specific databases rather than processing all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Role Specifies which database roles to export. Accepts wildcards and multiple role names. Use this when you need scripts for specific custom roles rather than all roles in the database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeRole Excludes specific database roles from the export operation. Accepts wildcards and multiple role names. Useful when you want most roles except certain application-specific or sensitive roles. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeFixedRole Excludes built-in SQL Server fixed database roles like db_datareader, db_datawriter, and db_owner. Use this when you only want to export custom application roles and not the standard SQL Server roles. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeRoleMember Includes ALTER ROLE statements to add existing members back to the roles. Use this when you need to recreate both the role definitions and their current membership assignments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Path Specifies the output directory for generated SQL script files. Defaults to the configured DbatoolsExport path. Each database gets its own script file named with the instance and database name for organization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Specifies the exact file path for the output script. Auto-generates filename based on instance and database if not provided. Only use this when processing a single database, as multiple databases would overwrite the same file. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -Passthru Outputs the T-SQL script to the console instead of writing to files. Use this to review the generated scripts before saving them or to pipe output to other commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BatchSeparator Sets the batch separator between T-SQL statements in the output script. Defaults to \"GO\" from configuration. Change this when deploying to tools that require different batch separators or set to null to remove separators entirely. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Formatting.BatchSeparator') | -NoClobber Prevents overwriting existing files at the target location. The operation will fail if files already exist. Use this as a safety measure when you want to avoid accidentally replacing existing role scripts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Append Adds the generated T-SQL scripts to the end of existing files rather than overwriting them. Use this to combine role scripts from multiple operations into a single deployment file. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoPrefix Removes the header comment block that includes creation timestamp, user, and source information. Use this when you need clean T-SQL scripts without metadata comments for automated deployments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Encoding Sets the character encoding for output files. Defaults to UTF8 for broad compatibility. Change to Unicode when working with international character sets in role names or comments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UTF8 | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String (when -Passthru is specified or no -Path/-FilePath is provided) Returns the generated T-SQL script as a string containing all role definitions, permission statements, and optionally role membership commands. System.IO.FileInfo (when -Path or -FilePath is specified) Returns file information objects for each created script file. Multiple databases result in multiple FileInfo objects. &nbsp;"
  },
  {
    "name": "Export-DbaDbTableData",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "backup",
      "export"
    ],
    "verb": "Export",
    "popular": true,
    "url": "/Export-DbaDbTableData",
    "popularityRank": 40,
    "synopsis": "Generates INSERT statements from table data for migration and deployment scripts",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaDbTableData View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates INSERT statements from table data for migration and deployment scripts 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. Syntax Export-DbaDbTableData [-InputObject] [[-Path] ] [[-FilePath] ] [[-Encoding] ] [[-BatchSeparator] ] [-NoPrefix] [-Passthru] [-NoClobber] [-Append] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Exports data from EmployeePayHistory in AdventureWorks2014 in sql2017 PS C:\\> Get-DbaDbTable -SqlInstance sql2017 -Database AdventureWorks2014 -Table EmployeePayHistory | Export-DbaDbTableData Example 2: Exports data from EmployeePayHistory in AdventureWorks2014 in sql2017 using a trusted connection - Will... PS C:\\> Get-DbaDbTable -SqlInstance sql2017 -Database AdventureWorks2014 -Table EmployeePayHistory | Export-DbaDbTableData -FilePath C:\\temp\\export.sql -Append Exports 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 Script does not include Batch Separator and will not compile Example 3: Exports only data from &#39;dbo.Table1&#39; and &#39;dbo.Table2&#39; in MyDatabase to C:\\temp\\export.sql and uses the SQL... PS C:\\> Get-DbaDbTable -SqlInstance sql2016 -Database MyDatabase -Table 'dbo.Table1', 'dbo.Table2' -SqlCredential sqladmin | Export-DbaDbTableData -FilePath C:\\temp\\export.sql -Append Exports only data from 'dbo.Table1' and 'dbo.Table2' in MyDatabase to C:\\temp\\export.sql and uses the SQL login \"sqladmin\" to login to sql2016 Required Parameters -InputObject Accepts table objects from Get-DbaDbTable through the pipeline. Use this to process specific tables you've already identified rather than specifying table names again. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Path Sets the directory where output files will be created when not using FilePath. Defaults to the dbatools export directory configured in module settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Specifies the complete path and filename for the output SQL script. Use this when you need the INSERT statements saved to a specific file location for deployment or version control. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -Encoding Controls the character encoding of the exported SQL file. Defaults to UTF8. Use UTF8 for compatibility with most modern SQL tools, or ASCII for older systems that don't support Unicode. Valid values are: ASCII: Uses the encoding for the ASCII (7-bit) character set. BigEndianUnicode: Encodes in UTF-16 format using the big-endian byte order. Byte: Encodes a set of characters into a sequence of bytes. String: Uses the encoding type for a string. Unicode: Encodes in UTF-16 format using the little-endian byte order. UTF7: Encodes in UTF-7 format. UTF8: Encodes in UTF-8 format. Unknown: The encoding type is unknown or invalid. The data can be treated as binary. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UTF8 | | Accepted Values | ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown | -BatchSeparator Adds batch separators (like GO) between INSERT statements in the output script. Use this when creating deployment scripts that will be executed in SQL Server Management Studio or sqlcmd. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoPrefix Excludes the USE database statement and other prefixes from the generated script. Use this when combining output with other scripts or when the database context is already established. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Passthru Displays the generated INSERT statements in the PowerShell console in addition to file output. Useful for reviewing the script content before execution or when piping to other commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoClobber Prevents overwriting existing files at the specified FilePath. Use this as a safety measure to avoid accidentally replacing important deployment scripts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Append Adds the INSERT statements to the end of an existing file instead of creating a new one. Useful when building comprehensive deployment scripts from multiple table exports or combining with other SQL operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.IO.FileInfo When used without -Passthru, returns file information objects for the created SQL script files. Properties: Name: The filename of the generated SQL script FullName: The complete file path to the generated script Directory: The directory containing the script file Length: The size of the file in bytes LastWriteTime: When the file was last modified CreationTime: When the file was created System.String (when -Passthru is specified) Returns 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 separation with GO or other batch terminators. &nbsp;"
  },
  {
    "name": "Export-DbaDiagnosticQuery",
    "description": "Processes the PowerShell objects returned by Glenn Berry's 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.",
    "category": "Migration",
    "tags": [
      "community",
      "glennberry"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaDiagnosticQuery",
    "popularityRank": 164,
    "synopsis": "Converts diagnostic query results from Invoke-DbaDiagnosticQuery into CSV or Excel files",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaDiagnosticQuery View Source Andre Kamman (@AndreKamman), clouddba.io Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Converts diagnostic query results from Invoke-DbaDiagnosticQuery into CSV or Excel files Description Processes the PowerShell objects returned by Glenn Berry's diagnostic queries and saves them as CSV files or Excel worksheets for analysis, reporting, and sharing with vendors. Automatically extracts execution plans as separate .sqlplan files and query text as .sql files, which can be opened directly in SQL Server Management Studio. This 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. CSV output creates individual files per query while Excel output consolidates results into worksheets within a single workbook. Syntax Export-DbaDiagnosticQuery [-InputObject] [[-ConvertTo] ] [[-Path] ] [[-Suffix] ] [-NoPlanExport] [-NoQueryExport] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Converts output from Invoke-DbaDiagnosticQuery to multiple CSV files PS C:\\> Invoke-DbaDiagnosticQuery -SqlInstance sql2016 | Export-DbaDiagnosticQuery -Path c:\\temp Example 2: Converts output from Invoke-DbaDiagnosticQuery to Excel worksheet(s) in the Documents folder PS C:\\> $output = Invoke-DbaDiagnosticQuery -SqlInstance sql2016 PS C:\\> Export-DbaDiagnosticQuery -InputObject $output -ConvertTo Excel Required Parameters -InputObject Specifies the diagnostic query results from Invoke-DbaDiagnosticQuery to convert to files. Accepts pipeline input directly from Invoke-DbaDiagnosticQuery or stored results in a variable. Each object contains query results, execution plans, and metadata needed for file export. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -ConvertTo Specifies the output format for diagnostic query results. Valid choices are Excel and CSV with CSV as the default. Use Excel when you need consolidated results in worksheets for easier analysis and sharing with non-technical stakeholders. Choose CSV when you need individual files per query for automated processing or importing into other tools. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Csv | | Accepted Values | Excel,Csv | -Path Specifies the directory path where exported files will be created. Must be a directory, not a filename. Defaults to the configured dbatools export path if not specified. The function creates separate files for each diagnostic query result within this directory. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -Suffix Specifies a suffix to append to all generated filenames for uniqueness. Defaults to a timestamp in yyyyMMddHHmmssms format. Use this when running exports multiple times to prevent filename conflicts or when you need custom file identification. Helps organize multiple export runs when tracking performance trends over time. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \"$(Get-Date -format 'yyyyMMddHHmmssms')\" | -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. Use this switch when you only need the query results data and not the execution plan details. Reduces file clutter when performing bulk exports where execution plans are not required for analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoQueryExport Suppresses the export of query text as separate .sql files. These files contain the actual SQL statements from the diagnostic queries. Use this switch when you only need the result data and not the source query text. Helpful when exporting large result sets where the query text is not needed for your analysis workflow. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns 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. For each diagnostic query result processed, the function may return: CSV file: When ConvertTo is \"Csv\" (one file per diagnostic query or one per database if DatabaseSpecific) Excel file: When ConvertTo is \"Excel\" (one workbook per instance or per database if DatabaseSpecific) .sqlplan file: Query execution plan files extracted from result columns (unless NoPlanExport is specified) .sql file: Query text files extracted from result columns (unless NoQueryExport is specified) Each System.IO.FileInfo object contains standard file properties including: Name: The filename (e.g., \"SERVERNAME-DQ-20231215120530ms.xlsx\") FullName: The complete path to the file Directory: The directory where the file is located Length: File size in bytes CreationTime: When the file was created LastWriteTime: When the file was last modified &nbsp;"
  },
  {
    "name": "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.",
    "category": "Migration",
    "tags": [
      "diagnostic",
      "performance",
      "executionplan"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaExecutionPlan",
    "popularityRank": 385,
    "synopsis": "Extracts execution plans from plan cache and saves them as .sqlplan files for analysis",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaExecutionPlan View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Extracts execution plans from plan cache and saves them as .sqlplan files for analysis 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. Thanks to https://www.simple-talk.com/sql/t-sql-programming/dmvs-for-query-plan-metadata/ and http://www.scarydba.com/2017/02/13/export-plans-cache-sqlplan-file/ for the idea and query. Syntax Export-DbaExecutionPlan [-Database ] [-ExcludeDatabase ] [-EnableException] [-WhatIf] [-Confirm] [ ] Export-DbaExecutionPlan -SqlInstance [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-Path ] [-SinceCreation ] [-SinceLastExecution ] [-EnableException] [-WhatIf] [-Confirm] [ ] Export-DbaExecutionPlan [-Database ] [-ExcludeDatabase ] [-Path ] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Exports all execution plans for sqlserver2014a PS C:\\> Export-DbaExecutionPlan -SqlInstance sqlserver2014a -Path C:\\Temp Exports all execution plans for sqlserver2014a. Files saved in to C:\\Temp Example 2: Exports all execution plans for databases db1 and db2 on sqlserver2014a since July 1, 2016 at 10:47 AM PS C:\\> Export-DbaExecutionPlan -SqlInstance sqlserver2014a -Database db1, db2 -SinceLastExecution '2016-07-01 10:47:00' -Path C:\\Temp Exports all execution plans for databases db1 and db2 on sqlserver2014a since July 1, 2016 at 10:47 AM. Files saved in to C:\\Temp Example 3: Gets all execution plans for sqlserver2014a PS C:\\> Get-DbaExecutionPlan -SqlInstance sqlserver2014a | Export-DbaExecutionPlan -Path C:\\Temp Gets all execution plans for sqlserver2014a. Using Pipeline exports them all to C:\\Temp Example 4: Gets all execution plans for sqlserver2014a PS C:\\> Get-DbaExecutionPlan -SqlInstance sqlserver2014a | Export-DbaExecutionPlan -Path C:\\Temp -WhatIf Gets all execution plans for sqlserver2014a. Then shows what would happen if the results where piped to Export-DbaExecutionPlan Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts execution plan objects from the pipeline, typically from Get-DbaExecutionPlan. Use this when you want to filter or process plans with Get-DbaExecutionPlan first, then export specific results. Allows for more complex filtering scenarios before exporting plans to files. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to export execution plans from. Accepts wildcards for pattern matching. Use this when you need to focus on specific databases instead of analyzing plans from all databases on the instance. Helps reduce output volume and processing time when troubleshooting database-specific performance issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to exclude from execution plan export. Accepts wildcards for pattern matching. Use this to skip system databases or databases that are known to be performing well when doing instance-wide plan analysis. Common exclusions include tempdb, model, or development databases that don't need performance review. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory path where .sqlplan files will be saved. Defaults to the dbatools export configuration path. Files are named using a pattern that includes instance name, database, query position, and SQL handle for easy identification. Ensure the path exists and has sufficient space, as large plan caches can generate hundreds of files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -SinceCreation Filters execution plans to only include those created after the specified date and time. Use this when investigating performance issues that started after a specific deployment, configuration change, or known incident. Helps focus analysis on recently compiled plans rather than older cached plans that may no longer be relevant. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SinceLastExecution Filters execution plans to only include those last executed after the specified date and time. Use this when you want to analyze only actively used plans rather than stale plans sitting in cache. Particularly useful for identifying currently problematic queries during active performance issues or recent workload changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per execution plan exported. Each object contains information about the exported plan and the file where it was saved. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: The name of the database containing the execution plan SqlHandle: Hexadecimal identifier for the SQL statement (used internally by SQL Server) CreationTime: DateTime when the plan was first compiled/cached LastExecutionTime: DateTime when the plan was last executed OutputFile: Full path to the .sqlplan file saved to disk Additional properties available (not displayed by default): PlanHandle: Hexadecimal identifier for the compiled plan QueryPosition: Position of the statement within the batch (determined by row number) SingleStatementPlan: XML string representation of the single-statement execution plan BatchQueryPlan: XML string representation of the batch query execution plan SingleStatementPlanRaw: XML object parsed from SingleStatementPlan BatchQueryPlanRaw: XML object parsed from BatchQueryPlan Use Select-Object * to access all properties if needed for scripting or further processing. &nbsp;"
  },
  {
    "name": "Export-DbaInstance",
    "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's perfect for version control or automated deployment pipelines.\n\nUnless an -Exclude is specified, it exports:\n\nAll database 'restore from backup' scripts.  Note: if a database does not have a backup the 'restore from backup' script won't be generated.\nAll logins.\nAll database mail objects.\nAll credentials.\nAll objects within the Job Server (SQL Agent).\nAll linked servers.\nAll groups and servers within Central Management Server.\nAll SQL Server configuration objects (everything in sp_configure).\nAll user objects in system databases.\nAll system triggers.\nAll system backup devices.\nAll Audits.\nAll Endpoints.\nAll Extended Events.\nAll Policy Management objects.\nAll Resource Governor objects.\nAll Server Audit Specifications.\nAll Custom Errors (User Defined Messages).\nAll Server Roles.\nAll Availability Groups.\nAll OLEDB Providers.\n\nWhen -IncludeDbMasterKey is specified: all database certificates (exported as .cer files; private keys exported as .pvk files when -EncryptionPassword is provided) and all database master keys encrypted with the -EncryptionPassword.\n\nThe exported files are written to a folder using the naming convention \"machinename$instance-yyyyMMddHHmmss\", making it easy to identify the source instance and export timestamp.\n\nThis command is particularly valuable for:\n- Instance migrations when moving to new hardware or cloud platforms\n- Creating standardized development and test environments that match production\n- Disaster recovery planning by maintaining current configuration snapshots\n- Compliance documentation that automatically captures security settings and configurations\n- Change management workflows where you need baseline configurations before major updates\n\nTwo folder management options are supported:\n1. Default behavior creates new timestamped folders for historical archiving\n2. Using -Force overwrites files in the same location, ideal for scheduled exports that feed into version control systems\n\nFor more granular control, please use one of the -Exclude parameters and use the other functions available within the dbatools module.",
    "category": "Migration",
    "tags": [
      "export"
    ],
    "verb": "Export",
    "popular": true,
    "url": "/Export-DbaInstance",
    "popularityRank": 42,
    "synopsis": "Exports complete SQL Server instance configuration as T-SQL scripts for migration or disaster recovery",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaInstance View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports complete SQL Server instance configuration as T-SQL scripts for migration or disaster recovery 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. This 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's perfect for version control or automated deployment pipelines. Unless an -Exclude is specified, it exports: All database 'restore from backup' scripts. Note: if a database does not have a backup the 'restore from backup' script won't be generated. All logins. All database mail objects. All credentials. All objects within the Job Server (SQL Agent). All linked servers. All groups and servers within Central Management Server. All SQL Server configuration objects (everything in sp_configure). All user objects in system databases. All system triggers. All system backup devices. All Audits. All Endpoints. All Extended Events. All Policy Management objects. All Resource Governor objects. All Server Audit Specifications. All Custom Errors (User Defined Messages). All Server Roles. All Availability Groups. All OLEDB Providers. When -IncludeDbMasterKey is specified: all database certificates (exported as .cer files; private keys exported as .pvk files when -EncryptionPassword is provided) and all database master keys encrypted with the -EncryptionPassword. The 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. This command is particularly valuable for: Instance migrations when moving to new hardware or cloud platforms Creating standardized development and test environments that match production Disaster recovery planning by maintaining current configuration snapshots Compliance documentation that automatically captures security settings and configurations Change management workflows where you need baseline configurations before major updates Two folder management options are supported: 1. Default behavior creates new timestamped folders for historical archiving 2. Using -Force overwrites files in the same location, ideal for scheduled exports that feed into version control systems For more granular control, please use one of the -Exclude parameters and use the other functions available within the dbatools module. Syntax Export-DbaInstance [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [[-Path] ] [-NoRecovery] [[-AzureCredential] ] [-IncludeDbMasterKey] [[-EncryptionPassword] ] [[-DecryptionPassword] ] [[-Exclude] ] [[-BatchSeparator] ] [[-ScriptingOption] ] [-NoPrefix] [-ExcludePassword] [-Force] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: All databases, logins, job objects and sp_configure options will be exported from sqlserver\\instance to an... PS C:\\> Export-DbaInstance -SqlInstance sqlserver\\instance All databases, logins, job objects and sp_configure options will be exported from sqlserver\\instance to an automatically generated folder name in Documents. For example, %userprofile%\\Documents\\DbatoolsExport\\sqldev1$sqlcluster-20201108140000 Example 2: Exports everything but logins and database restore scripts to a folder such as... PS C:\\> Export-DbaInstance -SqlInstance sqlcluster -Exclude Databases, Logins -Path C:\\dr\\sqlcluster Exports everything but logins and database restore scripts to a folder such as C:\\dr\\sqlcluster\\sqldev1$sqlcluster-20201108140000 Example 3: Exports everything to a folder such as C:\\servers\\sqldev1$sqlcluster-20201108140000 but scripts will not... PS C:\\> Export-DbaInstance -SqlInstance sqlcluster -Path C:\\servers\\ -NoPrefix Exports everything to a folder such as C:\\servers\\sqldev1$sqlcluster-20201108140000 but scripts will not include prefix information. Example 4: Exports everything to a folder such as C:\\servers\\sqldev1$sqlcluster and will overwrite/refresh existing... PS C:\\> Export-DbaInstance -SqlInstance sqlcluster -Path C:\\servers\\ -Force Exports 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 include a timestamp. This supports the use case of running Export-DbaInstance on a schedule and writing to the same dir each time. Required Parameters -SqlInstance The target SQL Server instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Alternative Windows credentials for exporting Linked Servers and Credentials. Accepts credential objects (Get-Credential) | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the root directory where export files will be created in a timestamped subfolder. Defaults to the dbatools export path configuration setting, typically Documents\\DbatoolsExport. | Property | Value | | --- | --- | | Alias | FilePath | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -NoRecovery Generates database restore scripts with NORECOVERY option, leaving databases in restoring state. Essential for log shipping scenarios or when you need to apply additional transaction log backups after the initial restore. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AzureCredential Specifies the Azure storage credential name for accessing backups stored in Azure Blob Storage. Required when generating restore scripts for databases backed up to Azure storage containers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeDbMasterKey When specified, exports database certificates (.cer files) and database master keys (.key files) to the export directory. Certificate private keys (.pvk files) are also exported when -EncryptionPassword is provided. Database master keys require -EncryptionPassword to be specified; if omitted, only certificates are exported. Use -Exclude DbCertificates to suppress certificate export while still exporting master keys. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EncryptionPassword Secure password used to encrypt exported certificate private key files (.pvk) and database master key backups (.key). When specified with -IncludeDbMasterKey, enables export of private keys alongside certificates and also backs up database master keys. Required for database master key export; optional for certificate export (without it only .cer files are generated). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DecryptionPassword Password required to decrypt the certificate's existing private key before it can be re-encrypted for backup. Use this when certificates were originally created with a password or imported from a password-protected source. Only applies when -IncludeDbMasterKey is specified and DbCertificates is not in -Exclude. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Exclude Skips specific object types from the export to reduce scope or avoid problematic areas. Useful when you only need certain components or when specific features cause export issues in your environment. Valid values: Databases, Logins, AgentServer, Credentials, LinkedServers, SpConfigure, CentralManagementServer, DatabaseMail, SysDbUserObjects, SystemTriggers, BackupDevices, Audits, Endpoints, ExtendedEvents, PolicyManagement, ResourceGovernor, ServerAuditSpecifications, CustomErrors, ServerRoles, AvailabilityGroups, ReplicationSettings, OleDbProvider, DbCertificates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | AgentServer,Audits,AvailabilityGroups,BackupDevices,CentralManagementServer,Credentials,CustomErrors,DatabaseMail,Databases,DbCertificates,Endpoints,ExtendedEvents,LinkedServers,Logins,PolicyManagement,ReplicationSettings,ResourceGovernor,ServerAuditSpecifications,ServerRoles,SpConfigure,SysDbUserObjects,SystemTriggers,OleDbProvider | -BatchSeparator Defines the T-SQL batch separator used in generated scripts, defaults to \"GO\". Change this if your deployment tools or target environment requires a different batch separator like semicolon or custom delimiter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'formatting.batchseparator') | -ScriptingOption Provides a Microsoft.SqlServer.Management.Smo.ScriptingOptions object to customize script generation behavior. Use this to control advanced scripting options like check constraints, triggers, indexes, or permissions that aren't controlled by other parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoPrefix Removes header comments from generated scripts that normally include creation timestamp and dbatools version. Use this for cleaner scripts when feeding into version control systems or automated deployment pipelines that don't need metadata headers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludePassword Omits passwords from exported scripts for logins, credentials, and linked servers, replacing them with placeholder text. Essential for security compliance when export scripts will be stored in version control or shared with other team members. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Overwrites existing export files and uses a static folder name without timestamp. Ideal for scheduled exports that always write to the same location, such as automated backup documentation or CI/CD integration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns 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 exported (logins, jobs, credentials, etc.). The command returns file objects for successfully created export files, such as: sp_configure.sql: SQL Server configuration settings customererrors.sql: User-defined error messages serverroles.sql: Server role definitions credentials.sql: SQL credentials logins.sql: SQL Server logins dbmail.sql: Database Mail configuration regserver.xml: Central Management Server registration settings backupdevices.sql: Backup device definitions linkedservers.sql: Linked server configurations servertriggers.sql: Server-level triggers databases.sql: Database restore scripts audits.sql: Server audits auditspecs.sql: Server audit specifications endpoints.sql: Server endpoints policymanagement.sql: Policy-Based Management policies and conditions resourcegov.sql: Resource Governor configuration extendedevents.sql: Extended Events sessions sqlagent.sql: SQL Agent jobs, schedules, operators, alerts, and proxies replication.sql: Replication settings userobjectsinsysdbs.sql: User-created objects in system databases AvailabilityGroups.sql: Availability Groups configuration OleDbProvider.sql: OLEDB provider configuration .cer: Database certificate backups when -IncludeDbMasterKey is specified .pvk: Database certificate private key backups when -IncludeDbMasterKey and -EncryptionPassword are specified *.key: Database master key backups when -IncludeDbMasterKey and -EncryptionPassword are specified Files are returned only if they were successfully created and are not excluded via the -Exclude parameter. The -ErrorAction Ignore used in Get-ChildItem means that if a file is not created, no error object is returned for that file. All FileInfo properties are accessible, including: FullName: Complete path to the exported file Name: File name Length: File size in bytes CreationTime: When the file was created LastWriteTime: When the file was last written &nbsp;"
  },
  {
    "name": "Export-DbaLinkedServer",
    "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.",
    "category": "Migration",
    "tags": [
      "linkedserver"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaLinkedServer",
    "popularityRank": 78,
    "synopsis": "Generates T-SQL scripts to recreate linked server configurations with their login credentials.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Export-DbaLinkedServer View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates T-SQL scripts to recreate linked server configurations with their login credentials. 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. Syntax Export-DbaLinkedServer [-SqlInstance] [[-LinkedServer] ] [[-SqlCredential] ] [[-Credential] ] [[-Path] ] [[-FilePath] ] [-ExcludePassword] [-Append] [-Passthru] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports the linked servers, including passwords, from sql2017 to the file C:\\temp\\ls.sql PS C:\\> Export-DbaLinkedServer -SqlInstance sql2017 -Path C:\\temp\\ls.sql Example 2: Exports the linked servers, without passwords, from sql2017 to the file C:\\temp\\ls.sql PS C:\\> Export-DbaLinkedServer -SqlInstance sql2017 -Path C:\\temp\\ls.sql -ExcludePassword Example 3: Returns the T-SQL script for linked servers to the console instead of writing to a file PS C:\\> Export-DbaLinkedServer -SqlInstance sql2017 -Passthru Required Parameters -SqlInstance Source SQL Server. You must have sysadmin access and server version must be SQL Server version 2005 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -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. Use this when you need to export specific linked servers rather than the entire linked server configuration from an instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential) Only used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory where the linked server export file will be created. Defaults to the configured DbatoolsExport path. Use this when you need the script saved to a specific folder location for organization or deployment purposes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Specifies the complete file path and name for the exported T-SQL script, including the .sql extension. Use this when you need precise control over the output filename and location, overriding the automatic naming from Path parameter. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -ExcludePassword Excludes actual passwords from the exported script, replacing them with placeholder values for security purposes. Use this when sharing scripts across environments or with team members where you need the linked server structure but want to protect sensitive credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Append Adds the exported linked server scripts to an existing file instead of overwriting it. Use this when combining multiple linked server exports into a single deployment script or building comprehensive migration scripts over multiple runs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Passthru Returns the generated T-SQL script to the PowerShell pipeline instead of saving to file. Use this to capture the script in a variable, pipe to other commands, or display directly in the console. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts linked server objects piped from Get-DbaLinkedServer, allowing you to filter and process specific linked servers before export. Use this when you want to chain commands together, such as first getting linked servers with specific criteria then exporting only those results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String (when -Passthru is specified or when no -Path/-FilePath is provided) Returns 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. System.IO.FileInfo (when -Path or -FilePath is specified) Returns file information for the exported T-SQL script file. Properties include: FullName: Complete file path including filename Name: The filename (e.g., \"sql2017_linkedservers.sql\") Directory: The directory where the file is located Length: File size in bytes LastWriteTime: Timestamp of when the file was created or last modified &nbsp;"
  },
  {
    "name": "Export-DbaLogin",
    "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't restore the associated logins, leaving applications unable to connect. DBAs use this for server migrations, disaster recovery scenarios, and maintaining consistent security across environments.",
    "category": "Migration",
    "tags": [
      "export",
      "login"
    ],
    "verb": "Export",
    "popular": true,
    "url": "/Export-DbaLogin",
    "popularityRank": 18,
    "synopsis": "Generates T-SQL scripts to recreate SQL Server logins with their complete security context for migration and disaster recovery.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaLogin View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates T-SQL scripts to recreate SQL Server logins with their complete security context for migration and disaster recovery. 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't restore the associated logins, leaving applications unable to connect. DBAs use this for server migrations, disaster recovery scenarios, and maintaining consistent security across environments. Syntax Export-DbaLogin [[-SqlInstance] ] [[-SqlCredential] ] [[-InputObject] ] [[-Login] ] [[-ExcludeLogin] ] [[-Database] ] [-ExcludeJobs] [-ExcludeDatabase] [-ExcludePassword] [[-DefaultDatabase] ] [[-Path] ] [[-FilePath] ] [[-Encoding] ] [-NoClobber] [-Append] [[-BatchSeparator] ] [[-DestinationVersion] ] [-NoPrefix] [-Passthru] [-ObjectLevel] [-IncludeRolePermissions] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Exports the logins for SQL Server &quot;sql2005&quot; and writes them to the file &quot;C:\\temp\\sql2005-logins.sql&quot; PS C:\\> Export-DbaLogin -SqlInstance sql2005 -Path C:\\temp\\sql2005-logins.sql Example 2: Authenticates to sqlserver2014a using SQL Authentication PS C:\\> Export-DbaLogin -SqlInstance sqlserver2014a -ExcludeLogin realcajun -SqlCredential $scred -Path C:\\temp\\logins.sql -Append Authenticates 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. Example 3: Exports ONLY logins netnerds and realcajun FROM sqlserver2014a to the file C:\\temp\\logins.sql PS C:\\> Export-DbaLogin -SqlInstance sqlserver2014a -Login realcajun, netnerds -Path C:\\temp\\logins.sql Example 4: Exports ONLY logins netnerds and realcajun FROM sqlserver2014a with the permissions on databases HR and... PS C:\\> Export-DbaLogin -SqlInstance sqlserver2014a -Login realcajun, netnerds -Database HR, Accounting Exports ONLY logins netnerds and realcajun FROM sqlserver2014a with the permissions on databases HR and Accounting Example 5: Exports ONLY logins FROM sqlserver2014a with permissions on databases HR and Accounting PS C:\\> Get-DbaDatabase -SqlInstance sqlserver2014a -Database HR, Accounting | Export-DbaLogin Example 6: Exports ONLY logins netnerds and realcajun FROM sqlserver2008 server, to the C:\\temp\\login.sql file without... PS C:\\> Set-DbatoolsConfig -FullName formatting.batchseparator -Value $null PS C:\\> Export-DbaLogin -SqlInstance sqlserver2008 -Login realcajun, netnerds -Path C:\\temp\\login.sql Exports ONLY logins netnerds and realcajun FROM sqlserver2008 server, to the C:\\temp\\login.sql file without the 'GO' batch separator. Example 7: Exports login realcajun from sqlserver2008 to the file C:\\temp\\users.sql with syntax to run on SQL Server 2016 PS C:\\> Export-DbaLogin -SqlInstance sqlserver2008 -Login realcajun -Path C:\\temp\\users.sql -DestinationVersion SQLServer2016 Example 8: Exports login realcajun from sqlserver2008 PS C:\\> Get-DbaDatabase -SqlInstance sqlserver2008 -Login realcajun | Export-DbaLogin Example 9: Exports all enabled logins from sqlserver2008 and sqlserver2008 PS C:\\> Get-DbaLogin -SqlInstance sqlserver2008, sqlserver2012 | Where-Object { $_.IsDisabled -eq $false } | Export-DbaLogin Optional Parameters -SqlInstance The target SQL Server instance or instances. SQL Server 2000 and above supported. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts piped objects from Get-DbaLogin, Get-DbaDatabase, or Connect-DbaInstance commands. Use this when you want to export logins from specific objects rather than specifying instances directly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Login Specifies which SQL Server logins to export by name. Accepts wildcards and arrays. When specified, only these logins are processed instead of all server logins. Use this to target specific accounts for migration or backup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeLogin Specifies login names to skip during export. Accepts wildcards and arrays. Use this to exclude system accounts, service accounts, or other logins that shouldn't be migrated to the target environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Limits export to logins that have user mappings in the specified databases. Accepts database names or database objects. When specified, only logins with permissions or user accounts in these databases are exported, reducing script size for targeted migrations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJobs Excludes SQL Agent job ownership assignments from the export script. Use this when migrating logins to servers where the associated jobs don't exist or will be owned by different accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeDatabase Excludes database user mappings and permissions from the export script. Use this when you only need server-level login definitions without their database-specific permissions and role memberships. | Property | Value | | --- | --- | | Alias | ExcludeDatabases | | Required | False | | Pipeline | false | | Default Value | False | -ExcludePassword Excludes hashed password values from SQL login export, replacing them with placeholder text. Use this for security compliance when sharing scripts or when passwords will be reset after migration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DefaultDatabase Overrides the default database for all exported logins with the specified database name. Use this when migrating to servers where the original default databases don't exist, preventing login creation failures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory where export files will be saved. Defaults to the Path.DbatoolsExport configuration setting. Files are automatically named based on instance and timestamp unless FilePath is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Specifies the complete file path for the export script. Cannot be used when exporting from multiple instances. Use this when you need precise control over the output file location and name. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -Encoding Sets the character encoding for the output file. Defaults to UTF8. Choose the appropriate encoding based on your deployment environment requirements and any special characters in login names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UTF8 | | Accepted Values | ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown | -NoClobber Prevents overwriting existing files at the specified Path location. Use this as a safety measure when you don't want to accidentally replace existing login export scripts. | Property | Value | | --- | --- | | Alias | NoOverwrite | | Required | False | | Pipeline | false | | Default Value | False | -Append Adds the generated script to an existing file instead of overwriting it. Use this to combine login exports from multiple instances into a single deployment script. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BatchSeparator Sets the T-SQL batch separator used between statements. Defaults to 'GO' from the Formatting.BatchSeparator configuration. Specify an empty string to remove batch separators when the target system doesn't support them. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Formatting.BatchSeparator') | -DestinationVersion Generates T-SQL syntax compatible with the specified SQL Server version. Defaults to the source instance version. Use this when migrating to older SQL Server versions that require different syntax for role assignments or other features. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | SQLServer2000,SQLServer2005,SQLServer2008/2008R2,SQLServer2012,SQLServer2014,SQLServer2016,SQLServer2017,SQLServer2019,SQLServer2022 | -NoPrefix Excludes the standard dbatools header comment from the generated script. Use this when you need clean T-SQL output without metadata comments for automated deployment systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Passthru Returns the generated T-SQL script to the PowerShell pipeline instead of saving to file. Use this to capture the script in a variable, pipe to other commands, or display directly in the console. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ObjectLevel Includes detailed object-level permissions for each database user associated with the exported logins. Use this for complete permission migration when you need granular security settings preserved in the target environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeRolePermissions Includes permissions granted to database roles that the login's database users are members of. By default, Export-DbaLogin scripts role membership (ALTER ROLE ... ADD MEMBER) but not the permissions granted to those roles. Use this switch to also export GRANT/DENY statements for each non-fixed role, ensuring the roles have the correct permissions on the target server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.String (when -Passthru is specified or neither -Path nor -FilePath is specified) Returns 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 saved to a file. System.IO.FileInfo (when -Path or -FilePath is specified) Returns file information objects for the created export files. Each file contains the generated T-SQL script for login recreation including: CREATE LOGIN statements with password hashes (or placeholder text if -ExcludePassword is used) DEFAULT_DATABASE setting (or the -DefaultDatabase override if specified) Login enabled/disabled status DENY CONNECT SQL restrictions if applicable Server role memberships SQL Agent job ownership assignments (unless -ExcludeJobs is specified) Server-level permissions and securables (for SQL Server 2005+) Credential associations Database user mappings and database roles (unless -ExcludeDatabase is specified) Object-level permissions (if -ObjectLevel is specified) The script is formatted with the specified -BatchSeparator (default 'GO') between statements and includes a dbatools header comment unless -NoPrefix is specified. &nbsp;"
  },
  {
    "name": "Export-DbaPfDataCollectorSetTemplate",
    "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.",
    "category": "Migration",
    "tags": [
      "performance",
      "datacollector"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaPfDataCollectorSetTemplate",
    "popularityRank": 611,
    "synopsis": "Exports Windows Performance Monitor Data Collector Set configurations as reusable XML templates.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Export-DbaPfDataCollectorSetTemplate View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports Windows Performance Monitor Data Collector Set configurations as reusable XML templates. 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. Syntax Export-DbaPfDataCollectorSetTemplate [[-ComputerName] ] [[-Credential] ] [[-CollectorSet] ] [[-Path] ] [[-FilePath] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports all data collector sets from to the C:\\temp\\pf folder PS C:\\> Export-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Path C:\\temp\\pf Example 2: Exports the &#39;System Correlation&#39; data collector set from sql2017 to C:\\temp PS C:\\> Get-DbaPfDataCollectorSet ComputerName sql2017 -CollectorSet 'System Correlation' | Export-DbaPfDataCollectorSetTemplate -Path C:\\temp Optional Parameters -ComputerName Specifies the target computer(s) to export data collector sets from. Defaults to localhost. Use this to export performance monitoring templates from remote SQL Server hosts for standardization across your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to $ComputerName using alternative credentials. To use: $cred = Get-Credential, then pass $cred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CollectorSet Specifies the name(s) of specific data collector sets to export. If not specified, all collector sets will be exported. Use this when you only need to export particular performance monitoring configurations rather than all available sets. | Property | Value | | --- | --- | | Alias | DataCollectorSet | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory where XML template files will be created. Each collector set exports as a separate XML file. Defaults to the configured dbatools export path, typically used when exporting multiple collector sets. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Specifies the complete file path including filename for the exported XML template. Use instead of Path when exporting a single collector set. Automatically appends .xml extension if not provided, ideal for creating named templates for specific monitoring scenarios. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts data collector set objects from Get-DbaPfDataCollectorSet via pipeline input. Enables pipeline workflows for filtering and processing collector sets. Use this when you need to chain commands together, such as filtering collector sets before exporting them. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns 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 settings. Properties: Name: The filename of the exported template (e.g., 'System Correlation.xml') FullName: The complete path to the exported XML file Directory: The parent folder where the file was created Length: File size in bytes CreationTime: When the file was created LastWriteTime: When the file was last modified Extension: File extension (.xml) &nbsp;"
  },
  {
    "name": "Export-DbaRegServer",
    "description": "Exports registered servers and registered server groups to file",
    "category": "Migration",
    "tags": [
      "registeredserver",
      "cms"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaRegServer",
    "popularityRank": 280,
    "synopsis": "Exports registered servers and registered server groups to file",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaRegServer View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports registered servers and registered server groups to file Description Exports registered servers and registered server groups to file Syntax Export-DbaRegServer [[-SqlInstance] ] [[-SqlCredential] ] [[-InputObject] ] [[-Path] ] [[-FilePath] ] [[-CredentialPersistenceType] ] [[-Group] ] [[-ExcludeGroup] ] [-Overwrite] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports all Registered Server and Registered Server Groups on sql2008 to an automatically generated file name... PS C:\\> Export-DbaRegServer -SqlInstance sql2008 Exports all Registered Server and Registered Server Groups on sql2008 to an automatically generated file name in the current directory Example 2: Exports all registered servers on sql2008 and sql2012 PS C:\\> Get-DbaRegServer -SqlInstance sql2008, sql2012 | Export-DbaRegServer Exports all registered servers on sql2008 and sql2012. Warning - each one will have its own individual file. Consider piping groups. Example 3: Exports all registered servers on sql2008 and sql2012, organized by group PS C:\\> Get-DbaRegServerGroup -SqlInstance sql2008, sql2012 | Export-DbaRegServer Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts registered server or server group objects from Get-DbaRegServer, Get-DbaRegServerGroup, or custom objects via pipeline. Use this to export specific servers or groups that have been filtered or modified before export. For custom objects, requires a ServerName column with optional Name, Description, and Group columns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Path Specifies the directory where the exported registered server files will be saved. Uses the dbatools default export directory if not specified, typically your user profile's Documents folder. Automatically generates timestamped filenames when exporting multiple servers or groups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Specifies the complete file path for the exported registered server file, including filename and extension. Must end with .xml or .regsrvr extension to be compatible with SQL Server Management Studio imports. When exporting multiple groups, the group name is automatically appended to avoid file conflicts. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -CredentialPersistenceType Controls how login credentials are stored in the exported registered server file. Use 'PersistLoginName' to save usernames only, or 'PersistLoginNameAndPassword' to include passwords for automated connections. Defaults to 'None' for security, requiring manual credential entry when connecting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | None | | Accepted Values | None,PersistLoginName,PersistLoginNameAndPassword | -Group Filters export to include only registered servers from the specified server group names. Use this when you want to export servers from specific organizational groups like 'Production', 'Development', or 'QA'. Accepts wildcards and multiple group names to export several groups in a single operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeGroup Excludes registered servers from the specified server group names during export. Useful when exporting most groups but need to skip sensitive environments like 'Production' or 'Customer-Facing'. Can be combined with the Group parameter to fine-tune which servers are included in the export. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Overwrite Allows the function to replace an existing file at the specified FilePath location. Required when the target export file already exists, preventing accidental data loss. Without this switch, the function will stop with an error if the destination file is found. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns one file object for each exported registered server or server group. The file object contains information about the exported XML file that was created. Properties: Name: The filename of the exported registered server file FullName: The complete file path to the exported file Directory: The directory containing the exported file Extension: The file extension (.xml or .regsrvr) Length: The size of the exported file in bytes CreationTime: When the file was created LastWriteTime: When the file was last modified Attributes: File attributes (Archive, etc.) &nbsp;"
  },
  {
    "name": "Export-DbaReplServerSetting",
    "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's 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",
    "category": "Migration",
    "tags": [
      "replication",
      "repl"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaReplServerSetting",
    "popularityRank": 516,
    "synopsis": "Generates T-SQL scripts to recreate SQL Server replication distributor and publication configurations",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Export-DbaReplServerSetting View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates T-SQL scripts to recreate SQL Server replication distributor and publication configurations 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. The function scripts out the complete replication configuration using SQL Server's replication management objects, so you can rebuild identical replication setups on different servers or restore replication after system failures. All replication commands need SQL Server Management Studio installed and are therefore currently not supported. Have a look at this issue to get more information: https://github.com/dataplat/dbatools/issues/7428 Syntax Export-DbaReplServerSetting [[-SqlInstance] ] [[-SqlCredential] ] [[-Path] ] [[-FilePath] ] [[-ScriptOption] ] [[-InputObject] ] [[-Encoding] ] [-Passthru] [-NoClobber] [-Append] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports the replication settings on sql2017 to the file C:\\temp\\replication.sql PS C:\\> Export-DbaReplServerSetting -SqlInstance sql2017 -Path C:\\temp\\replication.sql Example 2: Exports the replication settings on sql2017 to the file C:\\temp\\replication.sql PS C:\\> Get-DbaReplServer -SqlInstance sql2017 | Export-DbaReplServerSetting -Path C:\\temp\\replication.sql Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory where the replication script file will be created. Defaults to the dbatools export path configuration. Use this when you want to organize replication scripts in a specific directory structure for disaster recovery or documentation purposes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Specifies the complete file path including filename for the exported replication script. Overrides both Path parameter and default naming. Use this when you need precise control over the output file location and name, especially for automated backup processes. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -ScriptOption Specifies custom Microsoft.SqlServer.Replication.ScriptOptions flags to control which replication components are scripted. Advanced parameter for fine-tuning script output when the default options don't meet specific requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts replication server objects from Get-DbaReplServer pipeline input for batch processing. Use this when scripting replication settings from multiple servers or when combining with other replication commands in a pipeline. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Encoding Specifies the character encoding for the output script file. Defaults to UTF8 which handles international characters properly. Use ASCII for maximum compatibility with older systems, or Unicode when working with databases containing non-English characters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UTF8 | | Accepted Values | 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. Use this for immediate review of the script content or when piping output to other commands for further processing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoClobber Prevents overwriting an existing file with the same name. The operation will fail if the target file already exists. Use this as a safety measure to avoid accidentally replacing existing replication scripts during routine exports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Append Adds the replication script to the end of an existing file instead of overwriting it. Use this when consolidating multiple replication configurations into a single script file for bulk operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String (when -Passthru is specified) Returns the generated T-SQL replication script as a string. The script includes: An 'exec sp_dropdistributor' statement with @no_checks = 1 and @ignore_distributor = 1 T-SQL commands to recreate the distributor configuration T-SQL commands to recreate all publications and their settings T-SQL commands to recreate all subscriptions All related replication objects and configurations based on the specified -ScriptOption flags None (when -Passthru is not specified) No 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 replication setup on another server. &nbsp;"
  },
  {
    "name": "Export-DbaScript",
    "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.",
    "category": "Migration",
    "tags": [
      "migration",
      "backup",
      "export"
    ],
    "verb": "Export",
    "popular": true,
    "url": "/Export-DbaScript",
    "popularityRank": 10,
    "synopsis": "Generates T-SQL CREATE scripts from SQL Server Management Objects for migration and deployment",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaScript View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates T-SQL CREATE scripts from SQL Server Management Objects for migration and deployment 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. Syntax Export-DbaScript [-InputObject] [[-ScriptingOptionsObject] ] [[-Path] ] [[-FilePath] ] [[-Encoding] ] [[-BatchSeparator] ] [-NoPrefix] [-Passthru] [-NoClobber] [-Append] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Exports all jobs on the SQL Server sql2016 instance using a trusted connection - automatically determines... PS C:\\> Get-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript Exports 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. Example 2: Exports all jobs on the SQL Server sql2016 instance using a trusted connection - Will append the output to... PS C:\\> Get-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript -FilePath C:\\temp\\export.sql -Append Exports 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 Inclusion of Batch Separator in script depends on the configuration s not include Batch Separator and will not compile Example 3: Exports only script for &#39;dbo.Table1&#39; and &#39;dbo.Table2&#39; in MyDatabase to C:temp\\export.sql and uses the SQL... PS C:\\> Get-DbaDbTable -SqlInstance sql2016 -Database MyDatabase -Table 'dbo.Table1', 'dbo.Table2' -SqlCredential sqladmin | Export-DbaScript -FilePath C:\\temp\\export.sql Exports only script for 'dbo.Table1' and 'dbo.Table2' in MyDatabase to C:temp\\export.sql and uses the SQL login \"sqladmin\" to login to sql2016 Example 4: Exports only syspolicy_purge_history and &#39;Hourly Log Backups&#39; to C:temp\\export.sql and uses the SQL login... PS C:\\> Get-DbaAgentJob -SqlInstance sql2016 -Job syspolicy_purge_history, 'Hourly Log Backups' -SqlCredential sqladmin | Export-DbaScript -FilePath C:\\temp\\export.sql -NoPrefix Exports only syspolicy_purge_history and 'Hourly Log Backups' to C:temp\\export.sql and uses the SQL login \"sqladmin\" to login to sql2016 Suppress the output of a Prefix Example 5: Exports only syspolicy_purge_history and &#39;Hourly Log Backups&#39; to C:temp\\export.sql and uses the SQL login... PS C:\\> $options = New-DbaScriptingOption PS C:\\> $options.ScriptSchema = $true PS C:\\> $options.IncludeDatabaseContext = $true PS C:\\> $options.IncludeHeaders = $false PS C:\\> $Options.NoCommandTerminator = $false PS C:\\> $Options.ScriptBatchTerminator = $true PS C:\\> $Options.AnsiFile = $true PS C:\\> Get-DbaAgentJob -SqlInstance sql2016 -Job syspolicy_purge_history, 'Hourly Log Backups' -SqlCredential sqladmin | Export-DbaScript -FilePath C:\\temp\\export.sql -ScriptingOptionsObject $options Exports only syspolicy_purge_history and 'Hourly Log Backups' to C:temp\\export.sql and uses the SQL login \"sqladmin\" to login to sql2016 Uses Scripting options to ensure Batch Terminator is set Example 6: Exports jobs and replaces all instances of the servername &quot;sql2014&quot; with &quot;sql2016&quot; then writes to... PS C:\\> Get-DbaAgentJob -SqlInstance sql2014 | Export-DbaScript -Passthru | ForEach-Object { $_.Replace('sql2014','sql2016') } | Set-Content -Path C:\\temp\\export.sql Exports jobs and replaces all instances of the servername \"sql2014\" with \"sql2016\" then writes to C:\\temp\\export.sql Example 7: Exports Script for each database on sql2016 excluding system databases Uses Scripting options to ensure Batch... PS C:\\> $options = New-DbaScriptingOption PS C:\\> $options.ScriptSchema = $true PS C:\\> $options.IncludeDatabaseContext = $true PS C:\\> $options.IncludeHeaders = $false PS C:\\> $Options.NoCommandTerminator = $false PS C:\\> $Options.ScriptBatchTerminator = $true PS C:\\> $Options.AnsiFile = $true PS C:\\> $Databases = Get-DbaDatabase -SqlInstance sql2016 -ExcludeDatabase master, model, msdb, tempdb PS C:\\> foreach ($db in $Databases) { >> Export-DbaScript -InputObject $db -FilePath C:\\temp\\export.sql -Append -Encoding UTF8 -ScriptingOptionsObject $options -NoPrefix >> } Exports Script for each database on sql2016 excluding system databases Uses Scripting options to ensure Batch Terminator is set Will append the output to the file C:\\temp\\export.sql if it already exists Required Parameters -InputObject Accepts any SQL Server Management Object (SMO) from dbatools commands like Get-DbaLogin, Get-DbaAgentJob, or Get-DbaDatabase. Use this when you need to generate CREATE scripts for specific database objects, jobs, logins, or other SQL Server components. The object type determines what kind of T-SQL script will be generated. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -ScriptingOptionsObject Accepts a customized SMO ScriptingOptions object created with New-DbaScriptingOption to control script generation. Use this when you need specific formatting like including schema context, headers, or data along with object definitions. Settings in this object override other Export-DbaScript parameters like BatchSeparator. | Property | Value | | --- | --- | | Alias | ScriptingOptionObject | | Required | False | | Pipeline | false | | Default Value | | -Path Sets the directory where script files will be saved when FilePath is not specified. Defaults to the configured dbatools export directory from your Path.DbatoolsExport setting. Use this when you want scripts saved to a standard location with auto-generated filenames. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Sets the complete file path and name for the output script file. Use this when you need the script saved to a specific location with a custom filename. Overrides the Path parameter when specified. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -Encoding Controls the character encoding used when writing script files to disk. Default is UTF8 which handles international characters and is widely supported. Use UTF8 for most scenarios, or ASCII if you need compatibility with older tools that don't support Unicode. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UTF8 | | Accepted Values | ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown | -BatchSeparator Sets the batch terminator added between SQL statements in the output script. Defaults to \"GO\" from your dbatools configuration, which is standard for SQL Server Management Studio. Use a different separator if deploying to tools that require different batch terminators. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Formatting.BatchSeparator') | -NoPrefix Suppresses the header comment block that normally identifies when and by whom the script was generated. Use this when you need clean scripts without metadata comments for automated deployments. The prefix normally includes timestamp, username, and dbatools version information. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Passthru Returns the generated T-SQL script as string output instead of writing to a file. Use this when you need to capture the script in a variable for further processing or modification. Commonly used in pipelines to transform scripts before saving. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoClobber Prevents overwriting existing files, causing the command to fail if the target file already exists. Use this as a safety measure when you want to ensure you don't accidentally replace existing scripts. Combine with -Append if you want to add to existing files instead. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Append Adds the generated script to the end of an existing file instead of overwriting it. Use this when building consolidated deployment scripts by combining multiple objects into one file. Particularly useful for scripting multiple databases or object types into a single migration script. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.String (when -Passthru is specified) Returns the generated T-SQL script as a string. When multiple objects are piped in, returns multiple strings separated by newlines. Each script includes a comment prefix (unless -NoPrefix is used) with generation timestamp, username, and dbatools version. Script sections are separated by the configured batch terminator (typically \"GO\"). System.IO.FileInfo (default when -Passthru is not specified) Returns one file object per input object representing the generated SQL script file(s) written to disk. When multiple objects are piped in, multiple file objects are returned. Properties: Name: The filename of the exported script (e.g., \"sql2016-Export-DbaScript-20231215_143022.sql\") FullName: The complete path to the exported script file Directory: The directory object containing the file CreationTime: When the file was created LastWriteTime: When the file was last modified Length: Size of the file in bytes Extension: Always \".sql\" &nbsp;"
  },
  {
    "name": "Export-DbaServerRole",
    "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's post \"Fully Script out a MSSQL Database Role\"\nReference:  https://dbaeyes.wordpress.com/2013/04/19/fully-script-out-a-mssql-database-role/",
    "category": "Migration",
    "tags": [
      "export",
      "role"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaServerRole",
    "popularityRank": 268,
    "synopsis": "Generates T-SQL scripts for server-level roles including permissions and memberships",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaServerRole View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates T-SQL scripts for server-level roles including permissions and memberships 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. Primarily 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. This command extends John Eisbrener's post \"Fully Script out a MSSQL Database Role\" Reference: https://dbaeyes.wordpress.com/2013/04/19/fully-script-out-a-mssql-database-role/ Syntax Export-DbaServerRole [[-SqlInstance] ] [[-SqlCredential] ] [[-InputObject] ] [[-ScriptingOptionsObject] ] [[-ServerRole] ] [[-ExcludeServerRole] ] [-ExcludeFixedRole] [-IncludeRoleMember] [[-Path] ] [[-FilePath] ] [-Passthru] [[-BatchSeparator] ] [-NoClobber] [-Append] [-NoPrefix] [[-Encoding] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports the Server Roles for SQL Server &quot;sql2005&quot; and writes them to the path defined in the ConfigValue... PS C:\\> Export-DbaServerRole -SqlInstance sql2005 Exports the Server Roles for SQL Server \"sql2005\" and writes them to the path defined in the ConfigValue 'Path.DbatoolsExport' using a a default name pattern of ServerName-YYYYMMDDhhmmss-serverrole. Uses BatchSeparator defined by Config 'Formatting.BatchSeparator' Example 2: Exports the Server Roles for SQL Server &quot;sql2005&quot; and writes them to the path &quot;C:\\temp&quot; using a a default... PS C:\\> Export-DbaServerRole -SqlInstance sql2005 -Path C:\\temp Exports 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 'Formatting.BatchSeparator' Example 3: Exports the Server Roles for SQL Server sqlserver2014a to the file C:\\temp\\ServerRoles.sql PS C:\\> Export-DbaServerRole -SqlInstance sqlserver2014a -FilePath C:\\temp\\ServerRoles.sql Exports the Server Roles for SQL Server sqlserver2014a to the file C:\\temp\\ServerRoles.sql. Overwrites file if exists Example 4: Exports ONLY ServerRole SchemaReader FROM sqlserver2014a and writes script to console PS C:\\> Export-DbaServerRole -SqlInstance sqlserver2014a -ServerRole SchemaReader -Passthru Example 5: Exports server roles from sqlserver2008, excludes all roles marked as as FixedRole and Public role PS C:\\> Export-DbaServerRole -SqlInstance sqlserver2008 -ExcludeFixedRole -ExcludeServerRole Public -IncludeRoleMember -FilePath C:\\temp\\ServerRoles.sql -Append -BatchSeparator '' Exports 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. Does not include a BatchSeparator Example 6: Exports server roles from sqlserver2012, sqlserver2014 and writes them to the path defined in the ConfigValue... PS C:\\> Get-DbaServerRole -SqlInstance sqlserver2012, sqlserver2014 | Export-DbaServerRole Exports server roles from sqlserver2012, sqlserver2014 and writes them to the path defined in the ConfigValue 'Path.DbatoolsExport' using a a default name pattern of ServerName-YYYYMMDDhhmmss-serverrole Example 7: Exports server roles from sqlserver2016, excludes all roles marked as as FixedRole and Public role PS C:\\> Get-DbaServerRole -SqlInstance sqlserver2016 -ExcludeFixedRole -ExcludeServerRole Public | Export-DbaServerRole -IncludeRoleMember Exports server roles from sqlserver2016, excludes all roles marked as as FixedRole and Public role. Includes RoleMembers Optional Parameters -SqlInstance The target SQL Server instance or instances. SQL Server 2000 and above supported. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -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 object owners or database context. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeServerRole Excludes specific server-level roles from the export by name. Use this to skip problematic roles or roles you don't want to migrate to the target instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 Server 2008/2008R2, this will exclude all roles since user-defined server roles weren't supported. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 deployment process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -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 exporting from a single instance. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BatchSeparator Sets the batch separator used between T-SQL statements in the output. Defaults to the configured value, typically 'GO'. Change this when deploying to tools that use different batch separators or set to empty string to remove separators entirely. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Formatting.BatchSeparator') | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 deployments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Encoding Sets the character encoding for the output file. Defaults to UTF8 which handles international characters correctly. Change to ASCII only if you're certain the role names contain no special characters and need compatibility with older systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UTF8 | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String When -Passthru is specified, or when neither -Path nor -FilePath is provided, returns the generated T-SQL script as a string. Properties of the output include: Role creation statements with IF NOT EXISTS clauses GRANT, DENY, and REVOKE permission statements for each role's permissions Optional ALTER SERVER ROLE statements to add current role members (when -IncludeRoleMember is specified) Optional header comment block with generation metadata (unless -NoPrefix is specified) Batch separator statements between T-SQL commands (configurable via -BatchSeparator) System.IO.FileInfo When -Path or -FilePath is specified (and -Passthru is not used), returns FileInfo objects for each script file created, one per instance processed. Properties: FullName: Complete file path where the script was saved Name: File name of the exported script Directory: Directory containing the script file Length: Size of the file in bytes CreationTime: Timestamp when the file was created LastWriteTime: Timestamp of the last modification &nbsp;"
  },
  {
    "name": "Export-DbaSpConfigure",
    "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 'show advanced options' if needed to capture all available settings, then restores the original setting.",
    "category": "Migration",
    "tags": [
      "spconfig",
      "configure",
      "configuration"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaSpConfigure",
    "popularityRank": 156,
    "synopsis": "Generates SQL script containing all sp_configure settings for SQL Server instance configuration replication and documentation.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaSpConfigure View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates SQL script containing all sp_configure settings for SQL Server instance configuration replication and documentation. 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 'show advanced options' if needed to capture all available settings, then restores the original setting. Syntax Export-DbaSpConfigure [-SqlInstance] [[-SqlCredential] ] [[-Path] ] [[-FilePath] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports the SPConfigure settings on sourceserver PS C:\\> Export-DbaSpConfigure -SqlInstance sourceserver Exports 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 Example 2: Exports the SPConfigure settings on sourceserver to the directory C:\\temp using the default name format PS C:\\> Export-DbaSpConfigure -SqlInstance sourceserver -Path C:\\temp Example 3: Exports the SPConfigure settings on sourceserver to the file C:\\temp\\sp_configure.sql PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Export-DbaSpConfigure -SqlInstance sourceserver -SqlCredential $cred -Path C:\\temp\\sp_configure.sql Exports 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 'show advanced options' Example 4: Exports the SPConfigure settings for Server1 and Server2 using pipeline PS C:\\> 'Server1', 'Server2' | Export-DbaSpConfigure -Path C:\\temp\\configure.sql Exports 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 C:\\temp\\Servername-MMDDYYYYhhmmss-configure.sql Required Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input. You must have sysadmin access if needs to set 'show advanced options' to 1 and server version must be SQL Server version 2005 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory where the sp_configure script files will be exported. Defaults to the configured DbatoolsExport path. Use this when you need to organize configuration scripts in a specific location for documentation or deployment procedures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Specifies the complete file path including filename for the exported sp_configure script. Overrides the Path parameter when specified. Use this when you need precise control over the output filename, especially for automated deployment scripts or standardized naming conventions. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns 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 replicate the exact configuration settings. Properties: Name: The name of the exported SQL script file (format: Servername-MMDDYYYYhhmmss-sp_configure.sql) FullName: The complete file path to the exported SQL script Directory: The parent directory object where the file is stored Length: The size of the SQL script file in bytes CreationTime: DateTime when the file was created LastWriteTime: DateTime when the file was last modified Extension: The file extension (.sql) Attributes: File attributes (Archive, etc.) &nbsp;"
  },
  {
    "name": "Export-DbaSysDbUserObject",
    "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.",
    "category": "Migration",
    "tags": [
      "export",
      "object",
      "systemdatabase"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaSysDbUserObject",
    "popularityRank": 327,
    "synopsis": "Discovers and exports user-created objects from SQL Server system databases (master, model, msdb) to SQL script files.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaSysDbUserObject View Source Jess Pomfret (@jpomfret) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Discovers and exports user-created objects from SQL Server system databases (master, model, msdb) to SQL script files. 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. Syntax Export-DbaSysDbUserObject [-SqlInstance] [[-SqlCredential] ] [-IncludeDependencies] [[-BatchSeparator] ] [[-Path] ] [[-FilePath] ] [-NoPrefix] [[-ScriptingOptionsObject] ] [-NoClobber] [-PassThru] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports any user objects that are in the system database to the default location PS C:\\> Export-DbaSysDbUserObject -SqlInstance server1 Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential) | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeDependencies Includes dependent objects in the scripted output when exporting user objects. Use this when your custom objects have dependencies that need to be recreated together on the target instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BatchSeparator Sets the batch separator used between SQL statements in the exported script files. Defaults to \"GO\". Change this when you need compatibility with specific SQL tools that use different batch separators. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | GO | -Path Specifies the directory where the exported SQL script file will be created. Uses the dbatools default export path if not specified. Provide this when you need the script saved to a specific location for documentation or deployment purposes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Specifies the complete file path including filename for the exported SQL script. Use this instead of Path when you need precise control over the output file name and location. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoPrefix Excludes header information from the exported scripts, removing creator details and timestamp comments. Use this when you need clean scripts without metadata for version control or when the header information is not needed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ScriptingOptionsObject Provides a custom ScriptingOptions object to control how objects are scripted, including permissions, indexes, and constraints. Use this when you need specific scripting behavior beyond the default options, such as excluding certain object properties. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoClobber Prevents overwriting existing files at the target location and throws an error if the file already exists. Use this as a safety measure when you want to avoid accidentally replacing existing script files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -PassThru Outputs the generated SQL scripts directly to the PowerShell console instead of saving to a file. Use this when you want to review the scripts immediately or pipe them to other cmdlets for further processing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String (when -PassThru is specified) Returns the generated T-SQL CREATE scripts as strings. One string per user-defined object discovered in the system databases. Each script includes a comment prefix (unless -NoPrefix is used) with generation timestamp, username, and dbatools version. Script sections are separated by the configured batch terminator (typically \"GO\"). System.IO.FileInfo (when -Path or -FilePath is specified) Returns one file object per system database that contains user-defined objects, representing the generated SQL script file(s) written to disk. Properties: Name: The filename of the exported script (e.g., \"server1-Export-DbaSysDbUserObject-master-20231215_143022.sql\") FullName: The complete path to the exported script file Directory: The directory object containing the file CreationTime: When the file was created LastWriteTime: When the file was last modified Length: Size of the file in bytes Extension: Always \".sql\" &nbsp;"
  },
  {
    "name": "Export-DbatoolsConfig",
    "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't been modified from defaults.",
    "category": "Migration",
    "tags": [
      "module"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbatoolsConfig",
    "popularityRank": 350,
    "synopsis": "Exports dbatools module configuration settings to a JSON file for backup or migration.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbatoolsConfig View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports dbatools module configuration settings to a JSON file for backup or migration. 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't been modified from defaults. Syntax Export-DbatoolsConfig -FullName [-OutPath] [-SkipUnchanged] [-EnableException] [ ] Export-DbatoolsConfig -Module [[-Name] ] [-OutPath] [-SkipUnchanged] [-EnableException] [ ] Export-DbatoolsConfig -Config [-OutPath] [-SkipUnchanged] [-EnableException] [ ] Export-DbatoolsConfig -ModuleName [-ModuleVersion ] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-SkipUnchanged] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports all current settings to json PS C:\\> Get-DbatoolsConfig | Export-DbatoolsConfig -OutPath '~/export.json' Example 2: Exports all settings of the module &#39;message&#39; that are no longer the original default values to json PS C:\\> Export-DbatoolsConfig -Module message -OutPath '~/export.json' -SkipUnchanged Required Parameters -FullName Specifies the complete configuration setting name to export, including the module prefix (e.g., 'dbatools.path.dbatoolsdata'). Use this when you need to export a specific configuration setting and know its exact full name. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Module Filters configuration settings to export only those belonging to a specific dbatools module (e.g., 'sql', 'path', 'message'). Use this when you want to export all settings related to a particular functional area of dbatools rather than individual settings. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Config Accepts configuration objects directly from Get-DbatoolsConfig for export to JSON. Use this when you want to filter or manipulate configuration objects before export, typically in pipeline operations. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -ModuleName Exports module-specific configuration settings to predefined system locations rather than a custom path. Only exports settings marked as 'ModuleExport' that have been modified from defaults, useful for creating standardized module configuration packages. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -OutPath Specifies the complete file path where the JSON configuration export will be saved, including the filename. The parent directory must exist or the export will fail, and any existing file at this location will be overwritten. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -Name Specifies a pattern to match configuration setting names within the selected module, supporting wildcards. Use this with the Module parameter to narrow down which settings to export when you don't need all settings from a module. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | * | -ModuleVersion Specifies the version number to include in the exported configuration filename when using ModuleName parameter. Defaults to 1 and helps track different versions of module configuration exports for change management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1 | -Scope Determines where to save module configuration files when using ModuleName parameter - user profile, shared location, or system-wide. Only file-based scopes are supported (registry scopes are blocked). Defaults to FileUserShared for cross-user accessibility. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | FileUserShared | -SkipUnchanged Excludes configuration settings that still have their original default values from the export. Use this to create smaller backup files containing only your customized settings, making configuration migration more focused. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs None This 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 parameter. File write operations are performed silently without pipeline output. &nbsp;"
  },
  {
    "name": "Export-DbaUser",
    "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).",
    "category": "Migration",
    "tags": [
      "user",
      "export"
    ],
    "verb": "Export",
    "popular": true,
    "url": "/Export-DbaUser",
    "popularityRank": 28,
    "synopsis": "Generates T-SQL scripts to recreate database users with their complete security context including roles and permissions",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaUser View Source Claudio Silva (@ClaudioESSilva) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates T-SQL scripts to recreate database users with their complete security context including roles and permissions 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. This 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. The 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). Syntax Export-DbaUser [[-SqlInstance] ] [[-InputObject] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-User] ] [[-DestinationVersion] ] [[-Path] ] [[-FilePath] ] [[-Encoding] ] [-NoClobber] [-Append] [-Passthru] [-Template] [-EnableException] [[-ScriptingOptionsObject] ] [-ExcludeGoBatchSeparator] [ ] &nbsp; Examples &nbsp; Example 1: Exports SQL for the users in server &quot;sql2005&quot; and writes them to the file &quot;C:\\temp\\sql2005-users.sql&quot; PS C:\\> Export-DbaUser -SqlInstance sql2005 -FilePath C:\\temp\\sql2005-users.sql Example 2: Authenticates to sqlserver2014a using SQL Authentication PS C:\\> Export-DbaUser -SqlInstance sqlserver2014a $scred -FilePath C:\\temp\\users.sql -Append Authenticates 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. Example 3: Exports ONLY users User1 and User2 from sqlserver2014a to the file C:\\temp\\users.sql PS C:\\> Export-DbaUser -SqlInstance sqlserver2014a -User User1, User2 -FilePath C:\\temp\\users.sql Example 4: Exports ONLY users User1 and User2 from sqlserver2014a to the folder C:\\temp PS C:\\> Export-DbaUser -SqlInstance sqlserver2014a -User User1, User2 -Path C:\\temp Exports ONLY users User1 and User2 from sqlserver2014a to the folder C:\\temp. One file per user will be generated Example 5: Exports user User1 from sqlserver2008 to the file C:\\temp\\users.sql with syntax to run on SQL Server 2016 PS C:\\> Export-DbaUser -SqlInstance sqlserver2008 -User User1 -FilePath C:\\temp\\users.sql -DestinationVersion SQLServer2016 Example 6: Exports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\\temp\\users.sql file PS C:\\> Export-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -FilePath C:\\temp\\users.sql Example 7: Exports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\\temp\\users.sql file PS C:\\> $options = New-DbaScriptingOption PS C:\\> $options.ScriptDrops = $false PS C:\\> $options.WithDependencies = $true PS C:\\> Export-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -FilePath C:\\temp\\users.sql -ScriptingOptionsObject $options Exports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\\temp\\users.sql file. It will not script drops but will script dependencies. Example 8: Exports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\\temp\\users.sql file without... PS C:\\> Export-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -FilePath C:\\temp\\users.sql -ExcludeGoBatchSeparator Exports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\\temp\\users.sql file without the 'GO' batch separator. Example 9: Exports user1 from database db1, replacing loginname and username with {templateLogin} and {templateUser}... PS C:\\> Export-DbaUser -SqlInstance sqlserver2008 -Database db1 -User user1 -Template -PassThru Exports user1 from database db1, replacing loginname and username with {templateLogin} and {templateUser} correspondingly. Optional Parameters -SqlInstance The target SQL Server instance or instances. SQL Server 2000 and above supported. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase for processing specific database collections. Use this in pipeline operations when you have pre-filtered database objects to process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to export users from. Accepts wildcards for pattern matching. Use this when you need to export users from specific databases instead of all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to exclude from user export operations. Accepts wildcards for pattern matching. Useful when exporting from most databases but need to skip system databases or specific application databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -User Exports only the specified database users by name. Accepts multiple user names. Use this when you need to export specific application users or service accounts rather than all database users. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationVersion Specifies the target SQL Server version for the generated T-SQL script syntax compatibility. Use this when migrating users to a different SQL Server version than the source database compatibility level. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this when organizing exported scripts by directory structure for different environments or applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FilePath Sets the complete file path for a single consolidated script containing all exported users. Use this when you need all user definitions in one file for batch deployment or version control. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -Encoding Sets the character encoding for the output T-SQL script file. Defaults to UTF8. Change this when you need to match specific encoding requirements for your deployment tools or source control systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UTF8 | | Accepted Values | ASCII,BigEndianUnicode,Byte,String,Unicode,UTF7,UTF8,Unknown | -NoClobber Prevents overwriting existing files during export operations. Use this safety feature when running exports to avoid accidentally replacing existing user scripts. | Property | Value | | --- | --- | | Alias | NoOverwrite | | Required | False | | Pipeline | false | | Default Value | False | -Append Adds the exported user scripts to the end of an existing file instead of creating a new file. Use this when consolidating user exports from multiple instances or databases into a single deployment script. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Passthru Returns the T-SQL script to the console instead of writing to a file. Use this for copying scripts to clipboard, reviewing output before saving, or integrating with other PowerShell operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Template Replaces actual usernames and login names with placeholders {templateUser} and {templateLogin} in the generated script. Use this when creating reusable deployment scripts that can be parameterized for different environments or applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ScriptingOptionsObject Provides a custom ScriptingOptions object to control detailed T-SQL generation behavior and formatting. Use this for advanced scenarios requiring specific scripting options beyond the standard Export-DbaUser parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeGoBatchSeparator Removes the 'GO' batch separator statements from the generated T-SQL script. Use this when the target deployment tool or application doesn't support batch separators or requires continuous T-SQL. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String (when -Passthru is specified) Returns the generated T-SQL script containing CREATE USER statements, role memberships, database permissions, and object-level permissions as raw text. System.IO.FileInfo (default) Returns 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 a single file (using -FilePath), returns one FileInfo object for that file. &nbsp;"
  },
  {
    "name": "Export-DbaXESession",
    "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.",
    "category": "Migration",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaXESession",
    "popularityRank": 442,
    "synopsis": "Generates T-SQL creation scripts for Extended Events sessions to files or console",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaXESession View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates T-SQL creation scripts for Extended Events sessions to files or console 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. Syntax Export-DbaXESession [[-SqlInstance] ] [[-SqlCredential] ] [[-InputObject] ] [[-Session] ] [[-Path] ] [[-FilePath] ] [[-Encoding] ] [-Passthru] [[-BatchSeparator] ] [-NoPrefix] [-NoClobber] [-Append] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports a script to create all Extended Events Sessions on sourceserver to the console Will include prefix... PS C:\\> Export-DbaXESession -SqlInstance sourceserver -Passthru Exports a script to create all Extended Events Sessions on sourceserver to the console Will include prefix information containing creator and datetime. and uses the default value for BatchSeparator value from configuration Formatting.BatchSeparator Example 2: Exports a script to create all Extended Events Sessions on sourceserver PS C:\\> Export-DbaXESession -SqlInstance sourceserver Exports 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 time and server name like Servername-YYYYMMDDhhmmss-sp_configure.sql Will include prefix information containing creator and datetime. and uses the default value for BatchSeparator value from configuration Formatting.BatchSeparator Example 3: Exports a script to create all Extended Events Sessions on sourceserver to the directory C:\\temp using the... PS C:\\> Export-DbaXESession -SqlInstance sourceserver -FilePath C:\\temp Exports 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 Will include prefix information containing creator and datetime. and uses the default value for BatchSeparator value from configuration Formatting.BatchSeparator Example 4: Exports a script to create all Extended Events Sessions on sourceserver to the file C:\\temp\\EEvents.sql PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Export-DbaXESession -SqlInstance sourceserver -SqlCredential $cred -FilePath C:\\temp\\EEvents.sql -BatchSeparator \"\" -NoPrefix -NoClobber Exports a script to create all Extended Events Sessions on sourceserver to the file C:\\temp\\EEvents.sql. Will exclude prefix information containing creator and datetime and does not include a BatchSeparator Will not overwrite file if it already exists Example 5: Exports a script to create all Extended Events Sessions for Server1 and Server2 using pipeline PS C:\\> 'Server1', 'Server2' | Export-DbaXESession -FilePath 'C:\\Temp\\EE.sql' -Append Exports a script to create all Extended Events Sessions for Server1 and Server2 using pipeline. Writes to a single file using the Append switch Example 6: Exports a script to create the System_Health Extended Events Sessions for Server1 and Server2 using pipeline PS C:\\> Get-DbaXESession -SqlInstance Server1, Server2 -Session system_health | Export-DbaXESession -Path 'C:\\Temp' Exports a script to create the System_Health Extended Events Sessions for Server1 and Server2 using pipeline. Write to the directory C:\\temp using the default name format of Servername-YYYYMMDDhhmmss-sp_configure.sql Will include prefix information containing creator and datetime. and uses the default value for BatchSeparator value from configuration Formatting.BatchSeparator Optional Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input. Server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -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 specific monitoring configurations rather than all sessions on the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 specific directory with consistent naming for multiple servers or scheduled exports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -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 must also use -Append to prevent data loss from overwriting. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -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't support Unicode. Use Unicode (UTF-16) if required by specific deployment tools or when working with non-Latin scripts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UTF8 | | Accepted Values | 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 PowerShell pipeline. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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't support them, or customize for specific deployment tools that require different separators. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Formatting.BatchSeparator') | -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 want to avoid unnecessary differences between exports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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't accidentally replace important script files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 comprehensive deployment scripts that include sessions from multiple SQL Server instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String (when -Passthru is specified or no output path is specified) Returns 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 configuration settings. System.IO.FileInfo (when -Path or -FilePath is specified) Returns 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 first session returns file information for that instance. &nbsp;"
  },
  {
    "name": "Export-DbaXESessionTemplate",
    "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.",
    "category": "Migration",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Export",
    "popular": false,
    "url": "/Export-DbaXESessionTemplate",
    "popularityRank": 637,
    "synopsis": "Exports Extended Events sessions as reusable XML templates for SSMS",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Export-DbaXESessionTemplate View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Exports Extended Events sessions as reusable XML templates for SSMS Description Converts existing Extended Events sessions into XML template files that can be imported and reused in SQL Server Management Studio. This lets you standardize XE session configurations across multiple environments without manually recreating session definitions. Templates are saved to the SSMS XEvent templates folder by default, making them immediately available in the SSMS template browser. Accepts sessions directly from SQL Server instances or from Get-DbaXESession pipeline output. Syntax Export-DbaXESessionTemplate [[-SqlInstance] ] [[-SqlCredential] ] [[-Session] ] [[-Path] ] [[-FilePath] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Exports an XESession XML Template for all Extended Event Sessions on sql2017 to the C:\\temp\\xe folder PS C:\\> Export-DbaXESessionTemplate -SqlInstance sql2017 -Path C:\\temp\\xe Example 2: Gets the system_health Extended Events Session from sql2017 and then exports as an XESession XML Template to... PS C:\\> Get-DbaXESession -SqlInstance sql2017 -Session system_health | Export-DbaXESessionTemplate -Path C:\\temp\\xe Gets the system_health Extended Events Session from sql2017 and then exports as an XESession XML Template to C:\\temp\\xe Optional Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Session Specifies which Extended Events sessions to export by name. Accepts wildcards for pattern matching. Use this to export specific sessions instead of all sessions on the instance. Common sessions include system_health, AlwaysOn_health, or custom monitoring sessions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Sets the directory where XML template files will be saved. Defaults to the SSMS XEvent Templates folder in your Documents. Templates saved to the default location appear automatically in SSMS under Templates > XEventTemplates for easy reuse. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \"$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. When 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. | Property | Value | | --- | --- | | Alias | OutFile,FileName | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Extended Events session objects from Get-DbaXESession pipeline input. Use this when you need to filter sessions first or when working with sessions from multiple instances in a single export operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns one FileInfo object per Extended Events session exported. Each object represents the XML template file that was created. Properties: Name: The filename of the exported XE session template (e.g., \"system_health.xml\") FullName: The complete path to the exported template file DirectoryName: The directory path where the template file was saved Extension: The file extension (\".xml\") Length: The size of the template file in bytes CreationTime: When the template file was created LastWriteTime: When the template file was last modified LastAccessTime: When the template file was last accessed Mode: File attributes and permissions (e.g., \"-a----\") &nbsp;"
  },
  {
    "name": "Find-DbaAgentJob",
    "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't 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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaAgentJob",
    "popularityRank": 191,
    "synopsis": "Searches and filters SQL Agent jobs across SQL Server instances using multiple criteria.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaAgentJob View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Searches and filters SQL Agent jobs across SQL Server instances using multiple criteria. 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't 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. Syntax Find-DbaAgentJob [-SqlInstance] [[-SqlCredential] ] [[-JobName] ] [[-ExcludeJobName] ] [[-StepName] ] [[-LastUsed] ] [-IsDisabled] [-IsFailed] [-IsNotScheduled] [-IsNoEmailNotification] [[-Category] ] [[-Owner] ] [[-Since] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all agent job(s) that have backup in the name PS C:\\> Find-DbaAgentJob -SqlInstance Dev01 -JobName backup Example 2: Returns all agent job(s) that are named exactly Mybackup PS C:\\> Find-DbaAgentJob -SqlInstance Dev01, Dev02 -JobName Mybackup Example 3: Returns all agent job(s) that have not ran in 10 days PS C:\\> Find-DbaAgentJob -SqlInstance Dev01 -LastUsed 10 Example 4: Returns all agent job(s) that are either disabled, have no email notification or don&#39;t have a schedule PS C:\\> Find-DbaAgentJob -SqlInstance Dev01 -IsDisabled -IsNoEmailNotification -IsNotScheduled Returns all agent job(s) that are either disabled, have no email notification or don't have a schedule. returned with detail Example 5: Finds all failed job then starts them PS C:\\> $servers | Find-DbaAgentJob -IsFailed | Start-DbaAgentJob Finds all failed job then starts them. Consider using a -WhatIf at the end of Start-DbaAgentJob to see what it'll do first Example 6: Returns all agent jobs that have not ran in the last 10 days ignoring jobs &quot;Yearly - RollUp Workload&quot; and... PS C:\\> Find-DbaAgentJob -SqlInstance Dev01 -LastUsed 10 -ExcludeJobName \"Yearly - RollUp Workload\", \"SMS - Notification\" Returns all agent jobs that have not ran in the last 10 days ignoring jobs \"Yearly - RollUp Workload\" and \"SMS - Notification\" Example 7: Returns all job/s on Dev01 that are in either category &quot;REPL-Distribution&quot; or &quot;REPL-Snapshot&quot; PS C:\\> Find-DbaAgentJob -SqlInstance Dev01 -Category \"REPL-Distribution\", \"REPL-Snapshot\" | Format-Table -AutoSize -Wrap Example 8: Returns all agent job(s) on Dev01 and Dev02 that have failed since July of 2016 (and still have history in... PS C:\\> Find-DbaAgentJob -SqlInstance Dev01, Dev02 -IsFailed -Since '2016-07-01 10:47:00' Returns all agent job(s) on Dev01 and Dev02 that have failed since July of 2016 (and still have history in msdb) Example 9: Queries CMS server to return all SQL instances in the Production folder and then list out all agent jobs that... PS C:\\> Get-DbaRegServer -SqlInstance CMSServer -Group Production | Find-DbaAgentJob -Disabled -IsNotScheduled | Format-Table -AutoSize -Wrap Queries 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. Example 10: Find-DbaAgentJob -SqlInstance $Instances -JobName backup -IsNotScheduled Returns all agent job(s) wiht... PS C:\\> $Instances = 'SQL2017N5','SQL2019N5','SQL2019N20','SQL2019N21','SQL2019N22' Find-DbaAgentJob -SqlInstance $Instances -JobName backup -IsNotScheduled Returns all agent job(s) wiht backup in the name, that don't have a schedule on 'SQL2017N5','SQL2019N5','SQL2019N20','SQL2019N21','SQL2019N22' Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -JobName Specifies agent job names to search for using exact matches or wildcard patterns. Supports wildcards like backup, MyJob, or ETL to find jobs with specific naming conventions. Useful when you need to focus on particular job types or troubleshoot specific processes. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJobName Excludes specific job names from the search results using exact name matches. Use this to filter out known good jobs when searching for problematic ones, like excluding maintenance jobs when looking for failed application jobs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StepName Searches for jobs containing steps with specific names or patterns. Supports wildcards to find jobs with steps like backup, index, or cleanup. Helpful when troubleshooting issues in multi-step jobs or finding jobs that perform specific operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LastUsed Finds jobs that haven't executed successfully in the specified number of days. Use this to identify stale or potentially broken jobs that may need attention. Common values are 7, 30, or 90 days depending on job frequency and business requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -IsDisabled Finds all jobs with disabled status (not scheduled to run automatically). Use this during maintenance windows to identify jobs that were disabled for troubleshooting or may have been forgotten after maintenance. | Property | Value | | --- | --- | | Alias | Disabled | | Required | False | | Pipeline | false | | Default Value | False | -IsFailed Finds jobs where the last execution resulted in a failure status. Essential for daily health checks and identifying jobs that need immediate attention. Combine with Since parameter to focus on recent failures or look at historical patterns. | Property | Value | | --- | --- | | Alias | Failed | | Required | False | | Pipeline | false | | Default Value | False | -IsNotScheduled Finds jobs that exist but have no schedule defined (manual execution only). Useful for identifying orphaned jobs, temporary jobs that should be cleaned up, or jobs awaiting proper scheduling configuration. | Property | Value | | --- | --- | | Alias | NoSchedule | | Required | False | | Pipeline | false | | Default Value | False | -IsNoEmailNotification Finds jobs that lack email notification setup for failures or completion. Important for ensuring critical jobs will alert DBAs when they fail. Use this during compliance audits or when establishing monitoring standards. | Property | Value | | --- | --- | | Alias | NoEmailNotification | | Required | False | | Pipeline | false | | Default Value | False | -Category Filters jobs by their assigned categories such as 'Database Maintenance', 'REPL-Distribution', or custom categories. Useful for focusing on specific types of jobs like replication jobs, maintenance tasks, or application-specific processes. Categories help organize and manage jobs in environments with many different job types. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Owner Filters jobs by their owner login name, or excludes jobs by prefixing with a dash (-). Use 'DOMAIN\\\\User' to find jobs owned by specific accounts, or '-sa' to exclude sa-owned jobs. Helpful for security audits, identifying jobs that may need ownership changes, or finding jobs created by specific users. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Since Limits results to jobs that last ran on or after the specified date and time. Use with IsFailed to find jobs that failed since a specific incident, or combine with other filters to focus on recent activity. Accepts standard datetime formats like '2023-01-01' or '2023-01-01 14:30:00'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Job Returns one Job object for each job that matches the specified search criteria. Multiple jobs can be returned per instance depending on filter parameters. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Job name Category: Job category classification OwnerLoginName: Login name of the job owner CurrentRunStatus: Current execution status (Idle, Running, etc.) CurrentRunRetryAttempt: Number of retry attempts for current execution Enabled: Boolean indicating if the job is enabled (aliased from IsEnabled) LastRunDate: DateTime of the most recent job execution LastRunOutcome: Outcome of the last execution (Succeeded, Failed, Cancelled, etc.) DateCreated: DateTime when the job was created HasSchedule: Boolean indicating if the job has a schedule assigned OperatorToEmail: Email operator name for notifications CreateDate: DateTime when the job was created (aliased from DateCreated) Additional properties available (from SMO Job object): JobId: Unique identifier for the job (GUID) IsEnabled: Boolean indicating if the job is enabled and can be scheduled JobType: Type of job (Local or MultiServer) Category: Job category name CategoryID: Numeric category identifier Owner: Job owner name OwnerLoginName: Login name of the job owner Description: Job description text StartStepID: ID of the first step to execute EventLogLevel: Event log level for job events (OnSuccess, OnFailure, Always, Never) EmailLevel: Email notification level (OnSuccess, OnFailure, OnCompletion, Never) NetsendLevel: NetSend notification level (OnSuccess, OnFailure, OnCompletion, Never) PageLevel: Pager notification level (OnSuccess, OnFailure, OnCompletion, Never) OperatorToNetSend: Operator name for NetSend notifications OperatorToPage: Operator name for pager notifications LastRunDuration: Duration of last run in seconds NextRunDate: DateTime when the job is scheduled to run next DateModified: DateTime when the job was last modified HasSchedule: Boolean indicating if the job has a schedule IsRunnable: Boolean indicating if the job can be executed Parent: Reference to parent JobServer SMO object All properties from the base SMO Job object are accessible even though only default properties are displayed without using Select-Object . &nbsp;"
  },
  {
    "name": "Find-DbaBackup",
    "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's retention requirements.",
    "category": "Backup & Restore",
    "tags": [
      "backup",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaBackup",
    "popularityRank": 190,
    "synopsis": "Searches filesystem directories for SQL Server backup files based on age and extension criteria.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaBackup View Source Chris Sommer (@cjsommer), www.cjsommer.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Searches filesystem directories for SQL Server backup files based on age and extension criteria. 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. This 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. Commonly used in automated maintenance scripts to identify backup files ready for deletion based on your organization's retention requirements. Syntax Find-DbaBackup [-Path] [-BackupFileExtension] [-RetentionPeriod] [-CheckArchiveBit] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Searches for all trn files in C:\\MSSQL\\SQL Backup\\ and all subdirectories that are more than 48 hours old... PS C:\\> Find-DbaBackup -Path 'C:\\MSSQL\\SQL Backup\\' -BackupFileExtension trn -RetentionPeriod 48h Searches for all trn files in C:\\MSSQL\\SQL Backup\\ and all subdirectories that are more than 48 hours old will be included. Example 2: Searches for all bak files in C:\\MSSQL\\Backup\\ and all subdirectories that are more than 7 days old will be... PS C:\\> Find-DbaBackup -Path 'C:\\MSSQL\\Backup\\' -BackupFileExtension bak -RetentionPeriod 7d -CheckArchiveBit Searches 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 checking the Archive bit. Example 3: Searches for all bak files in \\\\SQL2014\\Backup\\ and all subdirectories that are more than 24 hours old and... PS C:\\> Find-DbaBackup -Path '\\\\SQL2014\\Backup\\' -BackupFileExtension bak -RetentionPeriod 24h | Remove-Item -Verbose Searches 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. Required Parameters -Path Specifies the root directory path to recursively search for backup files. Searches all subdirectories within this path. Use this to target specific backup locations like dedicated backup drives or network shares where your SQL Server backups are stored. | Property | Value | | --- | --- | | Alias | BackupFolder | | Required | True | | Pipeline | false | | Default Value | | -BackupFileExtension Specifies the file extension to search for without the period (e.g., 'bak', 'trn', 'dif', 'log'). Use 'bak' for full backups, 'trn' or 'log' for transaction log backups, or 'dif' for differential backups depending on which backup type you need to manage. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -RetentionPeriod Specifies how old backup files must be before they're included in results, using format like '7d' or '48h'. Files older than this period will be returned, making this essential for backup cleanup operations based on your retention policy. Valid units: h (hours), d (days), w (weeks), m (months). Examples: '48h', '7d', '4w', '1m'. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -CheckArchiveBit Only includes backup files that have been archived to another location (Archive bit is not set). Use this safety feature to ensure backups have been copied to tape, cloud storage, or other backup systems before cleanup to prevent accidental data loss. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns one file object for each backup file found in the specified directory and subdirectories that meets the age and archive bit criteria. Properties: FullName: The complete path to the backup file Name: The file name including extension Extension: The file extension (e.g., .bak, .trn, .dif, .log) DirectoryName: The directory containing the file Length: The file size in bytes LastWriteTime: The timestamp when the file was last modified, used to determine if it meets the retention period Attributes: File attributes including the Archive bit status (checked when -CheckArchiveBit is specified) CreationTime: The timestamp when the file was created LastAccessTime: The timestamp when the file was last accessed These file objects are suitable for piping to Remove-Item or other file management cmdlets for automated cleanup workflows. &nbsp;"
  },
  {
    "name": "Find-DbaCommand",
    "description": "Finds dbatools commands searching through the inline help text, building a consolidated json index and querying it because Get-Help is too slow",
    "category": "Utilities",
    "tags": [
      "module",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaCommand",
    "popularityRank": 253,
    "synopsis": "Finds dbatools commands searching through the inline help text",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaCommand View Source Simone Bizzotto (@niphlod) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Finds dbatools commands searching through the inline help text Description Finds dbatools commands searching through the inline help text, building a consolidated json index and querying it because Get-Help is too slow Syntax Find-DbaCommand [[-Pattern] ] [[-Tag] ] [[-Author] ] [[-MinimumVersion] ] [[-MaximumVersion] ] [-Rebuild] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: For lazy typers: finds all commands searching the entire help for &quot;snapshot&quot; PS C:\\> Find-DbaCommand \"snapshot\" Example 2: For rigorous typers: finds all commands searching the entire help for &quot;snapshot&quot; PS C:\\> Find-DbaCommand -Pattern \"snapshot\" Example 3: Finds all commands tagged with &quot;Job&quot; PS C:\\> Find-DbaCommand -Tag Job Example 4: Finds all commands tagged with BOTH &quot;Job&quot; and &quot;Owner&quot; PS C:\\> Find-DbaCommand -Tag Job,Owner Example 5: Finds every command whose author contains our beloved &quot;Chrissy&quot; PS C:\\> Find-DbaCommand -Author Chrissy Example 6: Finds every command whose author contains our beloved &quot;Chrissy&quot; and it tagged as &quot;AG&quot; PS C:\\> Find-DbaCommand -Author Chrissy -Tag AG Example 7: Finds all commands searching the entire help for &quot;snapshot&quot;, rebuilding the index (good for developers) PS C:\\> Find-DbaCommand -Pattern snapshot -Rebuild Optional Parameters -Pattern Searches all help text properties (synopsis, description, examples, parameters) for the specified text pattern using wildcard matching. Use this for broad searches when you know a concept or term but aren't sure which specific commands handle it. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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\". Use this when you need to find commands related to specific SQL Server functionality. Multiple tags require commands to have ALL specified tags. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Author Filters results to show commands created by authors whose name contains the specified text. Uses wildcard matching so partial names work. Useful when you want to find commands written by a specific contributor or when following up on recommendations from particular experts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MinimumVersion Filters results to show only commands that require the specified minimum version of dbatools or higher. Use this to ensure compatibility when working with older dbatools installations or when checking what features require recent updates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaximumVersion Filters results to show only commands that work with the specified maximum version of dbatools or lower. Helpful when working with legacy environments where you need to avoid commands that require newer dbatools versions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when developing new commands, after updating dbatools, or when search results seem outdated or incomplete. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Displays what would happen if the command is run | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Confirms overwrite of index | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per dbatools command matching the specified filters. Default display properties (via Select-DefaultView): CommandName: The name of the dbatools command Synopsis: A brief one-line description of what the command does *Additional properties available (use Select-Object to see all):* Name: The full name of the command function Availability: Platform availability (Windows, Linux, macOS or Windows only) Alias: Comma-separated list of command aliases Description: Detailed description of the command's functionality Examples: Full examples section from the command's help text Links: Related documentation links Syntax: Complete syntax information for the command Tags: Array of tags categorizing the command by feature area (Backup, AG, Job, Security, etc.) Author: Name(s) of the command author(s) MinimumVersion: Minimum dbatools version required to use this command MaximumVersion: Maximum dbatools version supported by this command Params: Array of parameter information (name, description, aliases, required status, pipeline support, default values, accepted values) All properties from the full command help index are accessible. Use Select-Object to display all available properties for further analysis. &nbsp;"
  },
  {
    "name": "Find-DbaDatabase",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaDatabase",
    "popularityRank": 93,
    "synopsis": "Searches multiple SQL Server instances for databases matching name, owner, or Service Broker GUID patterns",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaDatabase View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Searches multiple SQL Server instances for databases matching name, owner, or Service Broker GUID patterns 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. This 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. Service 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. Syntax Find-DbaDatabase [-SqlInstance] [[-SqlCredential] ] [[-Property] ] [-Pattern] [-Exact] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all database from the SqlInstances that have a database with Report in the name PS C:\\> Find-DbaDatabase -SqlInstance \"DEV01\", \"DEV02\", \"UAT01\", \"UAT02\", \"PROD01\", \"PROD02\" -Pattern Report Example 2: Returns all database from the SqlInstances that have a database named TestDB with a detailed output PS C:\\> Find-DbaDatabase -SqlInstance \"DEV01\", \"DEV02\", \"UAT01\", \"UAT02\", \"PROD01\", \"PROD02\" -Pattern TestDB -Exact | Select-Object Example 3: Returns all database from the SqlInstances that have the same Service Broker GUID with a detailed output PS C:\\> Find-DbaDatabase -SqlInstance \"DEV01\", \"DEV02\", \"UAT01\", \"UAT02\", \"PROD01\", \"PROD02\" -Property ServiceBrokerGuid -Pattern '-faeb-495a-9898-f25a782835f5' | Select-Object Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Pattern The search value to match against the specified property. Supports regular expressions for flexible pattern matching. Use simple strings like 'Sales' or 'Test', or regex patterns like '^prod.*db$' to match databases starting with 'prod' and ending with 'db'. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Property Specifies which database property to search against: Name, Owner, or ServiceBrokerGuid. Defaults to Name for database name searches. Use Owner when tracking down databases by their owner for security audits, or ServiceBrokerGuid when identifying databases with matching Service Broker configurations across environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Name | | Accepted Values | Name,ServiceBrokerGuid,Owner | -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. Particularly useful when searching for database names that contain regex special characters or when you want precise matches without wildcards. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database matching the search criteria. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The database name Id: The database ID Size: The database size in megabytes (dbasize object for formatting) Owner: The database owner login CreateDate: DateTime when the database was created ServiceBrokerGuid: The Service Broker GUID for the database (useful for identifying mismatched GUIDs after restore operations) Tables: Count of user-defined tables in the database StoredProcedures: Count of user-defined stored procedures in the database Views: Count of user-defined views in the database ExtendedProperties: Array of PSCustomObjects containing extended properties (each with Name and Value properties), or 0 if no extended properties exist &nbsp;"
  },
  {
    "name": "Find-DbaDbDisabledIndex",
    "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't 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.",
    "category": "Utilities",
    "tags": [
      "index",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaDbDisabledIndex",
    "popularityRank": 505,
    "synopsis": "Identifies disabled indexes across SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaDbDisabledIndex View Source Jason Squires, sqlnotnull.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies disabled indexes across SQL Server 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't 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. Syntax Find-DbaDbDisabledIndex [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-NoClobber] [-Append] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Generates the SQL statements to drop the selected disabled indexes on server &quot;sql2005&quot; PS C:\\> Find-DbaDbDisabledIndex -SqlInstance sql2005 Example 2: Generates the SQL statements to drop the selected disabled indexes on server &quot;sqlserver2016&quot;, using SQL... PS C:\\> Find-DbaDbDisabledIndex -SqlInstance sqlserver2016 -SqlCredential $cred Generates the SQL statements to drop the selected disabled indexes on server \"sqlserver2016\", using SQL Authentication to connect to the database. Example 3: Generates the SQL Statement to drop selected indexes in databases db1 &amp; db2 on server &quot;sqlserver2016&quot; PS C:\\> Find-DbaDbDisabledIndex -SqlInstance sqlserver2016 -Database db1, db2 Example 4: Generates the SQL statements to drop selected indexes on all user databases PS C:\\> Find-DbaDbDisabledIndex -SqlInstance sqlserver2016 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for disabled indexes. Accepts multiple database names and supports wildcards. When not specified, all accessible user databases on the instance will be scanned. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Accepts multiple database names to exclude from the operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoClobber Prevents overwriting existing output files when used with file export functionality. Note: This parameter is currently not implemented in the function logic. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Append Appends results to existing output files instead of overwriting them when used with file export functionality. Note: This parameter is currently not implemented in the function logic. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.Data.DataRow Returns one data row per disabled index found in the scanned databases. Properties: DatabaseName: The name of the database containing the disabled index DatabaseId: The numeric ID of the database in SQL Server SchemaName: The schema name where the table containing the index resides TableName: The name of the table that contains the disabled index ObjectId: The numeric ID of the table object in SQL Server IndexName: The name of the disabled index IndexId: The numeric ID of the index within the table (0 = clustered index, 1+ = nonclustered indexes) TypeDesc: The type of index (e.g., CLUSTERED, NONCLUSTERED, HEAP, SPATIAL, etc.) &nbsp;"
  },
  {
    "name": "Find-DbaDbDuplicateIndex",
    "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+)",
    "category": "Utilities",
    "tags": [
      "index",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaDbDuplicateIndex",
    "popularityRank": 290,
    "synopsis": "Identifies duplicate and overlapping indexes that waste storage space and degrade insert performance",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaDbDuplicateIndex View Source Claudio Silva (@ClaudioESSilva) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies duplicate and overlapping indexes that waste storage space and degrade insert performance 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. Use 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. Supports 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. Output includes: TableName, IndexName, KeyColumns, IncludedColumns, IndexSizeMB, IndexType, CompressionDescription (2008+), RowCount, IsDisabled, IsFiltered (2008+) Syntax Find-DbaDbDuplicateIndex [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [-IncludeOverlapping] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns duplicate indexes found on sql2005 PS C:\\> Find-DbaDbDuplicateIndex -SqlInstance sql2005 Example 2: Finds exact duplicate indexes on all user databases present on sql2017, using SQL authentication PS C:\\> Find-DbaDbDuplicateIndex -SqlInstance sql2017 -SqlCredential sqladmin Example 3: Finds exact duplicate indexes on the db1 and db2 databases PS C:\\> Find-DbaDbDuplicateIndex -SqlInstance sql2017 -Database db1, db2 Example 4: Finds both duplicate and overlapping indexes on all user databases PS C:\\> Find-DbaDbDuplicateIndex -SqlInstance sql2017 -IncludeOverlapping Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for duplicate indexes. Accepts wildcards for pattern matching. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeOverlapping Finds indexes that share some key columns but have different column structures, not just exact duplicates. Use this to identify indexes where one might be redundant because it's covered by another with additional columns. For example, an index on (CustomerID) would be flagged as overlapping with an index on (CustomerID, OrderDate). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 objects are returned). Properties: DatabaseName: Name of the database containing the index TableName: Name of the table containing the index (schema.table format) IndexName: Name of the index KeyColumns: Comma-separated list of key columns with sort direction (ASC/DESC) IncludedColumns: Comma-separated list of included columns with sort direction (empty if none) IndexType: Type of index (CLUSTERED or NONCLUSTERED) IndexSizeMB: Size of the index in megabytes (Decimal) RowCount: Number of rows in the table (Integer) IsDisabled: Boolean indicating if the index is disabled IsUnique: Boolean indicating if the index is unique IsFiltered: Boolean indicating if the index has a filter condition (SQL Server 2008+) CompressionDescription: Data compression type applied to the index - NONE, ROW, or PAGE (SQL Server 2008+) The function returns different property sets based on the target SQL Server version: SQL Server 2005: Excludes IsFiltered and CompressionDescription properties SQL Server 2008+: Includes all properties including IsFiltered and CompressionDescription &nbsp;"
  },
  {
    "name": "Find-DbaDbGrowthEvent",
    "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't 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",
    "category": "Database Operations",
    "tags": [
      "autogrow",
      "database",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaDbGrowthEvent",
    "popularityRank": 308,
    "synopsis": "Retrieves database auto-growth and auto-shrink events from the SQL Server Default Trace",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaDbGrowthEvent View Source Aaron Nelson Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database auto-growth and auto-shrink events from the SQL Server Default Trace 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't have to manually parse trace files or write custom T-SQL queries. The following events are included: 92 - Data File Auto Grow 93 - Log File Auto Grow 94 - Data File Auto Shrink 95 - Log File Auto Shrink Syntax Find-DbaDbGrowthEvent [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-EventType] ] [[-FileType] ] [-UseLocalTime] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns any database AutoGrow events in the Default Trace with UTC time for the instance for every database... PS C:\\> Find-DbaDbGrowthEvent -SqlInstance localhost Returns any database AutoGrow events in the Default Trace with UTC time for the instance for every database on the localhost instance. Example 2: Returns any database AutoGrow events in the Default Trace with the local time of the instance for every... PS C:\\> Find-DbaDbGrowthEvent -SqlInstance localhost -UseLocalTime Returns any database AutoGrow events in the Default Trace with the local time of the instance for every database on the localhost instance. Example 3: Returns any database AutoGrow events in the Default Traces for every database on ServerA\\sql2016 &amp;... PS C:\\> Find-DbaDbGrowthEvent -SqlInstance ServerA\\SQL2016, ServerA\\SQL2014 Returns any database AutoGrow events in the Default Traces for every database on ServerA\\sql2016 & ServerA\\SQL2014. Example 4: Returns any database AutoGrow events in the Default Trace for every database on the ServerA\\SQL2016 instance... PS C:\\> Find-DbaDbGrowthEvent -SqlInstance ServerA\\SQL2016 | Format-Table -AutoSize -Wrap Returns any database AutoGrow events in the Default Trace for every database on the ServerA\\SQL2016 instance in a table format. Example 5: Returns any database Auto Shrink events in the Default Trace for every database on the ServerA\\SQL2016... PS C:\\> Find-DbaDbGrowthEvent -SqlInstance ServerA\\SQL2016 -EventType Shrink Returns any database Auto Shrink events in the Default Trace for every database on the ServerA\\SQL2016 instance. Example 6: Returns any database Auto Growth events on data files in the Default Trace for every database on the... PS C:\\> Find-DbaDbGrowthEvent -SqlInstance ServerA\\SQL2016 -EventType Growth -FileType Data Returns any database Auto Growth events on data files in the Default Trace for every database on the ServerA\\SQL2016 instance. Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for growth events. Accepts wildcards for pattern matching. Use this to focus on specific databases when investigating growth patterns or troubleshooting performance issues. If not specified, searches all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specified databases from the growth event search. Accepts wildcards for pattern matching. Useful when you want to skip system databases like tempdb or exclude databases with known frequent growth events. Commonly used with tempdb, master, model, and msdb to focus on user databases only. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EventType Filters results to show only specific types of database size change events. Use 'Growth' to identify when files expanded automatically, which can indicate undersized initial allocations or unexpected data volume increases. Use 'Shrink' to find auto-shrink events that may be causing performance problems due to file fragmentation. Allowed values: Growth, Shrink | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Growth,Shrink | -FileType Filters results to show only data file or log file growth events. Use 'Data' when investigating storage capacity issues or unexpected table growth patterns. Use 'Log' when troubleshooting transaction log growth, often caused by long-running transactions or delayed log backups. Allowed values: Data, Log | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Data,Log | -UseLocalTime Returns timestamps in the SQL Server instance's local time zone instead of converting to UTC. Use this when correlating growth events with local application schedules, maintenance windows, or business hours. By default, times are converted to UTC for consistency across multiple time zones. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name where the SQL Server instance is running InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) 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) DatabaseName: The name of the database that experienced the growth/shrink event Filename: The path and name of the database file that was resized Duration: The duration of the event in milliseconds StartTime: The date and time when the event started (UTC by default, local time if -UseLocalTime is specified) EndTime: The date and time when the event ended (UTC by default, local time if -UseLocalTime is specified) ChangeInSize: The size change during the event in megabytes (MB) ApplicationName: The application that triggered the growth event HostName: The host name of the client that triggered the event *Additional properties available (accessible with Select-Object ):** DatabaseId: The numeric database identifier from sys.databases SessionLoginName: The SQL login name of the session that triggered the event SPID: The SQL Server session ID (SPID) of the process that caused the event OrderRank: Internal ranking value used for trace file rotation ordering &nbsp;"
  },
  {
    "name": "Find-DbaDbUnusedIndex",
    "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.",
    "category": "Utilities",
    "tags": [
      "index",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaDbUnusedIndex",
    "popularityRank": 224,
    "synopsis": "Identifies database indexes with low usage statistics that may be candidates for removal",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaDbUnusedIndex View Source Aaron Nelson (@SQLvariant), SQLvariant.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies database indexes with low usage statistics that may be candidates for removal 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. This 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. Supports 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. Syntax Find-DbaDbUnusedIndex [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-IgnoreUptime] [[-Seeks] ] [[-Scans] ] [[-Lookups] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Finds unused indexes on db1 and db2 on sql2016 PS C:\\> Find-DbaDbUnusedIndex -SqlInstance sql2016 -Database db1, db2 Example 2: Finds unused indexes on db1 and db2 on sql2016 using SQL Authentication to connect to the server PS C:\\> Find-DbaDbUnusedIndex -SqlInstance sql2016 -SqlCredential $cred Example 3: Finds unused indexes on all databases on sql2016 PS C:\\> Get-DbaDatabase -SqlInstance sql2016 | Find-DbaDbUnusedIndex Example 4: Finds &#39;unused&#39; indexes with user_seeks &lt; 10, user_scans &lt; 100, and user_lookups &lt; 1000 on all databases on... PS C:\\> Get-DbaDatabase -SqlInstance sql2019 | Find-DbaDbUnusedIndex -Seeks 10 -Scans 100 -Lookups 1000 Finds 'unused' indexes with user_seeks Optional Parameters -SqlInstance The SQL Server you want to check for unused indexes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for unused indexes. Accepts wildcards for pattern matching. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the unused index analysis. Accepts wildcards for pattern matching. Commonly used to skip system databases, read-only databases, or databases undergoing maintenance that shouldn't be modified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IgnoreUptime Bypasses the 7-day uptime check that normally prevents analysis on recently restarted instances. Use this when you need results from a server with recent restarts, but be aware that usage statistics may not reflect normal workload patterns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Seeks Sets the threshold for user seeks below which an index is considered unused. Default is 1. User 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1 | -Scans Sets the threshold for user scans below which an index is considered unused. Default is 1. User 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1 | -Lookups Sets the threshold for user lookups below which an index is considered unused. Default is 1. User 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1 | -InputObject Accepts database objects from Get-DbaDatabase for pipeline operations. This allows you to chain commands and apply complex database filtering logic before analyzing unused indexes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per unused index found. Each object contains comprehensive index usage statistics and metadata. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the index DatabaseId: Numeric ID of the database Schema: The schema name containing the table Table: The name of the table containing the index ObjectId: Numeric ID of the table object IndexName: The name of the index IndexId: Numeric ID of the index within the table TypeDesc: Type description of the index (CLUSTERED, NONCLUSTERED, etc.) UserSeeks: Number of seek operations by user queries since last SQL Server restart UserScans: Number of scan operations by user queries since last SQL Server restart UserLookups: Number of lookup operations by user queries since last SQL Server restart UserUpdates: Number of update operations on the index by user queries since last SQL Server restart LastUserSeek: Timestamp of the last seek operation by user queries LastUserScan: Timestamp of the last scan operation by user queries LastUserLookup: Timestamp of the last lookup operation by user queries LastUserUpdate: Timestamp of the last update operation by user queries SystemSeeks: Number of seek operations by system queries since last SQL Server restart SystemScans: Number of scan operations by system queries since last SQL Server restart SystemLookup: Number of lookup operations by system queries since last SQL Server restart SystemUpdates: Number of update operations on the index by system queries since last SQL Server restart LastSystemSeek: Timestamp of the last seek operation by system queries LastSystemScan: Timestamp of the last scan operation by system queries LastSystemLookup: Timestamp of the last lookup operation by system queries LastSystemUpdate: Timestamp of the last update operation by system queries IndexSizeMB: Size of the index in megabytes RowCount: Number of rows in the index CompressionDescription: Data compression type (SQL Server 2008+ only). Values include None, Row, Page, ColumnStore, or ColumnStoreArchive Indexes are identified as \"unused\" when their usage statistics fall below the specified thresholds (default: UserSeeks < 1, UserScans < 1, UserLookups < 1). &nbsp;"
  },
  {
    "name": "Find-DbaInstance",
    "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.",
    "category": "Server Management",
    "tags": [
      "instance",
      "connect",
      "sqlserver",
      "lookup"
    ],
    "verb": "Find",
    "popular": true,
    "url": "/Find-DbaInstance",
    "popularityRank": 24,
    "synopsis": "Discovers SQL Server instances across networks using multiple scanning methods",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaInstance View Source Scott Sutherland, 2018 NetSPI , Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Discovers SQL Server instances across networks using multiple scanning methods 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. The function combines two distinct phases to systematically locate SQL Server instances: Discovery Phase: Compiles 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). You can specify explicit computer lists via -ComputerName or use automated discovery via -DiscoveryType. Scan Phase: Tests 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. Results include confidence levels (High/Medium/Low) based on scan success combinations. Common DBA scenarios: Audit all SQL instances before migrations or compliance reviews Discover shadow IT databases that bypass standard deployment processes Inventory instances across acquired companies or merged networks Validate disaster recovery documentation against actual running instances Identify instances running on non-standard ports or with unusual configurations Security considerations: The 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. Syntax Find-DbaInstance [-Credential ] [-SqlCredential ] [-ScanType {TCPPort | SqlConnect | SqlService | DNSResolve | SPN | Browser | Ping | Default | All}] [-DomainController ] [-TCPPort ] [-MinimumConfidence {None | Low | Medium | High}] [-EnableException] [ ] Find-DbaInstance -ComputerName [-Credential ] [-SqlCredential ] [-ScanType {TCPPort | SqlConnect | SqlService | DNSResolve | SPN | Browser | Ping | Default | All}] [-DomainController ] [-TCPPort ] [-MinimumConfidence {None | Low | Medium | High}] [-EnableException] [ ] Find-DbaInstance -DiscoveryType {IPRange | DomainSPN | Domain | DataSourceEnumeration | DomainServer | All} [-Credential ] [-SqlCredential ] [-ScanType {TCPPort | SqlConnect | SqlService | DNSResolve | SPN | Browser | Ping | Default | All}] [-IpAddress ] [-DomainController ] [-TCPPort ] [-MinimumConfidence {None | Low | Medium | High}] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Performs a network search for SQL Instances by: - Looking up the Service Principal Names of computers in... PS C:\\> Find-DbaInstance -DiscoveryType Domain, DataSourceEnumeration Performs a network search for SQL Instances by: Looking up the Service Principal Names of computers in Active Directory Using the UDP broadcast based auto-discovery of SSMS After that it will extensively scan all hosts thus discovered for instances. Example 2: Performs a network search for SQL Instances, using all discovery protocols: - Active directory search for... PS C:\\> Find-DbaInstance -DiscoveryType All Performs a network search for SQL Instances, using all discovery protocols: Active directory search for Service Principal Names SQL Instance Enumeration (same as SSMS does) All IPAddresses in the current computer's subnets of all connected network interfaces Note: This scan will take a long time, due to including the IP Scan Example 3: Scans all computers in the domain for SQL Instances, using a deep probe: - Tries resolving the name in DNS... PS C:\\> Get-ADComputer -Filter \"*\" | Find-DbaInstance Scans all computers in the domain for SQL Instances, using a deep probe: Tries resolving the name in DNS Tries pinging the computer Tries listing all SQL Services using CIM/WMI Tries discovering all instances via the browser service Tries connecting to the default TCP Port (1433) Tries connecting to the TCP port of each discovered instance Tries to establish a SQL connection to the server using default windows credentials Tries looking up the Service Principal Names for each instance Example 4: Reads all servers from the servers.txt file (one server per line), then scans each of them for instances... PS C:\\> Get-Content .\\servers.txt | Find-DbaInstance -SqlCredential $cred -ScanType Browser, SqlConnect Reads all servers from the servers.txt file (one server per line), then scans each of them for instances using the browser service and finally attempts to connect to each instance found using the specified credentials. then scans each of them for instances using the browser service and SqlService Example 5: Scans localhost for instances using the browser service, traverses all instances for all databases and... PS C:\\> Find-DbaInstance -ComputerName localhost | Get-DbaDatabase | Format-Table -Wrap Scans localhost for instances using the browser service, traverses all instances for all databases and displays all information in a formatted table. Example 6: Scans localhost for instances using the browser service, traverses all instances for all databases and... PS C:\\> $databases = Find-DbaInstance -ComputerName localhost | Get-DbaDatabase PS C:\\> $results = $databases | Select-Object SqlInstance, Name, Status, RecoveryModel, SizeMB, Compatibility, Owner, LastFullBackup, LastDiffBackup, LastLogBackup PS C:\\> $results | Format-Table -Wrap Scans 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. Using this method regularly is not recommended. Use Get-DbaService or Get-DbaRegServer instead. Required Parameters -ComputerName Specifies target computers to scan for SQL Server instances. Accepts computer names, IP addresses, or output from Get-ADComputer. Use this when you have a specific list of servers to inventory rather than performing network-wide discovery. Only the computer name portion is used - connection strings or SQL instance details are ignored. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -DiscoveryType Specifies which automatic discovery methods to use for finding SQL Server targets across your network. Choose discovery methods based on your environment: DomainSPN for registered services, DataSourceEnumeration for broadcasting instances, IPRange for subnet scanning, or DomainServer for all Windows servers. Combine multiple types for comprehensive coverage, but be aware that IPRange scanning can be time-intensive on large networks. --- SPN Lookup The function tries to connect active directory to look up all computers with registered SQL Instances. Not all instances need to be registered properly, making this not 100% reliable. By default, your nearest Domain Controller is contacted for this scan. However it is possible to explicitly state the DC to contact using its DistinguishedName and the '-DomainController' parameter. If credentials were specified using the '-Credential' parameter, those same credentials are used to perform this lookup, allowing the scan of other domains. SQL Instance Enumeration This uses the default UDP Broadcast based instance enumeration used by SSMS to detect instances. Note that the result from this is not used in the actual scan, but only to compile a list of computers to scan. To enable the same results for the scan, ensure that the 'Browser' scan is enabled. IP Address range: This 'Discovery' uses a range of IPAddresses and simply passes them on to be tested. See the 'Description' part of help on security issues of network scanning. By default, it will enumerate all ethernet network adapters on the local computer and scan the entire subnet they are on. By using the '-IpAddress' parameter, custom network ranges can be specified. Domain Server: This will discover every single computer in Active Directory that is a Windows Server and enabled. By default, your nearest Domain Controller is contacted for this scan. However it is possible to explicitly state the DC to contact using its DistinguishedName and the '-DomainController' parameter. If credentials were specified using the '-Credential' parameter, those same credentials are used to perform this lookup, allowing the scan of other domains. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -Credential The credentials to use on windows network connection. These credentials are used for: Contact to domain controllers for SPN lookups (only if explicit Domain Controller is specified) CIM/WMI contact to the scanned computers during the scan phase (see the '-ScanType' parameter documentation on affected scans). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential The credentials used to connect to SqlInstances to during the scan phase. See the '-ScanType' parameter documentation on affected scans. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ScanType Controls which verification methods are used to detect and validate SQL Server instances on target computers. Use 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. Default performs all scans except SqlConnect, which requires explicit specification due to authentication overhead. Scans: Browser Tries discovering all instances via the browser service This scan detects instances. SQLService Tries listing all SQL Services using CIM/WMI This scan uses credentials specified in the '-Credential' parameter if any. This scan detects instances. Success in this scan guarantees high confidence (See parameter '-MinimumConfidence' for details). SPN Tries looking up the Service Principal Names for each instance Will use the nearest Domain Controller by default Target a specific domain controller using the '-DomainController' parameter If using the '-DomainController' parameter, use the '-Credential' parameter to specify the credentials used to connect TCPPort Tries connecting to the TCP Ports. By default, port 1433 is connected to. The parameter '-TCPPort' can be used to provide a list of port numbers to scan. This scan detects possible instances. Since other services might bind to a given port, this is not the most reliable test. This scan is also used to validate found SPNs if both scans are used in combination DNSResolve Tries resolving the computername in DNS Ping Tries pinging the computer. Failure will NOT terminate scans. SqlConnect Tries to establish a SQL connection to the server Uses windows credentials by default Specify custom credentials using the '-SqlCredential' parameter This scan is not used by default Success in this scan guarantees high confidence (See parameter '-MinimumConfidence' for details). All All of the above | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Default | | Accepted Values | 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. Use this to target specific network segments like DMZ subnets or remote locations where SQL instances might exist. Supports 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). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DomainController Specifies a specific domain controller for Active Directory queries when using DomainSPN or DomainServer discovery. Use this when you need to target a specific DC for cross-domain searches or when the nearest DC is unavailable. Requires the '-Credential' parameter when querying remote domains or when explicit authentication is needed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TCPPort Specifies which TCP ports to test for SQL Server connectivity during port scanning. Use this to detect instances running on non-standard ports or to scan multiple common SQL Server ports like 1433, 1434, and custom ports. Defaults to 1433 (SQL Server default port). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1433 | -MinimumConfidence Filters results based on how certain the scan is that a SQL Server instance exists on each target. Use High for definitive results when you need accurate inventories, Medium for likely instances, or Low for comprehensive discovery that includes potential false positives. High 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Low | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Discovery.DbaInstanceReport Returns 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 detected and its current availability status. Properties: MachineName: The network name of the computer where the instance was discovered ComputerName: The computer name (same as MachineName for consistency) InstanceName: The SQL Server instance name (e.g., \"SQLEXPRESS\", \"MSSQLSERVER\"). Null if only a port was detected SqlInstance: The full SQL Server instance identifier (ComputerName\\InstanceName or ComputerName:Port) Port: The TCP port number where the instance is listening (e.g., 1433). Null if InstanceName was discovered instead Confidence: Confidence level of the discovery (High, Medium, or Low). High = certain instance found, Medium = likely instance, Low = possible instance Availability: Instance availability status (Available, Unavailable, or Unknown). Set when SQL Service status is detected DnsResolution: System.Net.IPHostEntry object containing DNS resolution results if DNSResolve scan was performed. Null if not resolved Ping: Boolean indicating whether the computer responded to ping (True/False/Null) TcpConnected: Boolean indicating whether the detected TCP port is open/connected (True/False) SqlConnected: Boolean indicating whether a successful SQL connection was established (True/False). Only set if SqlConnect scan type is enabled Timestamp: DateTime when the discovery scan was performed ScanTypes: Bit-flag of scan types that were performed (Browser, SQLService, SPN, TCPPort, DNSResolve, Ping, SqlConnect, All) Services: Array of SQL Service objects detected via WMI/CIM for this instance. Objects have properties: ServiceType, State, InstanceName, DisplayName SystemServices: Array of system SQL Service objects detected (services without an InstanceName like SQL Server Agent service parent processes) SPNs: Array of Service Principal Names registered in Active Directory for this computer/instance BrowseReply: Custom object containing details from Browser service query if Browser scan was performed. Properties include InstanceName, TCPPort, Version, IsClustered PortsScanned: Array of port scan results. Each object has properties: ComputerName, Port, IsOpen The output is filtered by MinimumConfidence parameter - only instances meeting or exceeding the specified confidence level are returned. &nbsp;"
  },
  {
    "name": "Find-DbaLoginInGroup",
    "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.",
    "category": "Security",
    "tags": [
      "login",
      "group",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaLoginInGroup",
    "popularityRank": 223,
    "synopsis": "Discovers individual Active Directory users within Windows group logins on SQL Server instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Find-DbaLoginInGroup View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com , Simone Bizzotto (@niphlod) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Discovers individual Active Directory users within Windows group logins on SQL Server instances. 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. Syntax Find-DbaLoginInGroup [-SqlInstance] [[-SqlCredential] ] [[-Login] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all active directory groups with logins on Sql Instance DEV01 that contain the AD user... PS C:\\> Find-DbaLoginInGroup -SqlInstance DEV01 -Login \"MyDomain\\Stephen.Bennett\" Returns all active directory groups with logins on Sql Instance DEV01 that contain the AD user Stephen.Bennett. Example 2: Returns all active directory users within all windows AD groups that have logins on the instance PS C:\\> Find-DbaLoginInGroup -SqlInstance DEV01 Example 3: Returns all active directory users within all windows AD groups that have logins on the instance whose login... PS C:\\> Find-DbaLoginInGroup -SqlInstance DEV01 | Where-Object Login -like 'stephen' Returns all active directory users within all windows AD groups that have logins on the instance whose login contains \"stephen\" Required Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential PSCredential object to connect under. If not specified, current Windows login will be used. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Filters results to show only Windows Active Directory groups that contain the specified individual user account(s). Use 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. Accepts multiple login names in DOMAIN\\username format and supports pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Default display properties (via Select-DefaultView): SqlInstance: The SQL Server instance name (in the format COMPUTER\\INSTANCE or just COMPUTER for default instance) Login: The individual user account in DOMAIN\\username format DisplayName: The user's display name from Active Directory MemberOf: The Windows AD group login on SQL Server that contains this user ParentADGroupLogin: The original parent group login (same as MemberOf unless accessed through nested groups) Additional properties available: InstanceName: The SQL Server instance name only (without computer name) ComputerName: The name of the computer hosting the SQL Server instance All properties are accessible using Select-Object * or by directly referencing property names even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Find-DbaObject",
    "description": "Provides a unified search across all database object types (tables, views, stored procedures, functions,\nsynonyms, triggers) by matching their names against a regex pattern. Optionally extends the search to\ncolumn names within tables and views. This complements the existing Find-DbaStoredProcedure, Find-DbaView,\nand Find-DbaTrigger commands which search object definition text rather than object or column names.\n\nUses T-SQL queries against sys.objects and sys.columns for optimal performance. Pattern matching is\nperformed in PowerShell using full regex syntax.",
    "category": "Utilities",
    "tags": [
      "object",
      "lookup",
      "find"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaObject",
    "popularityRank": 0,
    "synopsis": "Searches database objects by name or column name across SQL Server databases using regex patterns.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaObject View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Searches database objects by name or column name across SQL Server databases using regex patterns. Description Provides a unified search across all database object types (tables, views, stored procedures, functions, synonyms, triggers) by matching their names against a regex pattern. Optionally extends the search to column names within tables and views. This complements the existing Find-DbaStoredProcedure, Find-DbaView, and Find-DbaTrigger commands which search object definition text rather than object or column names. Uses T-SQL queries against sys.objects and sys.columns for optimal performance. Pattern matching is performed in PowerShell using full regex syntax. Syntax Find-DbaObject [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-Pattern] [[-ObjectType] ] [-IncludeColumns] [-IncludeSystemObjects] [-IncludeSystemDatabases] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Searches all user databases on DEV01 for any object whose name contains &quot;Service&quot; PS C:\\> Find-DbaObject -SqlInstance DEV01 -Pattern Service Example 2: Searches all user databases on DEV01 for objects named with &quot;Service&quot; and tables/views that have columns... PS C:\\> Find-DbaObject -SqlInstance DEV01 -Pattern Service -IncludeColumns Searches all user databases on DEV01 for objects named with \"Service\" and tables/views that have columns whose names contain \"Service\". Example 3: Finds all user tables on DEV01 whose names start with &quot;Customer&quot; PS C:\\> Find-DbaObject -SqlInstance DEV01 -Pattern \"^Customer\" -ObjectType Table Example 4: Searches the Accounting database for objects and columns related to &quot;Invoice&quot; PS C:\\> Find-DbaObject -SqlInstance DEV01 -Pattern \"Invoice\" -Database Accounting -IncludeColumns Example 5: Finds all tables and views whose names contain either &quot;Service&quot; or &quot;Product&quot; PS C:\\> Find-DbaObject -SqlInstance sql2019 -Pattern \"Service|Product\" -ObjectType Table, View Required Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Pattern The regular expression pattern to match against object names (and optionally column names). Supports full regex syntax for complex pattern matching. For example, use \"^Customer\" to find objects starting with \"Customer\", or \"Service|Product\" to find objects mentioning either term. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies one or more databases to search. When omitted, searches all user databases on the instance. Use this to focus searches on specific databases when you know where the objects are located. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during the search. Accepts multiple database names. Use this to exclude large databases or test environments from the search. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ObjectType Filters the search to specific object types. Accepts one or more of: Table: User tables (sys.objects type U) View: Views (sys.objects type V) StoredProcedure: Stored procedures (sys.objects type P) ScalarFunction: Scalar-valued functions (sys.objects type FN) TableValuedFunction: Inline and multi-statement table-valued functions (sys.objects type IF/TF) Synonym: Synonyms (sys.objects type SN) Trigger: Object-level DML triggers plus database DDL SQL triggers All: All of the above (default) | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @(\"All\") | | Accepted Values | Table,View,StoredProcedure,ScalarFunction,TableValuedFunction,Synonym,Trigger,All | -IncludeColumns When specified, additionally searches column names within tables and views for the given pattern. Results with column name matches include a MatchType of \"ColumnName\" and the matching column name. This is useful for finding which tables or views contain a column related to a specific domain concept. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSystemObjects Includes system objects (those shipped with SQL Server) in the search results. By default, only user-created objects are searched. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSystemDatabases Includes system databases (master, model, msdb, tempdb) in the search scope. By default, only user databases are searched. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per match found. When -IncludeColumns is used, there may be multiple results per database object (one for the object name match plus one per matching column name). Properties: ComputerName: The computer name of the SQL Server instance SqlInstance: The SQL Server instance name Database: The database containing the matched object Schema: The schema of the matched object (null for database DDL triggers) Name: The name of the matched object ObjectType: The SQL Server type description (e.g., USER_TABLE, VIEW, SQL_STORED_PROCEDURE) MatchType: \"ObjectName\" when the object name matched, \"ColumnName\" when a column name matched ColumnName: The matching column name when MatchType is \"ColumnName\", otherwise null CreateDate: DateTime when the object was created LastModified: DateTime when the object was last modified &nbsp;"
  },
  {
    "name": "Find-DbaOrphanedFile",
    "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.",
    "category": "Database Operations",
    "tags": [
      "orphan",
      "database",
      "databasefile",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaOrphanedFile",
    "popularityRank": 200,
    "synopsis": "Identifies database files on disk that are not attached to any SQL Server database instance",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaOrphanedFile View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies database files on disk that are not attached to any SQL Server database instance 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. The 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. Perfect 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. Syntax Find-DbaOrphanedFile -SqlInstance [-SqlCredential ] [-Path ] [-FileType ] [-LocalOnly] [-EnableException] [-Recurse] [ ] Find-DbaOrphanedFile -SqlInstance [-SqlCredential ] [-Path ] [-FileType ] [-RemoteOnly] [-EnableException] [-Recurse] [ ] &nbsp; Examples &nbsp; Example 1: Connects to sqlserver2014a, authenticating with Windows credentials, and searches for orphaned files PS C:\\> Find-DbaOrphanedFile -SqlInstance sqlserver2014a Connects to sqlserver2014a, authenticating with Windows credentials, and searches for orphaned files. Returns server name, local filename, and unc path to file. Example 2: Connects to sqlserver2014a, authenticating with SQL Server authentication, and searches for orphaned files PS C:\\> Find-DbaOrphanedFile -SqlInstance sqlserver2014a -SqlCredential $cred Connects to sqlserver2014a, authenticating with SQL Server authentication, and searches for orphaned files. Returns server name, local filename, and unc path to file. Example 3: Finds the orphaned files in &quot;E:\\Dir1&quot; and &quot;E:Dir2&quot; in addition to the default directories PS C:\\> Find-DbaOrphanedFile -SqlInstance sql2014 -Path 'E:\\Dir1', 'E:\\Dir2' Example 4: Finds the orphaned files in &quot;E:\\Dir1&quot; and any of its subdirectories in addition to the default directories PS C:\\> Find-DbaOrphanedFile -SqlInstance sql2014 -Path 'E:\\Dir1' -Recurse Example 5: Returns only the local file paths for orphaned files PS C:\\> Find-DbaOrphanedFile -SqlInstance sql2014 -LocalOnly Example 6: Returns only the remote file path for orphaned files PS C:\\> Find-DbaOrphanedFile -SqlInstance sql2014 -RemoteOnly Example 7: Finds the orphaned ending with &quot;.fsf&quot; and &quot;.mld&quot; in addition to the default filetypes &quot;.mdf&quot;, &quot;.ldf&quot;, &quot;.ndf&quot;... PS C:\\> Find-DbaOrphanedFile -SqlInstance sql2014, sql2016 -FileType fsf, mld Finds the orphaned ending with \".fsf\" and \".mld\" in addition to the default filetypes \".mdf\", \".ldf\", \".ndf\" for both the servers sql2014 and sql2016. Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 custom backup/restore directories. Accepts multiple paths and searches them alongside the automatically detected SQL Server directories. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 SQL Server-related files. Do not include the dot when specifying extensions (use \"bak\" not \".bak\"). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 recommended for multi-server environments since it omits which server the file belongs to. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Provides the \\\\server\\share\\path format needed for remote file operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 cleanup of complex directory hierarchies. Without this switch, only the immediate directories are searched. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String (when -LocalOnly is specified) Returns the local file path to each orphaned file. System.String (when -RemoteOnly is specified) Returns the UNC path to each orphaned file. PSCustomObject (default) Returns one object per orphaned file found with the following properties: ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName Server: The server name (same as ComputerName for most instances) Filename: The local file path to the orphaned file RemoteFilename: The UNC network path to the orphaned file (\\\\ComputerName\\share\\path format) &nbsp;"
  },
  {
    "name": "Find-DbaSimilarTable",
    "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/",
    "category": "Utilities",
    "tags": [
      "table",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaSimilarTable",
    "popularityRank": 392,
    "synopsis": "Finds tables and views with similar structures by comparing column names across databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaSimilarTable View Source Jana Sattainathan (@SQLJana), sqljana.wordpress.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Finds tables and views with similar structures by comparing column names across databases 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. Perfect 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. You 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. More information can be found here: https://sqljana.wordpress.com/2017/03/31/sql-server-find-tables-with-similar-table-structure/ Syntax Find-DbaSimilarTable [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-SchemaName] ] [[-TableName] ] [-ExcludeViews] [-IncludeSystemDatabases] [[-MatchPercentThreshold] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Searches all user database tables and views for each, returns all tables or views with their matching... PS C:\\> Find-DbaSimilarTable -SqlInstance DEV01 Searches all user database tables and views for each, returns all tables or views with their matching tables/views and match percent Example 2: Searches AdventureWorks database and lists tables/views and their corresponding matching tables/views with... PS C:\\> Find-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks Searches AdventureWorks database and lists tables/views and their corresponding matching tables/views with match percent Example 3: Searches AdventureWorks database and lists tables/views in the HumanResource schema with their corresponding... PS C:\\> Find-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -SchemaName HumanResource Searches AdventureWorks database and lists tables/views in the HumanResource schema with their corresponding matching tables/views with match percent Example 4: Searches AdventureWorks database and lists tables/views in the HumanResource schema and table Employee with... PS C:\\> Find-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -SchemaName HumanResource -Table Employee Searches AdventureWorks database and lists tables/views in the HumanResource schema and table Employee with its corresponding matching tables/views with match percent Example 5: Searches AdventureWorks database and lists all tables/views with its corresponding matching tables/views with... PS C:\\> Find-DbaSimilarTable -SqlInstance DEV01 -Database AdventureWorks -MatchPercentThreshold 60 Searches AdventureWorks database and lists all tables/views with its corresponding matching tables/views with match percent greater than or equal to 60 Required Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for similar table structures. Accepts multiple database names. Use this to limit the search scope when you know which databases contain the tables you're comparing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the similarity search. Accepts multiple database names. Useful for skipping temp databases, development copies, or databases with known irrelevant structures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SchemaName Limits the search to tables within a specific schema. Only tables in this schema will be used as reference structures. Use this when comparing tables within a logical grouping like 'Sales', 'HR', or 'Archive' schemas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TableName Uses a specific table as the reference structure to find similar tables across databases. Perfect for finding archive versions of production tables or identifying tables that mirror a known structure. When the table exists in multiple schemas, all instances are used as reference points. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeViews Excludes views from both the reference objects and the comparison results, focusing only on physical tables. Use this when you need to find similar table structures for data migration or archiving where views aren't relevant. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSystemDatabases Includes system databases (master, model, msdb, tempdb) in the similarity search. Typically used when troubleshooting system table relationships or comparing custom objects in system databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MatchPercentThreshold Sets the minimum percentage of matching column names required to include a table pair in results. Use values like 50 for loose matches, 80 for close structural similarity, or 95 for near-identical tables. Zero matches are always excluded regardless of this threshold. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per matching table pair found. Each object represents one source table matched against one similar table. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Table: The fully qualified name of the source table (database.schema.table) MatchingTable: The fully qualified name of the matching table found (database.schema.table) MatchPercent: Percentage of matching column names between the two tables (0-100) OriginalDatabaseName: Name of the database containing the source table OriginalDatabaseId: System database ID for the source table's database OriginalSchemaName: Name of the schema containing the source table OriginalTableName: Name of the source table OriginalTableNameRankInDB: Dense ranking of the table among all tables in its database (used for processing order) OriginalTableType: Type of the source table (TABLE or VIEW) OriginalColumnCount: Number of columns in the source table MatchingDatabaseName: Name of the database containing the matching table MatchingDatabaseId: System database ID for the matching table's database MatchingSchemaName: Name of the schema containing the matching table MatchingTableName: Name of the matching table MatchingTableType: Type of the matching table (TABLE or VIEW) MatchingColumnCount: Number of columns in the matching table &nbsp;"
  },
  {
    "name": "Find-DbaStoredProcedure",
    "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.",
    "category": "Utilities",
    "tags": [
      "storedprocedure",
      "proc",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaStoredProcedure",
    "popularityRank": 240,
    "synopsis": "Searches stored procedure definitions for specific text patterns or regex expressions across SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaStoredProcedure View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Searches stored procedure definitions for specific text patterns or regex expressions across SQL Server databases. 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. Syntax Find-DbaStoredProcedure [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-Pattern] [-IncludeSystemObjects] [-IncludeSystemDatabases] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Searches all user databases stored procedures for &quot;whatever&quot; in the text body PS C:\\> Find-DbaStoredProcedure -SqlInstance DEV01 -Pattern whatever Example 2: Searches all databases for all stored procedures that contain a valid email pattern in the text body PS C:\\> Find-DbaStoredProcedure -SqlInstance sql2016 -Pattern '\\w+@\\w+\\.\\w+' Example 3: Searches in &quot;mydb&quot; database stored procedures for &quot;some string&quot; in the text body PS C:\\> Find-DbaStoredProcedure -SqlInstance DEV01 -Database MyDB -Pattern 'some string' -Verbose Example 4: Searches in &quot;mydb&quot; database stored procedures for &quot;runtime&quot; in the text body PS C:\\> Find-DbaStoredProcedure -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects Required Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Pattern Specifies the text pattern or regular expression to search for within stored procedure definitions. Supports full regex syntax for complex pattern matching. Use this to find hardcoded values, deprecated functions, security vulnerabilities, or specific business logic across procedure source code. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for stored procedures containing the pattern. Accepts database names and supports wildcards. When omitted, searches all user databases on the instance. Use this to focus searches on specific databases when you know where procedures are located. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during the stored procedure search. Accepts database names and supports wildcards. Use this when you want to search most databases but exclude specific ones like test environments or databases with sensitive procedures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSystemObjects Includes system stored procedures (those shipped with SQL Server) in the search results. By default, only user-created procedures are searched. Use this when investigating system procedures or when patterns might exist in Microsoft-provided code. Warning: this significantly slows performance when searching multiple databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSystemDatabases Includes system databases (master, model, msdb, tempdb) in the search scope. By default, only user databases are searched. Use this when investigating system procedures or when your pattern might exist in maintenance scripts stored in system databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance SqlInstance: The SQL Server instance name Database: The database containing the stored procedure DatabaseId: The database ID (system assigned identifier) Schema: The schema that owns the stored procedure Name: The name of the stored procedure Owner: The owner of the stored procedure IsSystemObject: Boolean indicating if this is a system stored procedure CreateDate: DateTime when the stored procedure was created LastModified: DateTime when the stored procedure was last modified StoredProcedureTextFound: Formatted string containing matching line numbers and the matched text lines (formatted as \"(LineNumber: #) matched text\") *Additional properties available via Select-Object (excluded from default view):** StoredProcedure: The full Microsoft.SqlServer.Management.Smo.StoredProcedure object with all SMO properties StoredProcedureFullText: The complete T-SQL source code of the stored procedure as a string &nbsp;"
  },
  {
    "name": "Find-DbaTrigger",
    "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.",
    "category": "Utilities",
    "tags": [
      "trigger",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaTrigger",
    "popularityRank": 503,
    "synopsis": "Searches trigger code across server, database, and object levels for specific text patterns or regex matches.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaTrigger View Source Claudio Silva (@ClaudioESSilva) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Searches trigger code across server, database, and object levels for specific text patterns or regex matches. 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. This 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. When 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. Syntax Find-DbaTrigger [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-Pattern] [[-TriggerLevel] ] [-IncludeSystemObjects] [-IncludeSystemDatabases] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Searches all user databases triggers for &quot;whatever&quot; in the text body PS C:\\> Find-DbaTrigger -SqlInstance DEV01 -Pattern whatever Example 2: Searches all databases for all triggers that contain a valid email pattern in the text body PS C:\\> Find-DbaTrigger -SqlInstance sql2016 -Pattern '\\w+@\\w+\\.\\w+' Example 3: Searches in &quot;mydb&quot; database triggers for &quot;some string&quot; in the text body PS C:\\> Find-DbaTrigger -SqlInstance DEV01 -Database MyDB -Pattern 'some string' -Verbose Example 4: Searches in &quot;mydb&quot; database triggers for &quot;runtime&quot; in the text body PS C:\\> Find-DbaTrigger -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects Required Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Pattern The text pattern or regular expression to search for within trigger definitions. Supports full regex syntax for complex pattern matching. Use this to find triggers containing specific table names, column references, or code patterns before making schema changes. Results show matching lines with line numbers to pinpoint exactly where the pattern occurs. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for triggers. Accepts an array of database names for targeting specific databases. When specified, server-level triggers are automatically excluded from the search to focus on database and object-level triggers. If omitted, searches all user databases plus any server-level triggers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the trigger search. Accepts an array of database names to skip during processing. Use this when you want to search most databases but avoid specific ones like staging or temporary databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use specific levels to narrow your search when you know what type of trigger contains the pattern you're looking for. Defaults to All, which searches server-level triggers, database DDL triggers, and object-level DML triggers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | All | | Accepted Values | All,Server,Database,Object | -IncludeSystemObjects Includes system-created triggers in the search results. By default, only user-created triggers are searched. Use this when you need to examine built-in triggers for troubleshooting or audit purposes. Warning: This significantly impacts performance when searching across multiple databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSystemDatabases Includes system databases (master, model, msdb, tempdb) in the trigger search. By default, only user databases are searched. Use this when troubleshooting system-level issues or when you need to examine triggers in system databases for audit purposes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance SqlInstance: The SQL Server instance name TriggerLevel: The type of trigger (Server, Database, or Object) Database: The name of the database containing the trigger (null for server-level triggers) DatabaseId: The ID of the database (null for server-level triggers) Object: The name of the parent object (table/view) for object-level triggers, null for server and database-level Name: The name of the trigger IsSystemObject: Boolean indicating if this is a system-created trigger CreateDate: DateTime when the trigger was created LastModified: DateTime when the trigger was last modified TriggerTextFound: String containing matching lines with line numbers in format \"(LineNumber: #) matched_text\" Additional properties available (not displayed by default): Trigger: The SMO Trigger object TriggerFullText: The complete T-SQL definition of the trigger &nbsp;"
  },
  {
    "name": "Find-DbaUserObject",
    "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't owned by system accounts.",
    "category": "Utilities",
    "tags": [
      "object",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaUserObject",
    "popularityRank": 259,
    "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",
    "windowsOnly": false,
    "fullContent": "Find-DbaUserObject View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Finds SQL Server objects owned by users other than sa or dbo, or searches for objects owned by a specific user pattern. Description Scans SQL Server instances to identify objects with non-standard ownership, which is critical for security auditing and user management. When removing user accounts or performing security reviews, you need to know what objects they own to avoid breaking dependencies. This function searches databases, SQL Agent jobs, credentials, proxies, endpoints, server roles, schemas, database roles, assemblies, and synonyms. Use the Pattern parameter to search for objects owned by a specific user, or run without it to find all user-owned objects that aren't owned by system accounts. Syntax Find-DbaUserObject [-SqlInstance] [[-SqlCredential] ] [[-Pattern] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Searches user objects for owner ad\\stephen PS C:\\> Find-DbaUserObject -SqlInstance DEV01 -Pattern ad\\stephen Example 2: Shows all user owned (non-sa, non-dbo) objects and verbose output PS C:\\> Find-DbaUserObject -SqlInstance DEV01 -Verbose Required Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. When omitted, finds all objects not owned by system accounts (sa/dbo). Supports Windows domain accounts like 'DOMAIN\\username' or SQL logins. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 instance. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (ServiceName from SMO) SqlInstance: The full SQL Server instance name (computer\\instance format) Type: The category of object found. Possible values include: Database Agent Job Credential Proxy Agent Step Endpoint Server Role Schema Database Role Database Assembly * Database Synonyms Owner: The login or user account that owns the object (string format for logins, domain\\username for Windows accounts) Name: The name of the object 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) &nbsp;"
  },
  {
    "name": "Find-DbaView",
    "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.",
    "category": "Utilities",
    "tags": [
      "view",
      "lookup"
    ],
    "verb": "Find",
    "popular": false,
    "url": "/Find-DbaView",
    "popularityRank": 337,
    "synopsis": "Searches database views for specific text patterns or regular expressions in their definitions.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Find-DbaView View Source Claudio Silva (@ClaudioESSilva) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Searches database views for specific text patterns or regular expressions in their definitions. 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. Syntax Find-DbaView [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-Pattern] [-IncludeSystemObjects] [-IncludeSystemDatabases] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Searches all user databases views for &quot;whatever&quot; in the text body PS C:\\> Find-DbaView -SqlInstance DEV01 -Pattern whatever Example 2: Searches all databases for all views that contain a valid email pattern in the text body PS C:\\> Find-DbaView -SqlInstance sql2016 -Pattern '\\w+@\\w+\\.\\w+' Example 3: Searches in &quot;mydb&quot; database views for &quot;some string&quot; in the text body PS C:\\> Find-DbaView -SqlInstance DEV01 -Database MyDB -Pattern 'some string' -Verbose Example 4: Searches in &quot;mydb&quot; database views for &quot;runtime&quot; in the text body PS C:\\> Find-DbaView -SqlInstance sql2016 -Database MyDB -Pattern RUNTIME -IncludeSystemObjects Required Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Pattern Specifies the text pattern or regular expression to search for within view definitions. Supports full regex syntax for complex pattern matching. Use 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. Common patterns include table names, column references, function calls, or data validation expressions. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for views containing the pattern. Accepts wildcards and multiple database names. Use this when you need to limit the search scope to specific databases instead of scanning all databases on the instance. Particularly useful for large instances where you only need to check certain application databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during the view search operation. Accepts multiple database names. Use this to exclude large databases that you know don't contain relevant views, speeding up the search process. Common exclusions include development copies, archive databases, or third-party application databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSystemObjects Includes system views in the search operation alongside user-created views. System views are excluded by default. Use this when troubleshooting issues that might involve system view dependencies or when documenting complete database schemas. Warning: Including system views significantly slows down the search, especially when scanning multiple databases or large instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSystemDatabases Includes system databases (master, model, msdb, tempdb) in the view search operation. System databases are excluded by default. Use this when investigating SQL Server internals, troubleshooting replication issues, or documenting complete instance configurations. Most DBA tasks focus on user databases, so this parameter is typically used for advanced troubleshooting scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per view matching the specified pattern. Each object represents a single matching view with the matching text lines highlighted. Default display properties (via Select-DefaultView): ComputerName: The name of the server where the view is located SqlInstance: The SQL Server instance name Database: The database name containing the view DatabaseId: The internal database ID Schema: The schema of the view Name: The name of the view Owner: The owner of the view IsSystemObject: Boolean indicating if this is a system view (affected by -IncludeSystemObjects parameter) CreateDate: DateTime when the view was created LastModified: DateTime when the view was last modified ViewTextFound: String containing the matching lines with line numbers in format \"(LineNumber: N) matched text\" *Additional properties available (via Select-Object ):** View: The SMO View object itself ViewFullText: The complete text body of the view definition &nbsp;"
  },
  {
    "name": "Format-DbaBackupInformation",
    "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're restoring to different servers, renaming databases, or moving files to new storage locations. The function handles all the metadata transformations needed so you don't have to manually edit restore paths and database references before running Restore-DbaDatabase.",
    "category": "Backup & Restore",
    "tags": [
      "disasterrecovery",
      "backup",
      "restore"
    ],
    "verb": "Format",
    "popular": false,
    "url": "/Format-DbaBackupInformation",
    "popularityRank": 212,
    "synopsis": "Modifies backup history metadata to prepare database restores with different names, paths, or locations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Format-DbaBackupInformation View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies backup history metadata to prepare database restores with different names, paths, or locations 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're restoring to different servers, renaming databases, or moving files to new storage locations. The function handles all the metadata transformations needed so you don't have to manually edit restore paths and database references before running Restore-DbaDatabase. Syntax Format-DbaBackupInformation [-BackupHistory] [[-ReplaceDatabaseName] ] [-ReplaceDbNameInFile] [[-DataFileDirectory] ] [[-LogFileDirectory] ] [[-DestinationFileStreamDirectory] ] [[-DatabaseNamePrefix] ] [[-DatabaseFilePrefix] ] [[-DatabaseFileSuffix] ] [[-RebaseBackupFolder] ] [-Continue] [[-FileMapping] ] [[-PathSep] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Changes as database name references to NewDb, both in the database name and any restore paths PS C:\\> $History | Format-DbaBackupInformation -ReplaceDatabaseName NewDb -ReplaceDbNameInFile Changes 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 Example 2: Will change all occurrences of original database name in the backup history (names and restore paths) using... PS C:\\> $History | Format-DbaBackupInformation -ReplaceDatabaseName @{'OldB'='NewDb';'ProdHr'='DevHr'} Will change all occurrences of original database name in the backup history (names and restore paths) using the mapping in the hashtable. In this example any occurrence of OldDb will be replaced with NewDb and ProdHr with DevPR Example 3: This example with change the restore path for all data files (everything that is not a log file) to... PS C:\\> $History | Format-DbaBackupInformation -DataFileDirectory 'D:\\DataFiles\\' -LogFileDirectory 'E:\\LogFiles\\ This example with change the restore path for all data files (everything that is not a log file) to d:\\datafiles And all Transaction Log files will be restored to E:\\Logfiles Example 4: This example changes the location that SQL Server will look for the backups PS C:\\> $History | Format-DbaBackupInformation -RebaseBackupFolder f:\\backups This example changes the location that SQL Server will look for the backups. This is useful if you've moved the backups to a different location Required Parameters -BackupHistory Backup history objects from Select-DbaBackupInformation that contain metadata about database backups. Use this to pass backup information that needs to be modified for restore operations to different locations or with different names. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -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. Use this when restoring databases to different environments or creating copies with new names. Database names in file paths are also updated, but logical file names require separate ALTER DATABASE commands after restore. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ReplaceDbNameInFile Replaces occurrences of the original database name within physical file names with the new database name. Use this in combination with ReplaceDatabaseName to ensure file names match the new database name and avoid confusion during restore operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DataFileDirectory Sets the destination directory for all data files during restore. This overrides the original file locations stored in the backup. Use this when restoring to servers with different drive configurations or when consolidating database files to specific storage locations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LogFileDirectory Sets the destination directory specifically for transaction log files during restore. This takes precedence over DataFileDirectory for log files only. Use this to place log files on separate storage from data files for performance optimization or storage management requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationFileStreamDirectory Sets the destination directory for FileStream data files during restore. This takes precedence over DataFileDirectory for FileStream files only. Use this when databases contain FileStream data that needs to be stored on specific storage optimized for large file handling. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DatabaseNamePrefix Adds a prefix to all database names during the restore operation. The prefix is applied after any name replacements from ReplaceDatabaseName. Use this to create standardized naming conventions like adding environment identifiers (Dev_, Test_, etc.) to restored databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DatabaseFilePrefix Adds a prefix to the physical file names of all restored database files (both data and log files). Use this to avoid file name conflicts when restoring to servers that already have files with the same names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DatabaseFileSuffix Adds a suffix to the physical file names of all restored database files (both data and log files). Use this to create unique file names when restoring multiple copies of the same database or to add version identifiers to restored files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RebaseBackupFolder Changes the path where SQL Server will look for backup files during the restore operation. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Continue Marks this as part of an ongoing restore sequence that will have additional transaction log backups applied later. Use this when performing point-in-time recovery scenarios where you need to restore a full backup followed by multiple log backups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FileMapping Maps specific logical file names to custom physical file paths during restore. Use hashtable format like @{'LogicalName1'='C:\\NewPath\\file1.mdf'}. Use this when you need granular control over where individual database files are restored, overriding directory-based parameters. Files not specified in the mapping retain their original locations, and this parameter takes precedence over all other file location settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PathSep Specifies the path separator character for file paths. Defaults to backslash (\\) for Windows. Use forward slash (/) when working with Linux SQL Server instances or when backup history contains Unix-style paths. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \\ | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Database.BackupHistory Returns 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. Default properties (from input backup history object): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name (modified if -ReplaceDatabaseName or -DatabaseNamePrefix was used) UserName: The user who performed the backup Start: DateTime when the backup started End: DateTime when the backup completed Duration: TimeSpan of the backup operation Path: Array of backup file paths (modified if -RebaseBackupFolder was used) FileList: Array of file objects containing Type, LogicalName, PhysicalName, and Size (modified if -DataFileDirectory, -LogFileDirectory, -DestinationFileStreamDirectory, -DatabaseFilePrefix, -DatabaseFileSuffix, -ReplaceDbNameInFile, or -FileMapping was used) TotalSize: Total size of the backup in bytes CompressedBackupSize: Size of compressed backup in bytes Type: Backup type (Database, Database Differential, or Transaction Log) BackupSetId: Unique identifier for the backup set (GUID) DeviceType: Type of backup device (typically Disk) FullName: Array of full paths to backup files (modified if -RebaseBackupFolder was used) Position: Position of the backup within the device FirstLsn: First Log Sequence Number in this backup DatabaseBackupLsn: Log Sequence Number of the database backup CheckpointLSN: Checkpoint Log Sequence Number LastLsn: Last Log Sequence Number in this backup SoftwareVersionMajor: Major version of SQL Server that created the backup RecoveryModel: Database recovery model at time of backup IsCopyOnly: Boolean indicating if this is a copy-only backup Additional properties added by this function: OriginalDatabase: String containing the original database name before any replacements or prefixes OriginalFileList: Object array containing the original FileList before any path modifications OriginalFullName: String array containing the original backup file paths before rebasing IsVerified: Boolean indicating if the backup has been verified (initialized to $False) All properties from the input backup history objects are preserved and accessible, with selective properties modified based on the parameters specified. &nbsp;"
  },
  {
    "name": "Get-DbaAgBackupHistory",
    "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",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgBackupHistory",
    "popularityRank": 134,
    "synopsis": "Retrieves backup history from msdb across all replicas in a SQL Server Availability Group",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgBackupHistory View Source Chrissy LeMaire (@cl) , Stuart Moore (@napalmgram), Andreas Jordan Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves backup history from msdb across all replicas in a SQL Server Availability Group 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. This 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. Reference: http://www.sqlhub.com/2011/07/find-your-backup-history-in-sql-server.html Syntax Get-DbaAgBackupHistory -SqlInstance [-SqlCredential ] -AvailabilityGroup [-Database ] [-ExcludeDatabase ] [-IncludeCopyOnly] [-Since ] [-RecoveryFork ] [-Last] [-LastFull] [-LastDiff] [-LastLog] [-DeviceType ] [-Raw] [-LastLsn ] [-IncludeMirror] [-Type ] [-LsnSort ] [-EnableException] [ ] Get-DbaAgBackupHistory -SqlInstance [-SqlCredential ] -AvailabilityGroup [-Database ] [-ExcludeDatabase ] [-IncludeCopyOnly] [-Force] [-Since ] [-RecoveryFork ] [-Last] [-LastFull] [-LastDiff] [-LastLog] [-DeviceType ] [-Raw] [-LastLsn ] [-IncludeMirror] [-Type ] [-LsnSort ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns information for all database backups still in msdb history on all replicas of availability group... PS C:\\> Get-DbaAgBackupHistory -SqlInstance AgListener -AvailabilityGroup AgTest1 Returns information for all database backups still in msdb history on all replicas of availability group AgTest1 using the listener AgListener to determine all replicas. Example 2: Returns information for all database backups still in msdb history on the given replicas of availability... PS C:\\> Get-DbaAgBackupHistory -SqlInstance Replica1, Replica2, Replica3 -AvailabilityGroup AgTest1 Returns information for all database backups still in msdb history on the given replicas of availability group AgTest1. Example 3: Returns information for all database backups still in msdb history on the given replicas of availability... PS C:\\> Get-DbaAgBackupHistory -SqlInstance 'Replica1:14331', 'Replica2:14332', 'Replica3:14333' -AvailabilityGroup AgTest1 Returns information for all database backups still in msdb history on the given replicas of availability group AgTest1 using custom ports. Example 4: Returns information for all database backups still in msdb history on the replicas in $ListOfReplicas of... PS C:\\> $ListOfReplicas | Get-DbaAgBackupHistory -AvailabilityGroup AgTest1 Returns information for all database backups still in msdb history on the replicas in $ListOfReplicas of availability group AgTest1. Example 5: Returns information for all database backups on all replicas for all availability groups on SQL instance... PS C:\\> $serverWithAllAgs = Connect-DbaInstance -SqlInstance MyServer PS C:\\> $allAgResults = foreach ( $ag in $serverWithAllAgs.AvailabilityGroups ) { >> Get-DbaAgBackupHistory -SqlInstance $ag.AvailabilityReplicas.Name -AvailabilityGroup $ag.Name >> } >> PS C:\\> $allAgResults | Format-Table Returns information for all database backups on all replicas for all availability groups on SQL instance MyServer. Required Parameters -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. If you pass in one availability group listener, all replicas are automatically determined and queried. If you pass in a list of individual replicas, they will be queried. This enables you to use custom ports for the replicas. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -AvailabilityGroup Specifies the name of the availability group to query for backup history. Required parameter that identifies which AG's databases should be included in the backup history retrieval. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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 are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases within the availability group to include in the backup history. If omitted, backup history for all databases in the availability group will be returned. Useful when you need backup history for specific databases rather than the entire AG. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases within the availability group to exclude from backup history results. Use this when you want most AG databases but need to omit specific ones like test or temporary databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeCopyOnly Includes copy-only backups in the results, which are normally excluded by default. Copy-only backups don't affect the backup chain sequence and are often used for ad-hoc copies or third-party backup tools. Enable this when you need a complete view of all backup activity including copy-only operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Returns detailed backup information including additional metadata fields normally hidden for readability. Use this when you need comprehensive backup details for troubleshooting or detailed analysis beyond the standard summary view. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Since Filters backup history to only include backups taken after this date and time. Defaults to January 1, 1970 if not specified, effectively including all backup history. Use this to limit results to recent backups or investigate backup activity within a specific timeframe. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-Date '01/01/1970') | -RecoveryFork Filters backup history to a specific recovery fork identified by its GUID. Recovery forks occur after point-in-time restores and create branching backup chains. Use this when investigating backup history related to a specific restore operation or recovery scenario. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Last Returns the most recent complete backup chain (full, differential, and log backups) needed for point-in-time recovery. This provides the minimum set of backups required to restore each database to its most recent recoverable state. Essential for recovery planning and validating that you have all necessary backup files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LastFull Returns only the most recent full backup for each database in the availability group. Use this to quickly identify the latest full backup baseline for each database, which is the foundation for any restore operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LastDiff Returns only the most recent differential backup for each database in the availability group. Useful for identifying the latest differential backup that can reduce restore time by applying changes since the last full backup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LastLog Returns only the most recent transaction log backup for each database in the availability group. Critical for determining the latest point-in-time recovery option and ensuring log backup chains are current. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DeviceType Filters backup history by the storage device type where backups were written. Common values include 'Disk' for local/network storage, 'URL' for Azure/S3 cloud storage, or 'Tape' for tape devices. Use this when you need to locate backups stored on specific media types or troubleshoot backup destinations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Raw Returns individual backup file details instead of grouping striped backup files into single backup set objects. Enable this when you need to see each physical backup file separately, useful for investigating striped backups or file-level backup issues. By default, related backup files are grouped together as logical backup sets. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LastLsn Filters backup history to only include backups with Log Sequence Numbers greater than this value. Use this to find backups taken after a specific point in the transaction log, improving performance when dealing with large backup histories. Commonly used when building incremental backup chains or investigating activity after a known LSN checkpoint. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeMirror Includes mirrored backup sets in the results, which are normally excluded for clarity. Mirrored backups are identical copies written simultaneously to multiple destinations during backup operations. Enable this when you need to see all backup copies or verify mirror backup destinations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Type Filters results to specific backup types such as 'Full', 'Log', or 'Differential'. Use this when you need to focus on particular backup types, like reviewing only transaction log backups for log shipping validation. If not specified, all backup types are included unless using one of the Last switches. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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). Options are 'FirstLsn' (default), 'DatabaseBackupLsn', or 'LastLsn' to control chronological ordering. Use 'LastLsn' when you need backups sorted by their ending checkpoint rather than starting point. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | FirstLsn | | Accepted Values | FirstLsn,DatabaseBackupLsn,LastLsn | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Database.BackupHistory Returns 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 timing, size, location, and LSN sequence information. When 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 instead of grouping striped files into single logical sets. Default display properties (via Format-Table): SqlInstance: The SQL Server instance name (computer\\instance) Database: The database name Type: Backup type (Full, Differential, Log, etc.) TotalSize: Total backup size in bytes DeviceType: Storage device type (Disk, Tape, URL, Virtual Device) Start: Backup start time Duration: Time span of the backup operation End: Backup completion time *Additional properties available (can be accessed via Select-Object ):** ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name DatabaseId: System database identifier UserName: User account that performed the backup CompressedBackupSize: Compressed size in bytes (null for SQL Server 2005) CompressionRatio: Ratio of TotalSize to CompressedBackupSize BackupSetId: Unique identifier for the backup set Software: Backup software name and version FullName: Full path to backup files (array of paths for striped backups) FileList: Details of database and log files in the backup Position: Position of the backup within a media set FirstLsn: Starting log sequence number DatabaseBackupLsn: LSN of the last database backup (for log/differential backups) CheckpointLsn: LSN of the checkpoint during backup LastLsn: Ending log sequence number SoftwareVersionMajor: Major version of SQL Server that created the backup IsCopyOnly: Boolean indicating if this is a copy-only backup LastRecoveryForkGuid: GUID of the recovery fork (for point-in-time restore scenarios) RecoveryModel: Database recovery model at time of backup (Simple, Full, BulkLogged) EncryptorThumbprint: Thumbprint of backup encryption certificate (SQL Server 2014+) EncryptorType: Type of encryption used (SQL Server 2014+) KeyAlgorithm: Encryption algorithm used (SQL Server 2014+) AvailabilityGroupName: Name of the availability group being queried (added by Get-DbaAgBackupHistory) &nbsp;"
  },
  {
    "name": "Get-DbaAgDatabase",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgDatabase",
    "popularityRank": 60,
    "synopsis": "Retrieves availability group database information and synchronization status from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgDatabase View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves availability group database information and synchronization status from SQL Server instances. 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. Use 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. Syntax Get-DbaAgDatabase [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Pattern] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all the databases in each availability group found on sql2017a PS C:\\> Get-DbaAgDatabase -SqlInstance sql2017a Example 2: Returns all the databases in the availability group AG101 on sql2017a PS C:\\> Get-DbaAgDatabase -SqlInstance sql2017a -AvailabilityGroup AG101 Example 3: Returns all the databases in each availability group found on sql2017a, excluding TestDB and StagingDB PS C:\\> Get-DbaAgDatabase -SqlInstance sql2017a -ExcludeDatabase TestDB,StagingDB Example 4: Returns all databases in each availability group found on sql2017a that match the regex pattern &quot;^dbatools_&quot;... PS C:\\> Get-DbaAgDatabase -SqlInstance sql2017a -Pattern \"^dbatools_\" Returns all databases in each availability group found on sql2017a that match the regex pattern \"^dbatools_\" (e.g., dbatools_example1, dbatools_example2) Example 5: Returns the database Sharepoint_Config found in the availability group SharePoint on server sqlcluster PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sqlcluster -AvailabilityGroup SharePoint | Get-DbaAgDatabase -Database Sharepoint_Config Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies which availability groups to query for database information. Accepts multiple availability group names. Use this to limit results to specific availability groups when you have multiple AGs on the same instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which availability group databases to return information for. Accepts multiple database names with tab completion. Use this to focus on specific databases when troubleshooting AG issues or monitoring particular applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies one or more databases to exclude from the results using exact name matching. Use this to filter out specific databases like test or staging environments from your results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Pattern Specifies a pattern for filtering databases using regular expressions. Use this when you need to match databases by pattern, such as \"^dbatools_\" or \".*_prod$\". This parameter supports standard .NET regular expression syntax. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group objects from Get-DbaAvailabilityGroup via pipeline input. Use this when you want to chain commands to get database details from already retrieved availability groups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityDatabase Returns one AvailabilityDatabase object for each database found in the availability groups on the specified instances. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) AvailabilityGroup: Name of the availability group LocalReplicaRole: Role of this replica (Primary or Secondary) Name: Database name SynchronizationState: Current synchronization state (NotSynchronizing, Synchronizing, Synchronized, Reverting, Initializing) IsFailoverReady: Boolean indicating if the database is ready for failover IsJoined: Boolean indicating if the database has joined the availability group IsSuspended: Boolean indicating if data movement is suspended Additional properties available (from SMO AvailabilityDatabase object): DatabaseGuid: Unique identifier for the database EstimatedDataLoss: Estimated data loss in seconds EstimatedRecoveryTime: Estimated recovery time in seconds FileStreamSendRate: Rate of FILESTREAM data being sent (bytes/sec) GroupDatabaseId: Unique identifier for the database within the AG ID: Internal object ID IsAvailabilityDatabaseSuspended: Boolean indicating suspension state IsDatabaseDiskHealthy: Boolean indicating if database disk health is good IsDatabaseJoined: Boolean indicating database join state IsInstanceDiskHealthy: Boolean indicating if instance disk health is good IsInstanceHealthy: Boolean indicating overall instance health IsPendingSecondarySuspend: Boolean indicating if secondary suspend is pending LastCommitLsn: Last commit log sequence number LastCommitTime: Timestamp of last committed transaction LastHardenedLsn: Last hardened log sequence number LastHardenedTime: Timestamp when last LSN was hardened LastReceivedLsn: Last received log sequence number LastReceivedTime: Timestamp when last LSN was received LastRedoneLsn: Last redone log sequence number LastRedoneTime: Timestamp when last LSN was redone LastSentLsn: Last sent log sequence number LastSentTime: Timestamp when last LSN was sent LogSendQueue: Size of log send queue in KB LogSendRate: Rate of log sending (bytes/sec) LowWaterMarkForGhostCleanup: Low water mark LSN for ghost cleanup Parent: Reference to parent AvailabilityGroup SMO object RecoveryLsn: Recovery log sequence number RedoQueue: Size of redo queue in KB RedoRate: Rate of redo operations (bytes/sec) SecondaryLagSeconds: Lag in seconds for secondary replica State: SMO object state (Existing, Creating, Pending, etc.) SuspendReason: Reason for suspension if database is suspended Urn: Uniform Resource Name for the SMO object &nbsp;"
  },
  {
    "name": "Get-DbaAgDatabaseReplicaState",
    "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's 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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha",
      "monitoring",
      "health"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgDatabaseReplicaState",
    "popularityRank": 0,
    "synopsis": "Retrieves the runtime state of databases participating in availability groups across all replicas.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgDatabaseReplicaState View Source Andreas Jordan (@andreasjordan) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves the runtime state of databases participating in availability groups across all replicas. 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. The class Microsoft.SqlServer.Management.Smo.DatabaseReplicaState represents the runtime state of a database that's participating in an availability group. This database may be located on any of the replicas that compose the availability group. Use 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. Syntax Get-DbaAgDatabaseReplicaState [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Database] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns database replica state information for all databases in all availability groups on sql2017a PS C:\\> Get-DbaAgDatabaseReplicaState -SqlInstance sql2017a Example 2: Returns database replica state information for all databases in the availability group AG101 on sql2017a PS C:\\> Get-DbaAgDatabaseReplicaState -SqlInstance sql2017a -AvailabilityGroup AG101 Example 3: Returns database replica state information for the AppDB database in the availability group AG101 on sql2017a PS C:\\> Get-DbaAgDatabaseReplicaState -SqlInstance sql2017a -AvailabilityGroup AG101 -Database AppDB Example 4: Returns database replica state information for all databases in the availability group SharePoint on server... PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sqlcluster -AvailabilityGroup SharePoint | Get-DbaAgDatabaseReplicaState Returns database replica state information for all databases in the availability group SharePoint on server sqlcluster Example 5: Returns database replica state information for the Sharepoint_Config database in the availability group... PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sqlcluster -AvailabilityGroup SharePoint | Get-DbaAgDatabaseReplicaState -Database Sharepoint_Config Returns database replica state information for the Sharepoint_Config database in the availability group SharePoint on server sqlcluster Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies which availability groups to query for database replica state information. Accepts multiple availability group names. Use this to limit results to specific availability groups when you have multiple AGs on the same instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which availability group databases to return replica state information for. Accepts multiple database names. Use this to focus on specific databases when troubleshooting AG issues or monitoring particular applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group objects from Get-DbaAvailabilityGroup via pipeline input. Use this when you want to chain commands to get database replica state details from already retrieved availability groups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties returned: ComputerName: The computer name of the SQL Server instance (string) InstanceName: The SQL Server instance name (string) SqlInstance: The full SQL Server instance name (computer\\instance format) (string) AvailabilityGroup: Name of the availability group (string) PrimaryReplica: Server name of the primary replica (string) ReplicaServerName: Server name of this replica (string) ReplicaRole: Role of this replica - Primary or Secondary (AvailabilityReplicaRole enum) ReplicaAvailabilityMode: Availability mode of this replica - Asynchronous or Synchronous (AvailabilityReplicaAvailabilityMode enum) ReplicaFailoverMode: Failover mode of this replica - Automatic or Manual (AvailabilityReplicaFailoverMode enum) ReplicaConnectionState: Connection state of this replica - Connected, Disconnected, or Failed (ReplicaConnectionState enum) ReplicaJoinState: Join state of this replica - Joined or NotJoined (ReplicaJoinState enum) ReplicaSynchronizationState: Rollup synchronization state for all databases on this replica (SynchronizationState enum) DatabaseName: Name of the database (string) SynchronizationState: Database synchronization state on this replica - Synchronized, Synchronizing, NotSynchronizing, Reverting, or Initializing (SynchronizationState enum) IsFailoverReady: Boolean indicating if the database is ready for failover (bool) IsJoined: Boolean indicating if the database has joined the availability group (bool) IsSuspended: Boolean indicating if data movement is suspended for this database (bool) SuspendReason: Reason why data movement was suspended - None, UserAction, PartnerSuspended, etc. (SuspendReason enum) EstimatedRecoveryTime: Estimated time to recover the database (TimeSpan) EstimatedDataLoss: Estimated amount of data loss in case of failover (TimeSpan) SynchronizationPerformance: Synchronization performance level - NotApplicable, High, Medium, Low (SynchronizationPerformance enum) LogSendQueueSize: Size of the unsent log queue in KB (long) LogSendRate: Rate at which log records are being sent in KB/sec (long) RedoQueueSize: Size of the redo queue in KB (long) RedoRate: Rate at which redo records are being applied in KB/sec (long) FileStreamSendRate: Rate at which FILESTREAM records are being sent in KB/sec (long) EndOfLogLSN: Log sequence number (LSN) of the end of the log (string) RecoveryLSN: LSN for recovery point (string) TruncationLSN: LSN for truncation point (string) LastCommitLSN: LSN of the last committed transaction (string) LastCommitTime: Timestamp when the last transaction was committed (DateTime) LastHardenedLSN: LSN that was last hardened to disk (string) LastHardenedTime: Timestamp when the last record was hardened to disk (DateTime) LastReceivedLSN: LSN of the last received log record (string) LastReceivedTime: Timestamp when the last log record was received (DateTime) LastRedoneLSN: LSN of the last redo operation (string) LastRedoneTime: Timestamp when the last redo operation completed (DateTime) LastSentLSN: LSN of the last sent log record (string) LastSentTime: Timestamp when the last log record was sent (DateTime) &nbsp;"
  },
  {
    "name": "Get-DbaAgentAlert",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "alert"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgentAlert",
    "popularityRank": 202,
    "synopsis": "Retrieves SQL Server Agent alert configurations from one or more instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentAlert View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Agent alert configurations from one or more instances 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. Syntax Get-DbaAgentAlert [-SqlInstance] [[-SqlCredential] ] [[-Alert] ] [[-ExcludeAlert] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all SQL Agent alerts on serverA and serverB\\instanceB PS C:\\> Get-DbaAgentAlert -SqlInstance ServerA,ServerB\\instanceB Example 2: Returns SQL Agent alert on serverA and serverB\\instanceB whose names match &#39;MyAlert&#39; PS C:\\> Get-DbaAgentAlert -SqlInstance ServerA,ServerB\\instanceB -Alert MyAlert Example 3: Returns all SQL Agent alerts on serverA and serverB\\instanceB PS C:\\> 'serverA','serverB\\instanceB' | Get-DbaAgentAlert Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Alert Specifies the specific SQL Agent alert names to retrieve from the target instances. Accepts wildcards for pattern matching. Use this when you need to check specific alerts like 'Severity 016' or 'DB Mail' instead of retrieving all alerts on the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeAlert Specifies SQL Agent alert names to exclude from the results. Accepts wildcards for pattern matching. Use this to filter out unwanted alerts when auditing or when you need to focus on specific alert categories without built-in system alerts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Alert Returns one Alert object per SQL Agent alert found on the specified instances. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Name of the alert ID: Unique identifier of the alert in the msdb database JobName: Name of the job that responds to this alert (if any) AlertType: Type of alert (EventAlert, ErrorNumberAlert, etc.) CategoryName: Category name assigned to the alert Severity: SQL Server error severity level (0-25) that triggers this alert MessageId: SQL Server message ID that triggers this alert (if alert is message-based) IsEnabled: Boolean indicating if the alert is enabled DelayBetweenResponses: Delay in seconds between repeated alert responses LastRaised: DateTime when this alert was last triggered (dbatools custom property) OccurrenceCount: Number of times this alert has been raised Additional properties available (from SMO Alert object): CategoryId: Unique identifier of the alert category CreateDate: DateTime when the alert was created DateLastModified: DateTime when the alert was last modified DatabaseName: Name of the database this alert applies to (for database-specific alerts) Urn: Uniform Resource Name for the SMO object State: SMO object state (Existing, Creating, Pending, etc.) Custom properties added by this function: Notifications: DataTable from EnumNotifications() containing operators notified by this alert and their notification methods (Email, Pager, NetSend) All properties from the base SMO Alert object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaAgentAlertCategory",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "alert",
      "alertcategory"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgentAlertCategory",
    "popularityRank": 617,
    "synopsis": "Retrieves SQL Server Agent alert categories and their associated alert counts",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentAlertCategory View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Agent alert categories and their associated alert counts 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. Syntax Get-DbaAgentAlertCategory [-SqlInstance] [[-SqlCredential] ] [[-Category] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Return all the agent alert categories PS C:\\> Get-DbaAgentAlertCategory -SqlInstance sql1 Example 2: Return all the agent alert categories that have the name &#39;Severity Alert&#39; PS C:\\> Get-DbaAgentAlertCategory -SqlInstance sql1 -Category 'Severity Alert' Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Category Specifies one or more alert category names to return from the SQL Server Agent. Accepts multiple values and wildcards are not supported. Use this when you need to examine specific alert categories rather than retrieving all categories on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Agent.AlertCategory Returns one AlertCategory object per alert category on the SQL Server instance. Custom properties are added to provide connection context and alert count information. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the alert category ID: The unique identifier of the alert category AlertCount: The number of alerts currently assigned to this category (integer) Additional properties available (from SMO AlertCategory object): Parent: Reference to the parent JobServer object Urn: The Unified Resource Name that uniquely identifies the alert category State: The state of the object (Existing, Creating, Dropping, Pending) All properties from the base SMO AlertCategory object are accessible by using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaAgentJob",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaAgentJob",
    "popularityRank": 20,
    "synopsis": "Retrieves SQL Server Agent job details and execution status from one or more instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentJob View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Agent job details and execution status from one or more instances. 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. Syntax Get-DbaAgentJob [-SqlInstance] [[-SqlCredential] ] [[-Job] ] [[-ExcludeJob] ] [[-Database] ] [[-Category] ] [[-ExcludeCategory] ] [-ExcludeDisabledJobs] [-IncludeExecution] [[-Type] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all SQL Agent Jobs on the local default SQL Server instance PS C:\\> Get-DbaAgentJob -SqlInstance localhost Example 2: Returns all SQl Agent Jobs for the local and sql2016 SQL Server instances PS C:\\> Get-DbaAgentJob -SqlInstance localhost, sql2016 Example 3: Returns all SQL Agent Jobs named BackupData and BackupDiff from the local SQL Server instance PS C:\\> Get-DbaAgentJob -SqlInstance localhost -Job BackupData, BackupDiff Example 4: Returns all SQl Agent Jobs for the local SQL Server instances, except the BackupDiff Job PS C:\\> Get-DbaAgentJob -SqlInstance localhost -ExcludeJob BackupDiff Example 5: Returns all SQl Agent Jobs for the local SQL Server instances, excluding the disabled jobs PS C:\\> Get-DbaAgentJob -SqlInstance localhost -ExcludeDisabledJobs Example 6: Find all of your Jobs from SQL Server instances in the $servers collection, select the jobs you want to start... PS C:\\> $servers | Get-DbaAgentJob | Out-GridView -PassThru | Start-DbaAgentJob -WhatIf Find 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 Example 7: Exports all SSRS jobs from SQL instance sqlserver2014a to a file PS C:\\> Get-DbaAgentJob -SqlInstance sqlserver2014a | Where-Object Category -eq \"Report Server\" | Export-DbaScript -Path \"C:\\temp\\sqlserver2014a_SSRSJobs.sql\" Example 8: Finds all jobs on sqlserver2014a that T-SQL job steps associated with msdb database PS C:\\> Get-DbaAgentJob -SqlInstance sqlserver2014a -Database msdb Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies specific SQL Agent job names to retrieve. Accepts an array of job names for targeting multiple jobs. Use this when you need to check status or configuration of specific jobs instead of retrieving all jobs on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJob Excludes specific SQL Agent job names from the results. Accepts an array of job names to skip. Useful when you want most jobs except for specific ones like test jobs or jobs you're not responsible for managing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Filters jobs to only those containing T-SQL job steps that target specific databases. Essential for database-specific maintenance planning or identifying which jobs will be affected by database operations like restores or migrations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Category Filters jobs by their assigned category such as 'Database Maintenance', 'Report Server', or custom categories. Helpful for organizing job management tasks by functional area or finding jobs related to specific SQL Server features. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeCategory Excludes jobs from specific categories from the results. Accepts an array of category names. Use this to filter out jobs you don't manage, such as third-party application jobs or SSRS jobs when focusing on database maintenance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDisabledJobs Excludes disabled SQL Agent jobs from the results, showing only enabled jobs. Use this when focusing on active job monitoring or troubleshooting since disabled jobs won't execute. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeExecution Adds execution start date information for currently running jobs to the output. Essential for troubleshooting long-running jobs or monitoring active job execution in real-time. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use 'Local' when managing single-instance environments or 'MultiServer' when working with SQL Server multi-server administration setups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @(\"MultiServer\", \"Local\") | | Accepted Values | MultiServer,Local | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Job Returns 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. Default display properties (via Select-DefaultView): ComputerName: The name of the SQL Server computer InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the SQL Agent job Category: The category assigned to the job OwnerLoginName: The login that owns the job CurrentRunStatus: Current execution status (Idle, Running, etc.) CurrentRunRetryAttempt: Number of retry attempts for the current execution Enabled: Boolean indicating if the job is enabled (True/False) LastRunDate: DateTime of the last job execution LastRunOutcome: Outcome of the last execution (Succeeded, Failed, Cancelled, Retried, etc.) HasSchedule: Boolean indicating if the job has an associated schedule OperatorToEmail: Email address of the operator to notify on completion CreateDate: DateTime when the job was created StartDate: DateTime when the job started executing (only when -IncludeExecution is specified) *Additional properties available from the SMO Job object (accessible via Select-Object ):** JobId: Unique identifier (GUID) for the job JobType: Type of job (Local or MultiServer) JobSteps: Collection of job steps belonging to this job CategoryID: Internal ID of the job category Description: Job description/notes IsSystemObject: Boolean indicating if this is a system object Note: When -IncludeExecution is specified, the StartDate property is added to the default display properties showing when the currently executing job started. &nbsp;"
  },
  {
    "name": "Get-DbaAgentJobCategory",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "category"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgentJobCategory",
    "popularityRank": 484,
    "synopsis": "Retrieves SQL Server Agent job categories with usage counts and filtering options",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentJobCategory View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Agent job categories with usage counts and filtering options 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. Syntax Get-DbaAgentJobCategory [-SqlInstance] [[-SqlCredential] ] [[-Category] ] [[-CategoryType] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Return all the job categories PS C:\\> Get-DbaAgentJobCategory -SqlInstance sql1 Example 2: Return all the job categories that have the name &#39;Log Shipping&#39; PS C:\\> Get-DbaAgentJobCategory -SqlInstance sql1 -Category 'Log Shipping' Example 3: Return all the job categories that have a type MultiServerJob PS C:\\> Get-DbaAgentJobCategory -SqlInstance sstad-pc -CategoryType MultiServerJob Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 'Database Maintenance', 'Log Shipping', 'Replication', and custom categories created by DBAs. Use this when you need to check specific categories for job assignments or verify custom organizational schemes. If not specified, all job categories are returned. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CategoryType Filters job categories by their deployment type: 'LocalJob' for single-instance jobs, 'MultiServerJob' for Master Server/Target Server (MSX/TSX) environments, or 'None' for uncategorized jobs. Use this in MSX/TSX configurations to distinguish between locally managed jobs and multi-server jobs, or to identify jobs that haven't been assigned a proper category. If not specified, all category types are returned. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | LocalJob,MultiServerJob,None | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Agent.JobCategory Returns one JobCategory object per job category on the SQL Server instance. Custom properties are added to provide connection context and job count information. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the job category ID: The unique identifier of the job category CategoryType: The type of category (LocalJob, MultiServerJob, or None) JobCount: The number of jobs currently assigned to this category (integer) Additional properties available (from SMO JobCategory object): Parent: Reference to the parent JobServer object Urn: The Unified Resource Name that uniquely identifies the job category State: The state of the object (Existing, Creating, Dropping, Pending) All properties from the base SMO JobCategory object are accessible by using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaAgentJobHistory",
    "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'd find in SQL Server Management Studio's 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",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgentJobHistory",
    "popularityRank": 84,
    "synopsis": "Retrieves SQL Server Agent job execution history from msdb database for troubleshooting and compliance reporting.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentJobHistory View Source Klaas Vandenberghe (@PowerDbaKlaas) , Simone Bizzotto (@niphold) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Agent job execution history from msdb database for troubleshooting and compliance reporting. 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'd find in SQL Server Management Studio's Job Activity Monitor, but with powerful filtering and output options. The 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. Results 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. Historical data availability depends on your SQL Agent history cleanup settings - older executions may have been purged based on your retention configuration. https://msdn.microsoft.com/en-us/library/ms201680.aspx https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.agent.jobhistoryfilter(v=sql.120).aspx Syntax Get-DbaAgentJobHistory [-SqlCredential ] [-Job ] [-ExcludeJob ] [-StartDate ] [-EndDate ] [-OutcomeType {Failed | Succeeded | Retry | Cancelled | InProgress | Unknown}] [-ExcludeJobSteps] [-WithOutputFile] [-EnableException] [ ] Get-DbaAgentJobHistory -SqlInstance [-SqlCredential ] [-Job ] [-ExcludeJob ] [-StartDate ] [-EndDate ] [-OutcomeType {Failed | Succeeded | Retry | Cancelled | InProgress | Unknown}] [-ExcludeJobSteps] [-WithOutputFile] [-EnableException] [ ] Get-DbaAgentJobHistory [-SqlCredential ] [-Job ] [-ExcludeJob ] [-StartDate ] [-EndDate ] [-OutcomeType {Failed | Succeeded | Retry | Cancelled | InProgress | Unknown}] [-ExcludeJobSteps] [-WithOutputFile] -JobCollection [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all SQL Agent Job execution results on the local default SQL Server instance PS C:\\> Get-DbaAgentJobHistory -SqlInstance localhost Example 2: Returns all SQL Agent Job execution results for the local and sql2016 SQL Server instances PS C:\\> Get-DbaAgentJobHistory -SqlInstance localhost, sql2016 Example 3: Returns all SQL Agent Job execution results for sql1 and sql2\\Inst2K17 PS C:\\> 'sql1','sql2\\Inst2K17' | Get-DbaAgentJobHistory Example 4: Returns all properties for all SQl Agent Job execution results on sql2\\Inst2K17 PS C:\\> Get-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 | Select-Object Example 5: Returns all properties for all SQl Agent Job execution results of the &#39;Output File Cleanup&#39; job on... PS C:\\> Get-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -Job 'Output File Cleanup' Returns all properties for all SQl Agent Job execution results of the 'Output File Cleanup' job on sql2\\Inst2K17. Example 6: Returns all properties for all SQl Agent Job execution results of the &#39;Output File Cleanup&#39; job on... PS C:\\> Get-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -Job 'Output File Cleanup' -WithOutputFile Returns all properties for all SQl Agent Job execution results of the 'Output File Cleanup' job on sql2\\Inst2K17, with additional properties that show the output filename path Example 7: Returns the SQL Agent Job execution results for the whole jobs on sql2\\Inst2K17, leaving out job step... PS C:\\> Get-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -ExcludeJobSteps Returns the SQL Agent Job execution results for the whole jobs on sql2\\Inst2K17, leaving out job step execution results. Example 8: Returns the SQL Agent Job execution results between 2017/05/22 00:00:00 and 2017/05/23 12:30:00 on... PS C:\\> Get-DbaAgentJobHistory -SqlInstance sql2\\Inst2K17 -StartDate '2017-05-22' -EndDate '2017-05-23 12:30:00' Returns the SQL Agent Job execution results between 2017/05/22 00:00:00 and 2017/05/23 12:30:00 on sql2\\Inst2K17. Example 9: Gets all jobs with the name that match the regex pattern &quot;backup&quot; and then gets the job history from those PS C:\\> Get-DbaAgentJob -SqlInstance sql2016 | Where-Object Name -Match backup | Get-DbaAgentJobHistory Gets 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. Example 10: Returns only the failed SQL Agent Job execution results for the sql2016 SQL Server instance PS C:\\> Get-DbaAgentJobHistory -SqlInstance sql2016 -OutcomeType Failed Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -JobCollection Accepts an array of SQL Server Management Objects (SMO) job objects instead of job names. Enables pipeline input from Get-DbaAgentJob. Use this when you need to filter jobs by complex criteria first, then get their history, such as jobs matching specific patterns or properties. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies specific SQL Agent jobs to retrieve history for by name. Accepts wildcards and arrays for multiple jobs. Use this when investigating specific job failures or monitoring particular maintenance routines instead of reviewing all job history. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJob Excludes specified jobs from the history results by name. Accepts arrays for multiple job exclusions. Useful when you want to review most jobs but skip noisy or less critical ones like frequent maintenance jobs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartDate Sets the earliest date and time for job history records to include. Defaults to 1900-01-01 to include all available history. Specify this when investigating issues within a specific timeframe or when older history isn't relevant to your troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1900-01-01 | -EndDate Sets the latest date and time for job history records to include. Defaults to current date and time. Use this with StartDate to focus on a specific time window when troubleshooting incidents or analyzing patterns during maintenance windows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $(Get-Date) | -OutcomeType Filters job history to only show executions with a specific completion result. Valid values are Failed, Succeeded, Retry, Cancelled, InProgress, Unknown. Most commonly used with 'Failed' when troubleshooting job failures or 'Succeeded' when verifying successful completion patterns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this when you need high-level job completion status for reporting or when step details aren't needed for your analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Essential when you need to locate and review job output files for troubleshooting failures or verifying job step results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Agent.JobExecutionHistory Returns 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 execution within a job. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Job: Name of the SQL Server Agent job (aliased from JobName property) StepName: Name of the job step that executed RunDate: DateTime when the execution started StartDate: DateTime when the execution started (formatted as DbaDatTime) EndDate: DateTime when the execution completed, calculated from RunDate plus duration Duration: PrettyTimeSpan formatted duration (e.g., \"00:05:23\") calculated from RunDuration Status: Human-readable execution status (Failed, Succeeded, Retry, or Canceled) OperatorEmailed: Boolean indicating if an operator was emailed about this execution Message: Job step execution message or failure reason When -WithOutputFile is specified, additional properties are included: OutputFileName: Resolved output file path with SQL Agent token placeholders replaced RemoteOutputFileName: UNC path to the output file on the remote server All additional SMO JobExecutionHistory properties are accessible (not displayed by default): JobID: Unique identifier for the job StepID: Step number (0 = job level, >0 = step level) Retries: Number of retries for this execution RunDuration: Duration in integer format (hhmmss) Use Select-Object to view all available properties. &nbsp;"
  },
  {
    "name": "Get-DbaAgentJobOutputFile",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgentJobOutputFile",
    "popularityRank": 378,
    "synopsis": "Retrieves output file paths configured for SQL Agent job steps",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentJobOutputFile View Source Rob Sewell (sqldbawithabeard.com) , Simone Bizzotto (@niphlod) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves output file paths configured for SQL Agent job steps 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. Syntax Get-DbaAgentJobOutputFile [-SqlInstance] [[-SqlCredential] ] [-Job ] [-ExcludeJob ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: This will return the configured paths to the output files for each of the job step of the The Agent Job Job... PS C:\\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Job 'The Agent Job' This will return the configured paths to the output files for each of the job step of the The Agent Job Job on the SERVERNAME instance Example 2: This will return the configured paths to the output files for each of the job step of all the Agent Jobs on... PS C:\\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME This will return the configured paths to the output files for each of the job step of all the Agent Jobs on the SERVERNAME instance Example 3: This will return the configured paths to the output files for each of the job step of the The Agent Job Job... PS C:\\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME,SERVERNAME2 -Job 'The Agent Job' This will return the configured paths to the output files for each of the job step of the The Agent Job Job on the SERVERNAME instance and SERVERNAME2 Example 4: This will return the configured paths to the output files for each of the job step of all the Agent Jobs on... PS C:\\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME | Out-GridView This will return the configured paths to the output files for each of the job step of all the Agent Jobs on the SERVERNAME instance and Pipe them to Out-GridView Example 5: This will return the configured paths to the output files for each of the job step of all the Agent Jobs on... PS C:\\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Verbose This will return the configured paths to the output files for each of the job step of all the Agent Jobs on the SERVERNAME instance and also show the job steps without an output file Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For 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 connection instead of a SQL login, ensure it contains a backslash. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Job Specifies specific SQL Agent jobs to examine for output file configurations. Accepts job names as strings and supports multiple values. Use this when you need to check output file paths for specific jobs rather than scanning all jobs on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJob Specifies SQL Agent jobs to exclude from the output file search. Accepts job names as strings and supports multiple values. Use this when you want to scan most jobs but skip specific ones, such as excluding system maintenance jobs or jobs you know don't use output files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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). Default display properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (service name) SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName format) Job: The name of the SQL Agent job containing this step JobStep: The name of the job step OutputFileName: The local file path where this job step writes its output RemoteOutputFileName: The UNC (Universal Naming Convention) path for accessing the output file from remote systems Additional properties available: StepId: The numeric identifier of this job step within the job (hidden from default display) &nbsp;"
  },
  {
    "name": "Get-DbaAgentJobStep",
    "description": "Collects comprehensive details about SQL Agent job steps across one or more SQL Server instances. Returns information about each step's 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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgentJobStep",
    "popularityRank": 139,
    "synopsis": "Retrieves detailed SQL Agent job step information including execution status and configuration from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentJobStep View Source Klaas Vandenberghe (@PowerDbaKlaas), powerdba.eu Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed SQL Agent job step information including execution status and configuration from SQL Server instances. Description Collects comprehensive details about SQL Agent job steps across one or more SQL Server instances. Returns information about each step's 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. Syntax Get-DbaAgentJobStep [[-SqlInstance] ] [[-SqlCredential] ] [[-Job] ] [[-ExcludeJob] ] [[-InputObject] ] [-ExcludeDisabledJobs] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all SQL Agent Job Steps on the local default SQL Server instance PS C:\\> Get-DbaAgentJobStep -SqlInstance localhost Example 2: Returns all SQL Agent Job Steps for the local and sql2016 SQL Server instances PS C:\\> Get-DbaAgentJobStep -SqlInstance localhost, sql2016 Example 3: Returns all SQL Agent Job Steps for the jobs named BackupData and BackupDiff from the local SQL Server... PS C:\\> Get-DbaAgentJobStep -SqlInstance localhost -Job BackupData, BackupDiff Returns all SQL Agent Job Steps for the jobs named BackupData and BackupDiff from the local SQL Server instance. Example 4: Returns all SQL Agent Job Steps for the local SQL Server instances, except for the BackupDiff Job PS C:\\> Get-DbaAgentJobStep -SqlInstance localhost -ExcludeJob BackupDiff Example 5: Returns all SQL Agent Job Steps for the local SQL Server instances, excluding the disabled jobs PS C:\\> Get-DbaAgentJobStep -SqlInstance localhost -ExcludeDisabledJobs Example 6: Find all of your Job Steps from SQL Server instances in the $servers collection PS C:\\> $servers | Get-DbaAgentJobStep Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies which SQL Agent jobs to include by name when retrieving job steps. Accepts wildcards for pattern matching. Use this when you need to examine steps for specific jobs like backup routines or maintenance tasks instead of processing all jobs on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJob Specifies which SQL Agent jobs to exclude by name when retrieving job steps. Accepts wildcards for pattern matching. Use this when you want to review most jobs but skip certain ones like test jobs or jobs that generate excessive output. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts SQL Agent job objects from the pipeline, typically from Get-DbaAgentJob output. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -ExcludeDisabledJobs Filters out disabled SQL Agent jobs from the results, showing only currently active jobs. Use this when troubleshooting production issues or monitoring active automation to avoid reviewing steps from jobs that aren't currently running. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Agent.JobStep Returns 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. Default display properties (via Select-DefaultView): ComputerName: The name of the SQL Server computer where the step is located InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) AgentJob: The name of the parent SQL Agent job containing this step Name: The name of the job step SubSystem: The subsystem type for the step (TransactSql, PowerShell, CmdExec, AnalysisCommand, AnalysisQuery, Ssis, etc.) LastRunDate: DateTime of the last execution of this step LastRunOutcome: Outcome of the last execution (Succeeded, Failed, Retry, Cancelled, Unknown, etc.) State: Current state of the step (Enabled, Disabled, etc.) *Additional properties available from the SMO JobStep object (accessible via Select-Object ):** ID: Internal step ID number CreateDate: DateTime when the step was created DateLastModified: DateTime when the step was last modified Command: The command or script to execute for this step CommandExecutionSuccessCode: Exit code indicating success (0 for success by default) DatabaseName: Database context for the step execution DatabaseUserName: User context for step execution Description: Step description/notes IncludeStepOutput: Boolean indicating if step output is included in job history IsLastStep: Boolean indicating if this is the last step in the job LogToTable: Boolean indicating if output is logged to a table OutputFileName: File path for step output logging ProxyID: ID of the proxy account used for this step RetryAttempts: Number of retry attempts if the step fails RetryInterval: Interval in minutes between retry attempts Note: The ComputerName, InstanceName, SqlInstance, and AgentJob properties are added by the function and are not native SMO properties. &nbsp;"
  },
  {
    "name": "Get-DbaAgentLog",
    "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's historical error logs (numbered 0-9, where 0 is the current log) so you don't 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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgentLog",
    "popularityRank": 326,
    "synopsis": "Retrieves SQL Server Agent error log entries for troubleshooting and monitoring",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentLog View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Agent error log entries for troubleshooting and monitoring 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's historical error logs (numbered 0-9, where 0 is the current log) so you don't 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. Syntax Get-DbaAgentLog [[-SqlInstance] ] [[-SqlCredential] ] [[-LogNumber] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the entire error log for the SQL Agent on sql01\\sharepoint PS C:\\> Get-DbaAgentLog -SqlInstance sql01\\sharepoint Example 2: Returns log numbers 3 and 6 for the SQL Agent on sql01\\sharepoint PS C:\\> Get-DbaAgentLog -SqlInstance sql01\\sharepoint -LogNumber 3, 6 Example 3: Returns the most recent SQL Agent error logs for &quot;sql2014&quot;,&quot;sql2016&quot; and &quot;sqlcluster\\sharepoint&quot; PS C:\\> $servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\" PS C:\\> $servers | Get-DbaAgentLog -LogNumber 0 Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need to examine historical agent activity or troubleshoot issues that occurred days or weeks ago, rather than just current entries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.LogFileEntry Returns one LogFileEntry object per log entry found. If multiple log numbers are specified, all entries from all requested log files are returned. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) LogDate: The date and time when the log entry was created (DateTime) ProcessInfo: The process ID or source component that created the entry (typically spid or component name) Text: The full text content of the log entry message Additional properties available (from SMO LogFileEntry object): Id: Unique identifier for the log entry All properties from the base SMO object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaAgentOperator",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "operator"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgentOperator",
    "popularityRank": 286,
    "synopsis": "Retrieves SQL Server Agent operators with their notification settings and related jobs and alerts.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentOperator View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Agent operators with their notification settings and related jobs and alerts. 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. Syntax Get-DbaAgentOperator [-SqlInstance] [[-SqlCredential] ] [[-Operator] ] [[-ExcludeOperator] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns any SQL Agent operators on serverA and serverB\\instanceB PS C:\\> Get-DbaAgentOperator -SqlInstance ServerA,ServerB\\instanceB Example 2: Returns all SQL Agent operators on serverA and serverB\\instanceB PS C:\\> 'ServerA','ServerB\\instanceB' | Get-DbaAgentOperator Example 3: Returns only the SQL Agent Operators Dba1 and Dba2 on ServerA PS C:\\> Get-DbaAgentOperator -SqlInstance ServerA -Operator Dba1,Dba2 Example 4: Returns all the SQL Agent operators on ServerA and ServerB, except the Dba3 operator PS C:\\> Get-DbaAgentOperator -SqlInstance ServerA,ServerB -ExcludeOperator Dba3 Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Operator Specifies which SQL Agent operators to retrieve by name. Accepts an array of operator names for targeting specific notification contacts. Use this when you need to check configuration or troubleshoot notification issues for particular operators instead of reviewing all operators on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeOperator Excludes specified SQL Agent operators from the results by name. Useful for filtering out test operators or disabled contacts during audits. Commonly used when reviewing active notification configurations while ignoring legacy or temporary operator accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Operator Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name where the SQL Server instance is running InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Name: The operator name ID: The unique ID of the operator in SQL Agent IsEnabled: Boolean indicating whether the operator is enabled to receive notifications EmailAddress: Email address configured for the operator LastEmail: DateTime when the operator last received an email notification Additional properties added by this command: RelatedJobs: Array of job objects (Microsoft.SqlServer.Management.Smo.Job) that notify this operator via email, net send, or pager RelatedAlerts: Array of alert names (strings) for which this operator is configured to receive notifications AlertLastEmail: DateTime when the operator last received notification from any alert Enabled: Boolean indicating the operator's enabled status (same as IsEnabled in default view) LastEmailDate: DateTime of last email notification (raw SMO property) *Other SMO properties available (select with Select-Object ):** FullyQualifiedName: Fully qualified name of the operator NetSendAddress: Net send address configured for the operator PagerAddress: Pager address configured for the operator PagerDayFridayEnd: End time for Friday pager notifications PagerDayFridayStart: Start time for Friday pager notifications PagerDayMondayEnd: End time for Monday pager notifications PagerDayMondayStart: Start time for Monday pager notifications PagerDaySaturdayEnd: End time for Saturday pager notifications PagerDaySaturdayStart: Start time for Saturday pager notifications PagerDaySundayEnd: End time for Sunday pager notifications PagerDaySundayStart: Start time for Sunday pager notifications PagerDayThursdayEnd: End time for Thursday pager notifications PagerDayThursdayStart: Start time for Thursday pager notifications PagerDayTuesdayEnd: End time for Tuesday pager notifications PagerDayTuesdayStart: Start time for Tuesday pager notifications PagerDayWednesdayEnd: End time for Wednesday pager notifications PagerDayWednesdayStart: Start time for Wednesday pager notifications SaturdayPagerStartTime: Saturday pager start time SaturdayPagerEndTime: Saturday pager end time State: Current state of the SMO object &nbsp;"
  },
  {
    "name": "Get-DbaAgentProxy",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "proxy"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgentProxy",
    "popularityRank": 0,
    "synopsis": "Retrieves SQL Server Agent proxy accounts and their associated credentials from target instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentProxy View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Agent proxy accounts and their associated credentials from target instances. Description Retrieves SQL Server Agent proxy accounts which allow job steps to execute under different security contexts than the SQL Agent service account. This function is essential for security auditing, compliance reporting, and troubleshooting job step execution permissions. Returns detailed information including proxy names, associated credentials, descriptions, and enabled status across multiple SQL Server instances. Syntax Get-DbaAgentProxy [-SqlInstance] [[-SqlCredential] ] [[-Proxy] ] [[-ExcludeProxy] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all SQL Agent proxies on serverA and serverB\\instanceB PS C:\\> Get-DbaAgentProxy -SqlInstance ServerA,ServerB\\instanceB Example 2: Returns all SQL Agent proxies on serverA and serverB\\instanceB PS C:\\> 'serverA','serverB\\instanceB' | Get-DbaAgentProxy Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Proxy Specifies which SQL Agent proxy accounts to retrieve by name. Supports wildcards for pattern matching. Use this to filter results when you only need specific proxy accounts instead of all proxies on the instance. Common when auditing specific service accounts or troubleshooting particular job step failures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeProxy Specifies which SQL Agent proxy accounts to exclude from results by name. Supports wildcards for pattern matching. Useful when you want to review all proxies except certain ones, such as excluding system or test proxies from security audits. Can be combined with the Proxy parameter for fine-grained filtering. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Agent.ProxyAccount Returns one ProxyAccount object per proxy account found on the target instance(s). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) InstanceName: The SQL Server instance name (service name) Name: The name of the proxy account ID: Unique identifier for the proxy account CredentialID: ID of the credential associated with this proxy CredentialIdentity: The Windows account identity of the associated credential CredentialName: The name of the credential used by this proxy Description: Description text for the proxy account IsEnabled: Boolean indicating if the proxy is enabled and available for use Additional properties available (from SMO ProxyAccount object): State: SMO object state (Existing, Creating, Pending, etc.) Urn: Uniform Resource Name for the SQL Server object Parent: Reference to the parent JobServer object All properties from the base SMO object are accessible via Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaAgentSchedule",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "schedule"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgentSchedule",
    "popularityRank": 153,
    "synopsis": "Retrieves SQL Agent shared schedules with detailed timing and recurrence information.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentSchedule View Source Chris McKeown (@devopsfu), devopsfu.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Agent shared schedules with detailed timing and recurrence information. 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. Syntax Get-DbaAgentSchedule [-SqlInstance] [[-SqlCredential] ] [[-Schedule] ] [[-ScheduleUid] ] [[-Id] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all SQL Agent Shared Schedules on the local default SQL Server instance PS C:\\> Get-DbaAgentSchedule -SqlInstance localhost Example 2: Returns all SQL Agent Shared Schedules for the local and sql2016 SQL Server instances PS C:\\> Get-DbaAgentSchedule -SqlInstance localhost, sql2016 Example 3: Returns the SQL Agent Shared Schedules with the Id of 3 PS C:\\> Get-DbaAgentSchedule -SqlInstance localhost, sql2016 -Id 3 Example 4: Returns the SQL Agent Shared Schedules with the UID PS C:\\> Get-DbaAgentSchedule -SqlInstance localhost, sql2016 -ScheduleUid 'bf57fa7e-7720-4936-85a0-87d279db7eb7' Example 5: Returns the &quot;Maintenance10min&quot; &amp; &quot;Maintenance60min&quot; schedules from the sql2016 SQL Server instance PS C:\\> Get-DbaAgentSchedule -SqlInstance sql2016 -Schedule \"Maintenance10min\",\"Maintenance60min\" Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schedule Specifies one or more schedule names to retrieve from the SQL Agent shared schedules collection. Use this when you need to examine specific schedules by their display names, such as checking timing details for maintenance windows or job execution patterns. Accepts multiple schedule names and supports wildcards for pattern matching. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ScheduleUid Specifies the GUID-based unique identifier of one or more shared schedules to retrieve. Use this when you need to target schedules by their immutable identifiers, particularly useful for automation scripts or when schedule names might change. Each shared schedule has a persistent UID that remains constant even if the schedule is renamed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Id Specifies the numeric identifier of one or more shared schedules to retrieve from SQL Agent. Use this when you know the internal ID numbers of specific schedules, often obtained from previous queries or database system tables. Schedule IDs are assigned sequentially by SQL Server and remain constant unless the schedule is deleted and recreated. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.SharedSchedule Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ScheduleName: The display name of the shared schedule ActiveStartDate: The date when the schedule becomes active (format depends on system locale) ActiveStartTimeOfDay: The time of day when the schedule becomes active ActiveEndDate: The date when the schedule stops being active (year 9999 indicates no end date) ActiveEndTimeOfDay: The time of day when the schedule stops being active DateCreated: Timestamp when the schedule was created in SQL Agent FrequencyTypes: How often the schedule runs (Once, Daily, Weekly, Monthly, MonthlyRelative, AutoStart, OnIdle) FrequencyInterval: The interval at which the schedule recurs (meaning depends on FrequencyTypes) FrequencySubDayTypes: How often within a day the schedule runs (None, Once, Seconds, Minutes, Hours) FrequencySubDayInterval: The interval in seconds, minutes, or hours between executions FrequencyRecurrenceFactor: The number of periods between schedule executions (e.g., 2 for every 2 weeks) FrequencyRelativeIntervals: Relative position for monthly schedules (First, Second, Third, Fourth, Last) IsEnabled: Boolean indicating whether the schedule is active and available for job execution JobCount: Number of SQL Server Agent jobs currently using this shared schedule ScheduleUid: The unique GUID identifier for this schedule (immutable even if schedule is renamed) Description: Human-readable description of the schedule timing pattern (auto-generated from frequency settings) Additional properties available from the SMO SharedSchedule object: Id: Numeric identifier for the shared schedule (assigned sequentially by SQL Server) Name: Display name of the shared schedule Owner: Login name that owns the schedule All properties from the base SMO object are accessible using Select-Object *, even though only default properties are displayed without explicit selection. &nbsp;"
  },
  {
    "name": "Get-DbaAgentServer",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "job",
      "agent"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgentServer",
    "popularityRank": 388,
    "synopsis": "Retrieves SQL Server Agent service configuration and status information",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgentServer View Source Claudio Silva (@claudioessilva), claudioessilva.eu Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Agent service configuration and status information 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. Syntax Get-DbaAgentServer [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns SQL Agent Server on the local default SQL Server instance PS C:\\> Get-DbaAgentServer -SqlInstance localhost Example 2: Returns SQL Agent Servers for the localhost and sql2016 SQL Server instances PS C:\\> Get-DbaAgentServer -SqlInstance localhost, sql2016 Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Agent.JobServer Returns one JobServer object per instance. The object represents the SQL Server Agent configuration for that instance. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (service name) SqlInstance: The full SQL Server instance name (computer\\instance or computer for default instance) AgentDomainGroup: The Active Directory domain group for SQL Server Agent AgentLogLevel: The verbosity level for SQL Server Agent error log (Errors, Warnings, Informational, etc.) AgentMailType: The mail system used by SQL Server Agent (SqlAgentMail or DatabaseMail) AgentShutdownWaitTime: The number of seconds SQL Server waits for Agent to shut down during restart ErrorLogFile: Full path to the SQL Server Agent error log file IdleCpuDuration: The number of seconds CPU must remain below threshold to be considered idle (seconds) IdleCpuPercentage: The CPU usage percentage threshold below which CPU is considered idle (percent) IsCpuPollingEnabled: Boolean indicating if CPU idle condition monitoring is enabled JobServerType: The role of the server in SQL Server Agent topology (Master, Target, etc.) LoginTimeout: The timeout period for Agent connections to SQL Server (seconds) JobHistoryIsEnabled: Boolean indicating if job history collection is enabled (computed from MaximumHistoryRows) MaximumHistoryRows: The maximum number of job history rows to retain in MSDB; -1 for unlimited MaximumJobHistoryRows: The maximum number of history rows to retain per individual job MsxAccountCredentialName: The credential name for Multi-Server Administration master account MsxAccountName: The login account for Multi-Server Administration MsxServerName: The name of the Multi-Server Administration master server Name: The name of the JobServer instance NetSendRecipient: The recipient for legacy net send notifications from SQL Server Agent ServiceAccount: The user account running the SQL Server Agent service ServiceStartMode: The startup mode of the SQL Server Agent service (Automatic, Manual, Disabled) SqlAgentAutoStart: Boolean indicating if SQL Server Agent starts automatically with SQL Server SqlAgentMailProfile: The name of the legacy SQL Agent Mail profile for notifications SqlAgentRestart: Boolean indicating if SQL Server Agent automatically restarts if stopped unexpectedly SqlServerRestart: Boolean indicating if SQL Server Agent can restart the SQL Server service State: The current state of the SQL Server Agent service (Running, Stopped, etc.) SysAdminOnly: Boolean indicating if only sysadmin-level users can access SQL Server Agent Additional properties available (from SMO JobServer object): AlertCategories: Collection of alert categories configured on this instance Alerts: Collection of alerts configured on this instance AlertSystem: The alert system configuration object DatabaseEngineEdition: The edition of SQL Server Database Engine (Enterprise, Standard, Express, etc.) DatabaseEngineType: The type of Database Engine (Standalone, SqlAzureDatabase, etc.) DatabaseMailProfile: The name of the Database Mail profile used for alerts and notifications ExecutionManager: The job execution manager object HostLoginName: The login name of the host running SQL Server Agent JobCategories: Collection of job categories configured on this instance Jobs: Collection of SQL Server Agent jobs configured on this instance LocalHostAlias: The alias SQL Server Agent uses to reference the local server OperatorCategories: Collection of operator categories configured on this instance Operators: Collection of database mail operators configured on this instance Parent: The parent SQL Server object ProxyAccounts: Collection of proxy accounts configured for job step execution ReplaceAlertTokensEnabled: Boolean indicating if alert notification tokens are replaced with actual values SaveInSentFolder: Boolean indicating if copies of agent notifications are saved to Database Mail sent items ServerVersion: The version of SQL Server SharedSchedules: Collection of shared job schedules configured on this instance TargetServerGroups: Collection of target server groups for Multi-Server Administration TargetServers: Collection of target servers for Multi-Server Administration WriteOemErrorLog: Boolean indicating if SQL Server Agent writes errors to the Windows Application Event Log All properties from the SMO JobServer object are accessible via Select-Object * even though only the default properties are displayed without explicit column selection. &nbsp;"
  },
  {
    "name": "Get-DbaAgHadr",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgHadr",
    "popularityRank": 95,
    "synopsis": "Retrieves the High Availability Disaster Recovery (HADR) service status for SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgHadr View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves the High Availability Disaster Recovery (HADR) service status for SQL Server instances. 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. Syntax Get-DbaAgHadr [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a status of the Hadr setting for sql2016 SQL Server instance PS C:\\> Get-DbaAgHadr -SqlInstance sql2016 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance queried, containing the current HADR status. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (e.g., MSSQLSERVER or named instance) SqlInstance: The full SQL Server instance identifier in the format ComputerName\\InstanceName or instance name for default IsHadrEnabled: Boolean value indicating whether HADR is enabled ($true) or disabled ($false) on the instance &nbsp;"
  },
  {
    "name": "Get-DbaAgListener",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgListener",
    "popularityRank": 120,
    "synopsis": "Retrieves availability group listener configurations including IP addresses and port numbers.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgListener View Source Viorel Ciucu (@viorelciucu) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves availability group listener configurations including IP addresses and port numbers. 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. Syntax Get-DbaAgListener [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Listener] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all listeners found on sql2017a PS C:\\> Get-DbaAgListener -SqlInstance sql2017a Example 2: Returns all listeners found on sql2017a on sql2017a for the availability group AG-a PS C:\\> Get-DbaAgListener -SqlInstance sql2017a -AvailabilityGroup AG-a Example 3: Returns all listeners found on sql2017a on sql2017a for the availability group OPP PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup OPP | Get-DbaAgListener Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies which availability groups to include when retrieving listener information. Supports wildcards for pattern matching. Use this when you only need listener details for specific availability groups rather than all groups on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Listener Specifies which availability group listeners to return by name. Accepts multiple listener names for filtering results. Use this when you need to examine specific listeners during troubleshooting or when documenting particular AG configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations. Use this when chaining commands to get listener details for specific availability groups you've already retrieved. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityGroupListener Returns one listener object per availability group listener found on the specified instance(s) or availability group(s). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance hosting the Availability Group InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) AvailabilityGroup: Name of the Availability Group that owns this listener Name: Network name of the listener that clients use for connections PortNumber: TCP port number for client connections (default 1433) ClusterIPConfiguration: WSFC cluster IP resource configuration details Additional properties available (from SMO AvailabilityGroupListener object): AvailabilityGroupListenerIPAddresses: Collection of IP address configurations for this listener (one per subnet in multi-subnet scenarios) Urn: Unique resource name for programmatic identification State: SMO object state (Existing, Creating, Pending, etc.) Properties: Collection of object properties and their values All properties from the base SMO AvailabilityGroupListener object are accessible via Select-Object * even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Get-DbaAgReplica",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaAgReplica",
    "popularityRank": 51,
    "synopsis": "Retrieves availability group replica configuration and status information from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgReplica View Source Shawn Melton (@wsmelton) , Chrissy LeMaire (@cl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves availability group replica configuration and status information from SQL Server instances. 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. Syntax Get-DbaAgReplica [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Replica] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns basic information on all the availability group replicas found on sql2017a PS C:\\> Get-DbaAgReplica -SqlInstance sql2017a Example 2: Shows basic information on the replicas found on availability group SharePoint on sql2017a PS C:\\> Get-DbaAgReplica -SqlInstance sql2017a -AvailabilityGroup SharePoint Example 3: Returns full object properties on all availability group replicas found on sql2017a PS C:\\> Get-DbaAgReplica -SqlInstance sql2017a | Select-Object Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies which availability groups to query for replica information. Accepts multiple values and wildcards for pattern matching. Use this when you need to focus on specific availability groups instead of retrieving replicas from all AGs on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Replica Filters results to return only the specified replica names. Accepts multiple values for querying specific replicas across availability groups. Use this when troubleshooting specific replicas or when you only need information about particular secondary replicas in your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group objects piped from Get-DbaAvailabilityGroup, allowing for more efficient processing in pipeline scenarios. Use this when chaining commands or when you already have availability group objects and want to retrieve their replica details without additional server queries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityReplica Returns 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 group. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance hosting the replica InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) AvailabilityGroup: Name of the availability group that contains this replica Name: The name/display name of the availability group replica Role: Current role of the replica (Primary or Secondary) ConnectionState: Current connectivity state with the local server (Connected, Disconnected, etc.) RollupSynchronizationState: Overall database synchronization state (NotSynchronizing, Synchronizing, Synchronized, Reverting, Initializing) AvailabilityMode: Commit mode (SynchronousCommit or AsynchronousCommit) BackupPriority: Backup preference priority value (0-100, where higher values are preferred for backups) EndpointUrl: Database mirroring endpoint URL used for replica communication (format: TCP://hostname:port) SessionTimeout: Session timeout in seconds for detecting communication failures (minimum 10 seconds recommended) FailoverMode: Failover capability (Automatic or Manual) ReadonlyRoutingList: Priority-ordered list of secondary replicas for routing read-only connections Additional properties available (from SMO AvailabilityReplica object): ConnectionModeInPrimaryRole: Connection mode when this replica is primary (AllowAllConnections or AllowReadWriteConnections) ConnectionModeInSecondaryRole: Connection mode when this replica is secondary (AllowNoConnections, AllowReadIntentConnectionsOnly, or AllowAllConnections) ReadonlyRoutingConnectionUrl: Connection URL used by read-only routing for this replica SeedingMode: Database seeding mode (Automatic or Manual) - SQL Server 2016+ Parent: Reference to the parent AvailabilityGroup object State: The state of the SMO object (Existing, Creating, Pending, etc.) Urn: Uniform resource name for programmatic identification of the replica All properties from the base SMO AvailabilityReplica object are accessible using Select-Object , even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Get-DbaAgRingBuffer",
    "description": "This command queries sys.dm_os_ring_buffers for HADR-specific ring buffer types to provide diagnostic\ninformation about Always On availability groups. These ring buffers record state transitions, role changes,\ncommit activity, and transport state events useful for troubleshooting AG health and failover issues.\n\nAs noted in Microsoft's documentation, the ring buffers are not officially supported, but they provide\nvaluable post-mortem diagnostic data, especially when SQL Server stops responding or has crashed.\n\nReference: https://learn.microsoft.com/en-us/sql/database-engine/availability-groups/windows/always-on-ring-buffers",
    "category": "Advanced Features",
    "tags": [
      "diagnostic",
      "buffer",
      "hadr",
      "availabilitygroup",
      "ag",
      "alwayson"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAgRingBuffer",
    "popularityRank": 0,
    "synopsis": "Retrieves Always On availability group diagnostic data from SQL Server's internal HADR ring buffers.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAgRingBuffer View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Always On availability group diagnostic data from SQL Server's internal HADR ring buffers. Description This command queries sys.dm_os_ring_buffers for HADR-specific ring buffer types to provide diagnostic information about Always On availability groups. These ring buffers record state transitions, role changes, commit activity, and transport state events useful for troubleshooting AG health and failover issues. As noted in Microsoft's documentation, the ring buffers are not officially supported, but they provide valuable post-mortem diagnostic data, especially when SQL Server stops responding or has crashed. Reference: https://learn.microsoft.com/en-us/sql/database-engine/availability-groups/windows/always-on-ring-buffers Syntax Get-DbaAgRingBuffer [-SqlInstance] [[-SqlCredential] ] [[-RingBufferType] ] [[-CollectionMinutes] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns HADR ring buffer records from the last 60 minutes from the sql2019 instance PS C:\\> Get-DbaAgRingBuffer -SqlInstance sql2019 Example 2: Returns HADR ring buffer records from the last 240 minutes from the sql2019 instance PS C:\\> Get-DbaAgRingBuffer -SqlInstance sql2019 -CollectionMinutes 240 Example 3: Returns only RING_BUFFER_HADRDBMGR_API records from the last 60 minutes from the sql2019 instance PS C:\\> Get-DbaAgRingBuffer -SqlInstance sql2019 -RingBufferType RING_BUFFER_HADRDBMGR_API Example 4: Returns API and transport state records from sql2019 PS C:\\> Get-DbaAgRingBuffer -SqlInstance sql2019 -RingBufferType RING_BUFFER_HADRDBMGR_API, RING_BUFFER_HADR_TRANSPORT_STATE Example 5: Returns all HADR ring buffer records from sql2019 and sql2022 PS C:\\> 'sql2019', 'sql2022' | Get-DbaAgRingBuffer Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. To use: $cred = Get-Credential, this pass this $cred to the param. Windows Authentication will be used if SqlCredential is not specified. To connect as a different Windows user, run PowerShell as that user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RingBufferType Specifies which HADR ring buffer types to query. Defaults to all four HADR ring buffer types. Valid values: RING_BUFFER_HADRDBMGR_API : State transitions at the API level RING_BUFFER_HADRDBMGR_STATE : Database manager state change records RING_BUFFER_HADRDBMGR_COMMIT : Commit-level activity records RING_BUFFER_HADR_TRANSPORT_STATE: Connection and transport state transitions | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | RING_BUFFER_HADRDBMGR_API,RING_BUFFER_HADRDBMGR_STATE,RING_BUFFER_HADRDBMGR_COMMIT,RING_BUFFER_HADR_TRANSPORT_STATE | -CollectionMinutes Specifies how many minutes of historical data to retrieve from the ring buffer. Defaults to 60 minutes. Use this to extend the analysis window when investigating longer-term AG issues or to focus on recent activity with shorter periods. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 60 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per ring buffer record retrieved from the SQL Server instance. Properties: ComputerName : The computer name of the SQL Server instance InstanceName : The SQL Server instance name SqlInstance : The full SQL Server instance name (computer\\instance) RingBufferType : The type of ring buffer (e.g. RING_BUFFER_HADRDBMGR_API) RecordId : The unique record identifier from the ring buffer entry EventTime : Approximate DateTime of the event (in local server time) Record : The raw XML record containing event-specific diagnostic fields &nbsp;"
  },
  {
    "name": "Get-DbaAvailabilityGroup",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaAvailabilityGroup",
    "popularityRank": 32,
    "synopsis": "Retrieves Availability Group configuration and status information from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAvailabilityGroup View Source Shawn Melton (@wsmelton) , Chrissy LeMaire (@cl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Availability Group configuration and status information from SQL Server instances. Description Retrieves detailed Availability Group information including replica roles, cluster configuration, database membership, and listener details from SQL Server 2012+ instances. This 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. Syntax Get-DbaAvailabilityGroup [-SqlInstance] [[-SqlCredential] ] [[-AvailabilityGroup] ] [-IsPrimary] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns basic information on all the Availability Group(s) found on sqlserver2014a PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2014a Example 2: Shows basic information on the Availability Group AG-a on sqlserver2014a PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2014a -AvailabilityGroup AG-a Example 3: Returns full object properties on all Availability Group(s) on sqlserver2014a PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2014a | Select-Object Example 4: Returns the SQL Server instancename of the primary replica as a string PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2014a | Select-Object -ExpandProperty PrimaryReplicaServerName Example 5: Returns true/false if the server, sqlserver2014a, is the primary replica for AG-a Availability Group PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2014a -AvailabilityGroup AG-a -IsPrimary Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies one or more Availability Group names to filter results to specific AGs. Supports wildcards for pattern matching. Use this when you need to check status or configuration of particular AGs rather than retrieving information for all AGs on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IsPrimary Returns a boolean value indicating whether the queried SQL Server instance is currently serving as the Primary replica for each Availability Group. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityGroup Returns 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 SqlInstance. Default display properties (without -IsPrimary): ComputerName: The computer name of the SQL Server instance hosting the availability group InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) LocalReplicaRole: The role of the current replica in the availability group (Primary or Secondary) AvailabilityGroup: Name of the availability group (from the Name property) PrimaryReplica: The server name of the primary replica (from PrimaryReplicaServerName property) ClusterType: Type of cluster supporting the availability group (Wsfc, External, None) DtcSupportEnabled: Boolean indicating if Distributed Transaction Coordinator support is enabled AutomatedBackupPreference: Preference for automated backups (Primary, SecondaryOnly, Secondary, None) AvailabilityReplicas: Collection of replicas that are part of this availability group AvailabilityDatabases: Collection of databases that are part of this availability group AvailabilityGroupListeners: Collection of listeners configured for this availability group Default display properties (with -IsPrimary): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) AvailabilityGroup: Name of the availability group (from the Name property) IsPrimary: Boolean indicating whether the queried instance is the primary replica for this availability group Additional properties available from the SMO AvailabilityGroup object: Name: Name of the availability group DtcSupportEnabled: Boolean for DTC support AutomatedBackupPreference: Backup preference setting FailureConditionLevel: Failure condition threshold level HealthCheckTimeout: Health check timeout in milliseconds BasicAvailabilityGroup: Boolean indicating if this is a basic availability group (SQL Server 2016+) DatabaseHealthTrigger: Boolean for database health trigger setting Urn: Uniform Resource Name for the SMO object All properties from the SMO AvailabilityGroup object are accessible by using Select-Object . &nbsp;"
  },
  {
    "name": "Get-DbaAvailableCollation",
    "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.",
    "category": "Utilities",
    "tags": [
      "collation",
      "configuration",
      "management"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaAvailableCollation",
    "popularityRank": 423,
    "synopsis": "Retrieves all available collations from SQL Server instances with detailed locale and code page information",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaAvailableCollation View Source Bryan Hamby (@galador) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves all available collations from SQL Server instances with detailed locale and code page information 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. This information is essential when creating new databases, changing database collations, or planning migrations where collation compatibility matters. The function enhances the raw collation data with human-readable code page and locale descriptions to help DBAs make informed collation choices. Only connect permission is required to retrieve this information. Syntax Get-DbaAvailableCollation [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all the collations from server sql2016 using NT authentication PS C:\\> Get-DbaAvailableCollation -SqlInstance sql2016 Required Parameters -SqlInstance The target SQL Server instance or instances. Only connect permission is required. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Collation Returns one collation object per collation supported by each SQL Server instance, enhanced with human-readable descriptions. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server service name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The collation name (e.g., SQL_Latin1_General_CP1_CI_AS) CodePage: The numeric code page identifier (e.g., 1252 for Latin1) CodePageName: Human-readable code page encoding name (e.g., iso-8859-1) LocaleID: The numeric locale identifier (LCID) representing the language/culture LocaleName: Human-readable locale/language name (e.g., English_United States, Japanese_Unicode) Description: SQL Server collation description with sorting and case sensitivity information *Additional properties available from SMO Collation object (use Select-Object to access):* BinaryOrder: Boolean indicating if the collation uses binary sort order BuiltInComparisonStyle: The comparison style constant used by SQL Server IsCodePageCompatible: Boolean indicating code page compatibility IsCaseSensitive: Boolean indicating if the collation is case-sensitive IsAccentSensitive: Boolean indicating if the collation is accent-sensitive IsKanaTypeSensitive: Boolean indicating if the collation distinguishes between Hiragana and Katakana IsWidthSensitive: Boolean indicating if the collation distinguishes between full-width and half-width characters All properties from the base SMO Collation object are accessible even though only default properties are displayed without using Select-Object . &nbsp;"
  },
  {
    "name": "Get-DbaBackupDevice",
    "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.",
    "category": "Backup & Restore",
    "tags": [
      "backup",
      "general"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaBackupDevice",
    "popularityRank": 409,
    "synopsis": "Retrieves configured backup devices from SQL Server instances for inventory and management",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaBackupDevice View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves configured backup devices from SQL Server instances for inventory and management 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. Syntax Get-DbaBackupDevice [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all Backup Devices on the local default SQL Server instance PS C:\\> Get-DbaBackupDevice -SqlInstance localhost Example 2: Returns all Backup Devices for the local and sql2016 SQL Server instances PS C:\\> Get-DbaBackupDevice -SqlInstance localhost, sql2016 Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.BackupDevice Returns one BackupDevice object per configured backup device on each SQL Server instance. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) Name: The logical name of the backup device BackupDeviceType: The type of backup device (Disk, Tape, or Url) PhysicalLocation: The physical path or location of the backup device (file path, tape device, or URL) SkipTapeLabel: Boolean indicating whether to skip tape label validation Additional properties available (from SMO BackupDevice object): Urn: The Uniform Resource Name identifying the backup device State: The state of the SMO object (Existing, Creating, Pending, etc.) Parent: Reference to the parent Server object All properties from the SMO BackupDevice object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaBackupInformation",
    "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.",
    "category": "Backup & Restore",
    "tags": [
      "disasterrecovery",
      "backup",
      "restore"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaBackupInformation",
    "popularityRank": 52,
    "synopsis": "Scans backup files and reads their headers to create structured backup history objects for restore operations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaBackupInformation View Source Chrissy LeMaire (@cl) , Stuart Moore (@napalmgram) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Scans backup files and reads their headers to create structured backup history objects for restore operations 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. The 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. By 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. Special support is included for Ola Hallengren maintenance solution backup folder structures, which can significantly speed up scanning of organized backup directories. Syntax Get-DbaBackupInformation -Path -SqlInstance [-SqlCredential ] [-DatabaseName ] [-SourceInstance ] [-NoXpDirTree] [-NoXpDirRecurse] [-DirectoryRecurse] [-EnableException] [-MaintenanceSolution] [-IgnoreLogBackup] [-IgnoreDiffBackup] [-ExportPath ] [-StorageCredential ] [-Anonymise] [-NoClobber] [-PassThru] [ ] Get-DbaBackupInformation -Path [-DatabaseName ] [-SourceInstance ] [-EnableException] [-MaintenanceSolution] [-IgnoreLogBackup] [-IgnoreDiffBackup] [-ExportPath ] [-StorageCredential ] [-Import] [-Anonymise] [-NoClobber] [-PassThru] [ ] &nbsp; Examples &nbsp; Example 1: Will use the Server1 instance to recursively read all backup files under c:\\backups, and return a dbatools... PS C:\\> Get-DbaBackupInformation -SqlInstance Server1 -Path c:\\backups\\ -DirectoryRecurse Will use the Server1 instance to recursively read all backup files under c:\\backups, and return a dbatools BackupHistory object Example 2: This example creates backup history output from server1 and copies the file to the remote machine in order to... PS C:\\> Get-DbaBackupInformation -SqlInstance Server1 -Path c:\\backups\\ -DirectoryRecurse -ExportPath c:\\store\\BackupHistory.xml PS C:\\> robocopy c:\\store\\ \\\\remoteMachine\\C$\\store\\ BackupHistory.xml PS C:\\> Get-DbaBackupInformation -Import -Path c:\\store\\BackupHistory.xml | Restore-DbaDatabase -SqlInstance Server2 -TrustDbBackupHistory This 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. Example 3: -TrustDbBackupHistory In this example we gather backup information, export it to an xml file, and then pass... PS C:\\> Get-DbaBackupInformation -SqlInstance Server1 -Path c:\\backups\\ -DirectoryRecurse -ExportPath C:\\store\\BackupHistory.xml -PassThru | Restore-DbaDatabase -SqlInstance Server2 -TrustDbBackupHistory In this example we gather backup information, export it to an xml file, and then pass it on through to Restore-DbaDatabase. This allows us to repeat the restore without having to scan all the backup files again Example 4: -ExportPath C:\\backupHistory.xml This lets you keep a record of all backup history from the last month on... PS C:\\> Get-ChildItem c:\\backups\\ -recurse -files | Where-Object {$_.extension -in ('.bak','.trn') -and $_.LastWriteTime -gt (get-date).AddMonths(-1)} | Get-DbaBackupInformation -SqlInstance Server1 -ExportPath C:\\backupHistory.xml This lets you keep a record of all backup history from the last month on hand to speed up refreshes Example 5: Scan the unc folder \\\\network\\backups with Server1, and then scan the C:\\backups folder on Server2 not using... PS C:\\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\network\\backups PS C:\\> $Backups += Get-DbaBackupInformation -SqlInstance Server2 -NoXpDirTree -Path c:\\backups Scan the unc folder \\\\network\\backups with Server1, and then scan the C:\\backups folder on Server2 not using xp_dirtree, adding the results to the first set. Example 6: When MaintenanceSolution is indicated we know we are dealing with the output from Ola Hallengren backup... PS C:\\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\network\\backups -MaintenanceSolution When 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 shortcut scanning all the files as we have nothing to work with Example 7: As we know we are dealing with an Ola Hallengren style backup folder from the MaintenanceSolution switch... PS C:\\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\network\\backups -MaintenanceSolution -IgnoreLogBackup As 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 log backups. Note this also means they WON'T be restored Example 8: Gets backup information from an S3-compatible object storage location PS C:\\> $Backups = Get-DbaBackupInformation -SqlInstance sql2022 -Path s3://s3.us-west-2.amazonaws.com/mybucket/backups/mydb.bak -StorageCredential MyS3Credential Gets backup information from an S3-compatible object storage location. Requires SQL Server 2022 or higher. The credential must be configured with Identity = 'S3 Access Key' and Secret containing the access key and secret key. Required Parameters -Path Path to SQL Server backup files. Paths passed in as strings will be scanned using the desired method, default is a non recursive folder scan Accepts multiple paths separated by ',' Or it can consist of FileInfo objects, such as the output of Get-ChildItem or Get-Item. This allows you to work with your own file structures as needed | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -SqlInstance The SQL Server instance to be used to read the headers of the backup files | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DatabaseName An array of Database Names to filter by. If empty all databases are returned. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 parsed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoXpDirRecurse If specified, this switch changes xp_dirtree behavior to not recurse the folder structure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DirectoryRecurse If specified the provided path/directory will be traversed (only applies if not using XpDirTree) | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MaintenanceSolution This switch tells the function that the folder is the root of a Ola Hallengren backup folder | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. For all other scenarios we need to read the file headers to be sure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. For all other scenarios we need to read the file headers to be sure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StorageCredential The name of the SQL Server credential to be used if restoring from cloud storage (Azure Blob Storage or S3-compatible object storage). For Azure, this is typically a credential with access to the storage account. For S3, this should be a credential created with Identity 'S3 Access Key' matching the S3 URL path. | Property | Value | | --- | --- | | Alias | AzureCredential,S3Credential | | Required | False | | Pipeline | false | | Default Value | | -Import When specified along with a path the command will import a previously exported BackupHistory object from an xml file. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Anonymise If specified we will output the results with ComputerName, InstanceName, Database, UserName, Paths, and Logical and Physical Names hashed out This options is mainly for use if we need you to submit details for fault finding to the dbatools team | Property | Value | | --- | --- | | Alias | Anonymize | | Required | False | | Pipeline | false | | Default Value | False | -NoClobber If specified will stop Export from overwriting an existing file, the default is to overwrite | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Database.BackupHistory Returns 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 supports being piped directly into that command. The object includes the following properties: ComputerName: The computer name where the backup originated from (SQL Server host) InstanceName: The SQL Server instance name where the backup was taken SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName) Database: The name of the database that was backed up UserName: The Windows/SQL login that performed the backup Start: DateTime of when the backup started End: DateTime of when the backup finished Duration: TimeSpan representing the duration of the backup operation Type: String indicating the backup type (Full, Differential, or Log) Path: String array of file paths containing the backup files FullName: Array of backup file paths (same as Path) FileList: Array of PSCustomObjects containing backup file details with properties: Type (MDF/LDF/NDF), LogicalName, PhysicalName, Size TotalSize: Total size of the backup in bytes CompressedBackupSize: Size of the compressed backup in bytes BackupSetId: GUID uniquely identifying this backup set Position: Position of the backup within the device DeviceType: The type of backup device (typically 'Disk') FirstLsn: BigInt representing the first log sequence number in the backup DatabaseBackupLsn: BigInt representing the database backup LSN for log backups CheckpointLSN: BigInt representing the checkpoint LSN LastLsn: BigInt representing the last log sequence number in the backup SoftwareVersionMajor: Major version of SQL Server that created the backup RecoveryModel: The recovery model of the database (Simple, Full, or BulkLogged) IsCopyOnly: Boolean indicating if this is a copy-only backup When -Anonymise is specified, the following properties are hashed: ComputerName, InstanceName, SqlInstance, Database, UserName, Path, FullName, and file logical/physical names in FileList. When -Import is specified, the BackupHistory object is deserialized from the exported CliXml file, preserving all properties for later use with Restore-DbaDatabase. &nbsp;"
  },
  {
    "name": "Get-DbaBinaryFileTable",
    "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't 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.",
    "category": "Backup & Restore",
    "tags": [
      "migration",
      "backup",
      "export"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaBinaryFileTable",
    "popularityRank": 621,
    "synopsis": "Identifies tables containing binary columns and their associated filename columns for file extraction operations.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaBinaryFileTable View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies tables containing binary columns and their associated filename columns for file extraction operations. 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't sure which tables contain binary data or how the filenames are stored. The 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. Syntax Get-DbaBinaryFileTable [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Table] ] [[-Schema] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a table with binary columns which can be used with Export-DbaBinaryFile and Import-DbaBinaryFile PS C:\\> Get-DbaBinaryFileTable -SqlInstance sqlcs -Database test Example 2: Allows you to pick tables with columns to be exported by Export-DbaBinaryFile PS C:\\> Get-DbaBinaryFileTable -SqlInstance sqlcs -Database test | Out-GridView -Passthru | Export-DbaBinaryFile -Path C:\\temp Optional Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for tables containing binary columns. Accepts wildcards for pattern matching. Use this to limit the search scope when you know which databases might contain file storage tables, reducing scan time on large instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you already know which tables contain binary data, such as document storage tables or attachment tables in applications. Wrap table names with special characters in square brackets, and escape actual ] characters by doubling them. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Restricts the search to tables within specific database schemas. Accepts multiple schema names and wildcards. Useful for focusing on application-specific schemas that typically contain file storage tables, such as 'Documents' or 'Attachments' schemas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts table objects piped directly from Get-DbaDbTable, allowing you to pre-filter tables before binary column analysis. Use this approach when you want to combine complex table filtering with binary column detection in a pipeline workflow. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Table Returns one Table object for each table found containing binary columns (binary, varbinary, or image data types). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the table Schema: The schema name containing the table Name: The table name BinaryColumn: The name(s) of the column(s) containing binary data; multiple values if multiple binary columns exist FileNameColumn: The name of the column identified as containing filenames for extraction; empty if no column matches the pattern or multiple matches were found Additional properties available from the base SMO Table object include: IndexSpaceUsed: Space consumed by indexes on the table (bytes) DataSpaceUsed: Space consumed by table data (bytes) RowCount: Number of rows in the table HasClusteredIndex: Boolean indicating if the table has a clustered index IsPartitioned: Boolean indicating if the table uses partitioning (SQL Server 2005+) ChangeTrackingEnabled: Boolean indicating if change tracking is enabled (SQL Server 2008+) IsFileTable: Boolean indicating if the table is a FileTable (SQL Server 2012+) IsMemoryOptimized: Boolean indicating if the table is memory-optimized (SQL Server 2014+) IsNode: Boolean indicating if the table is a node table (SQL Server 2017+) IsEdge: Boolean indicating if the table is an edge table (SQL Server 2017+) FullTextIndex: Full-text index configuration for the table if present All properties from the SMO Table object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaBuild",
    "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.",
    "category": "Utilities",
    "tags": [
      "sqlbuild",
      "utility"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaBuild",
    "popularityRank": 46,
    "synopsis": "Retrieves detailed SQL Server build information including service pack, cumulative update, KB articles, and support lifecycle dates",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaBuild View Source Simone Bizzotto (@niphold) , Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed SQL Server build information including service pack, cumulative update, KB articles, and support lifecycle dates Description Identifies the specific build version of SQL Server instances and translates build numbers into meaningful patch levels with their corresponding KB articles. This function helps DBAs quickly determine what service packs and cumulative updates are installed, whether builds have been retired by Microsoft, and when support ends. You 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. The function maintains an offline reference index that can be updated online to ensure current patch information and accurate support lifecycle dates. Syntax Get-DbaBuild [[-Build] ] [[-Kb] ] [[-MajorVersion] ] [[-ServicePack] ] [[-CumulativeUpdate] ] [[-SqlInstance] ] [[-SqlCredential] ] [-Update] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns information about a build identified by &quot;12.00.4502&quot; (which is SQL 2014 with SP1 and CU11) PS C:\\> Get-DbaBuild -Build \"12.00.4502\" Example 2: Returns information about a build trying to fetch the most up to date index online PS C:\\> Get-DbaBuild -Build \"12.00.4502\" -Update Returns 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 Example 3: Returns information builds identified by these versions strings PS C:\\> Get-DbaBuild -Build \"12.0.4502\",\"10.50.4260\" Example 4: Integrate with other cmdlets to have builds checked for all your registered servers on sqlserver2014a PS C:\\> Get-DbaRegServer -SqlInstance sqlserver2014a | Get-DbaBuild Optional Parameters -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\". Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Kb Looks up SQL Server build information using Knowledge Base article numbers. Accepts formats like \"KB4057119\" or just \"4057119\". Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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\". Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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\". Requires the -MajorVersion parameter and can be combined with -CumulativeUpdate to pinpoint exact patch levels. | Property | Value | | --- | --- | | Alias | SP | | Required | False | | Pipeline | false | | Default Value | 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. Requires the -MajorVersion parameter and works in combination with -ServicePack to identify exact patch levels within a service pack. | Property | Value | | --- | --- | | Alias | CU | | Required | False | | Pipeline | false | | Default Value | | -SqlInstance Target any number of instances, in order to return their build state. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when the function warns about stale index data or when you need the most current patch and support information for accurate compliance reporting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per build queried, containing SQL Server version and patch level information. Default properties when querying by -SqlInstance (all 9 properties displayed): SqlInstance: The SQL Server instance name (computer\\instance format) Build: The full build version number (e.g., 12.00.4502) NameLevel: SQL Server product name (e.g., \"SQL Server 2014\", \"SQL Server 2019\") SPLevel: Service pack level (e.g., \"SP1\", \"SP2\", or \"RTM\" for initial release) CULevel: Cumulative update level (e.g., \"CU11\", \"CU15\", or empty string if none applied) KBLevel: Array of Knowledge Base (KB) article numbers associated with this build BuildLevel: The normalized build version object SupportedUntil: DateTime indicating when this build version reaches end of support from Microsoft ReleaseDate: DateTime indicating when this build was released by Microsoft (null if not available in the index) MatchType: Match precision (\"Exact\" for precise match or \"Approximate\" if closest available match) Warning: Alert message if the build is retired or other issues detected (null if no warnings) Properties when querying by -Build, -Kb, or -MajorVersion (SqlInstance excluded from display): When using these parameters, the SqlInstance property is excluded from the default display but all 10 properties remain accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaClientAlias",
    "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.",
    "category": "Utilities",
    "tags": [
      "sqlclient",
      "alias"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaClientAlias",
    "popularityRank": 309,
    "synopsis": "Retrieves SQL Server client aliases from the Windows registry on local or remote computers",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaClientAlias View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server client aliases from the Windows registry on local or remote computers 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. Syntax Get-DbaClientAlias [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all SQL Server client aliases on the local computer PS C:\\> Get-DbaClientAlias Example 2: Gets all SQL Server client aliases on Workstationx PS C:\\> Get-DbaClientAlias -ComputerName workstationx Example 3: Logs into workstationx as ad\\sqldba then retrieves all SQL Server client aliases on Workstationx PS C:\\> Get-DbaClientAlias -ComputerName workstationx -Credential ad\\sqldba Example 4: Gets all SQL Server client aliases on Server1 and Server2 PS C:\\> 'Server1', 'Server2' | Get-DbaClientAlias Optional Parameters -ComputerName Specifies the computer(s) to retrieve SQL Server client aliases from. Accepts multiple computers via pipeline input. Use this when you need to audit client alias configurations across multiple workstations or servers in your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to remote computers using alternative credentials | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server client alias found in the registry. Each object represents a single alias configured on the specified computer(s). Properties: ComputerName: The name of the computer where the client alias is configured NetworkLibrary: The network protocol type for the alias (TCP/IP or Named Pipes) ServerName: The target server name or instance (with protocol prefix removed) AliasName: The alias name as defined in the registry AliasString: The complete registry value including protocol prefix (e.g., DBMSSOCN,servername,1433) Architecture: The registry hive architecture where the alias was found (32-bit or 64-bit) &nbsp;"
  },
  {
    "name": "Get-DbaClientProtocol",
    "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.",
    "category": "Utilities",
    "tags": [
      "management",
      "protocol",
      "os"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaClientProtocol",
    "popularityRank": 487,
    "synopsis": "Retrieves SQL Server client network protocol configuration and status from local or remote computers.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaClientProtocol View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server client network protocol configuration and status from local or remote computers. 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. The 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. Requires Local Admin rights on destination computer(s) and SQL Server 2005 or later. The client protocols can be enabled and disabled when retrieved via WSMan. Syntax Get-DbaClientProtocol [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the SQL Server related client protocols on computer sqlserver2014a PS C:\\> Get-DbaClientProtocol -ComputerName sqlserver2014a Example 2: Gets the SQL Server related client protocols on computers sql1, sql2 and sql3 PS C:\\> 'sql1','sql2','sql3' | Get-DbaClientProtocol Example 3: Gets the SQL Server related client protocols on computers sql1 and sql2, and shows them in a grid view PS C:\\> Get-DbaClientProtocol -ComputerName sql1,sql2 | Out-GridView Example 4: Disables the VIA ClientNetworkProtocol on computer sql2 PS C:\\> (Get-DbaClientProtocol -ComputerName sql2 | Where-Object { $_.DisplayName -eq 'Named Pipes' }).Disable() Disables the VIA ClientNetworkProtocol on computer sql2. If successful, return code 0 is shown. Optional Parameters -ComputerName Specifies the target computer(s) to retrieve SQL Server client protocol configuration from. Accepts computer names, IP addresses, or SQL Server instance names. Use this when you need to audit client protocol settings on remote servers or troubleshoot connectivity issues across multiple machines. Defaults to the local computer if not specified. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Credential object used to connect to the computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs *Microsoft.Management.Infrastructure.CimInstance#root\\Microsoft\\SQLServer\\ComputerManagement\\ClientNetworkProtocol Returns one ClientNetworkProtocol WMI object per protocol found on each computer. Default display properties (via Select-DefaultView): ComputerName: The computer name where the protocol is configured (alias for PSComputerName) DisplayName: The friendly display name of the protocol (alias for ProtocolDisplayName), such as \"TCP/IP\", \"Named Pipes\", \"Shared Memory\", or \"VIA\" DLL: The DLL file associated with the protocol (alias for ProtocolDll), typically sqlncli10.dll, sqlncli11.dll, or msoledbsql.dll Order: The protocol precedence order (alias for ProtocolOrder); lower numbers indicate higher priority, 0 means disabled IsEnabled: Boolean indicating if the protocol is enabled (based on ProtocolOrder value) Additional properties available from the WMI object: ProtocolDisplayName: Friendly name of the protocol ProtocolDll: Path to the protocol DLL file ProtocolOrder: Numeric precedence order (0 = disabled, 1+ = enabled and ordered) PSComputerName: Computer name from WMI PSPath: WMI object path PSProvider: WMI provider name Methods:* Enable(): Enables the protocol by calling the WMI SetEnable method; returns exit code 0 on success Disable(): Disables the protocol by calling the WMI SetDisable method; returns exit code 0 on success All properties and methods are accessible even though only default properties are displayed without using Select-Object . &nbsp;"
  },
  {
    "name": "Get-DbaCmConnection",
    "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.",
    "category": "Utilities",
    "tags": [
      "computermanagement",
      "cim"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaCmConnection",
    "popularityRank": 247,
    "synopsis": "Retrieves cached Windows Management and CIM connections used by dbatools commands",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaCmConnection View Source Friedrich Weinmann (@FredWeinmann) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves cached Windows Management and CIM connections used by dbatools commands 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. Syntax Get-DbaCmConnection [[-ComputerName] ] [[-UserName] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: List all cached connections PS C:\\> Get-DbaCmConnection Example 2: List the cached connection - if any - to the server sql2014 PS C:\\> Get-DbaCmConnection sql2014 Example 3: List all cached connection that use a username containing &quot;charles&quot; as default or override credentials PS C:\\> Get-DbaCmConnection -UserName \"charles\" Optional Parameters -ComputerName Filters cached connections by computer name or server name. Supports wildcards for pattern matching. Use this to check connections to specific SQL Server hosts or to search for connections matching a pattern like \"sqlprod\". | Property | Value | | --- | --- | | Alias | Filter | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -UserName Filters cached connections by the username in the stored credentials. Supports wildcards for pattern matching. Use this to find connections using specific service accounts or domain credentials. Will not match connections using integrated Windows authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Connection.ManagementConnection Returns one ManagementConnection object per cached connection matching the filter criteria. Each object represents a cached remote computer management connection that dbatools uses for Windows Management and CIM operations. Default display properties (displayed in table format): ComputerName: The name of the remote computer that this connection is cached for Available: Whether any connection protocol (CIM, WMI, or PowerShell Remoting) is available to this computer User: The username being used for this connection (either from stored credentials or the current Windows user) OverrideExplicitCredential: Boolean indicating if this connection ignores explicitly provided credentials and uses cached ones instead DisabledConnectionTypes: Which connection protocols are disabled for this computer (CimRM, CimDCOM, Wmi, PowerShellRemoting, or combinations) *Additional properties available on the object (use Select-Object to view all):** Credentials: The stored PSCredential object used for this connection (if any). Contains UserName property. UseWindowsCredentials: Boolean indicating if Windows authentication should be used DisableBadCredentialCache: Boolean indicating if failed credentials are not cached for this computer DisableCimPersistence: Boolean indicating if CIM sessions are not reused for this computer DisableCredentialAutoRegister: Boolean indicating if successful credentials are not automatically cached WindowsCredentialsAreBad: Boolean indicating if Windows authentication has been marked as non-functional CimRM: Connection test result for CIM over WinRM protocol (Success or Error) CimDCOM: Connection test result for CIM over DCOM protocol (Success or Error) Wmi: Connection test result for WMI protocol (Success or Error) PowerShellRemoting: Connection test result for PowerShell Remoting protocol (Success or Error) CimWinRMOptions: Advanced WinRM session options configured for this connection CimDCOMOptions: Advanced DCOM session options configured for this connection &nbsp;"
  },
  {
    "name": "Get-DbaCmObject",
    "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.",
    "category": "Utilities",
    "tags": [
      "computermanagement",
      "cim"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaCmObject",
    "popularityRank": 389,
    "synopsis": "Retrieves Windows system information from SQL Server hosts using WMI/CIM with intelligent connection fallback.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaCmObject View Source Friedrich Weinmann (@FredWeinmann) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows system information from SQL Server hosts using WMI/CIM with intelligent connection fallback. 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. Essential 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. Much of its behavior can be configured using Test-DbaCmConnection to pre-test and configure optimal connection methods for your environment. Syntax Get-DbaCmObject [-ClassName] [-ComputerName ] [-Credential ] [-Namespace ] [-DoNotUse {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-Force] [-SilentlyContinue] [-EnableException] [ ] Get-DbaCmObject -Query [-ComputerName ] [-Credential ] [-Namespace ] [-DoNotUse {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-Force] [-SilentlyContinue] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Retrieves the common operating system information from the local computer PS C:\\> Get-DbaCmObject win32_OperatingSystem Example 2: Retrieves the common operating system information from the server sql2014 PS C:\\> Get-DbaCmObject -Computername \"sql2014\" -ClassName Win32_OperatingSystem -Credential $cred -DoNotUse CimRM Retrieves the common operating system information from the server sql2014. It 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). Required Parameters -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 services. Use this when you need to retrieve all instances and properties of a specific Windows management class across your SQL Server infrastructure. | Property | Value | | --- | --- | | Alias | Class | | Required | True | | Pipeline | false | | Default Value | | -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. Use this when you need advanced filtering like \"SELECT Name, State FROM Win32_Service WHERE StartMode='Auto'\" to get specific data rather than entire class instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -ComputerName Specifies the target computer names or SQL Server host names to query for Windows management information. Accepts multiple values and pipeline input. Defaults to the local machine when not specified, but typically used to gather system-level data from remote SQL Server hosts for infrastructure monitoring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Credentials to use. Invalid credentials will be stored in a credentials cache and not be reused. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Namespace Specifies the WMI namespace path where the target class or query should be executed. The default \"root\\cimv2\" contains most Windows system classes. Change this when querying specialized namespaces like \"root\\SQLSERVER\" for SQL Server-specific WMI classes or \"root\\MSCluster\" for cluster information. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | root\\cimv2 | -DoNotUse Excludes specific connection protocols from the automatic fallback sequence. Valid values are CimRM, CimDCOM, Wmi, and PowerShellRemoting. Use this when certain protocols are blocked by network policies or cause issues in your environment, forcing the function to skip problematic connection methods. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | None | -Force Bypasses timeout protections on connections that have previously failed, allowing retry attempts on servers marked as problematic. Use this when you suspect connection issues have been resolved or when you need to override cached failure states during troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SilentlyContinue Converts terminating connection failures into non-terminating errors when used with EnableException, allowing processing to continue with remaining servers. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Management.ManagementObject or Microsoft.Management.Infrastructure.CimInstance Returns 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, Win32_Service, etc.). The 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 native WMI/CIM object with all properties exposed by that class. Common examples of returned object properties (varies by class): For Win32_OperatingSystem: Name, Caption, Version, BuildNumber, OSArchitecture, FreePhysicalMemory, TotalVisibleMemorySize, SystemDrive, WindowsDirectory For Win32_ComputerSystem: Name, DNSHostName, Domain, Manufacturer, Model, SystemType, NumberOfProcessors, NumberOfLogicalProcessors, TotalPhysicalMemory For Win32_Service: Name, DisplayName, State, StartMode, Status, PathName, StartName, Description For Win32_LogicalDisk: Name, FileSystem, FreeSpace, Size, Description, VolumeSerialNumber Use 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. &nbsp;"
  },
  {
    "name": "Get-DbaComputerCertificate",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaComputerCertificate",
    "popularityRank": 125,
    "synopsis": "Retrieves X.509 certificates from Windows certificate stores that can be used for SQL Server TLS encryption",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaComputerCertificate View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves X.509 certificates from Windows certificate stores that can be used for SQL Server TLS encryption 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. Syntax Get-DbaComputerCertificate [[-ComputerName] ] [[-Credential] ] [[-Store] ] [[-Folder] ] [[-Type] ] [[-Path] ] [[-Thumbprint] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets computer certificates on localhost that are candidates for using with SQL Server&#39;s network encryption PS C:\\> Get-DbaComputerCertificate Example 2: Gets computer certificates on sql2016 that are candidates for using with SQL Server&#39;s network encryption PS C:\\> Get-DbaComputerCertificate -ComputerName sql2016 Example 3: Gets computer certificates on sql2016 that match thumbprints 8123472E32AB412ED4288888B83811DB8F504DED or... PS C:\\> Get-DbaComputerCertificate -ComputerName sql2016 -Thumbprint 8123472E32AB412ED4288888B83811DB8F504DED, 04BFF8B3679BB01A986E097868D8D494D70A46D6 Gets computer certificates on sql2016 that match thumbprints 8123472E32AB412ED4288888B83811DB8F504DED or 04BFF8B3679BB01A986E097868D8D494D70A46D6 Optional Parameters -ComputerName Specifies the target computer(s) to scan for certificates. Defaults to localhost. Use this when you need to check certificates on remote SQL Server machines or when configuring network encryption across multiple instances. For SQL Server clusters, specify each individual cluster node separately since certificates are stored per machine, not per cluster resource. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to $ComputerName using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Store Specifies which Windows certificate store location to search. Defaults to LocalMachine. Use LocalMachine for certificates that SQL Server service accounts can access, or CurrentUser for user-specific certificates. SQL Server typically requires certificates in LocalMachine store for network encryption to work properly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | LocalMachine | -Folder Specifies which certificate folder within the store to search. Defaults to My (Personal certificates). Use My for personal certificates with private keys, Root for trusted root certificates, or other folders based on certificate type. SQL Server network encryption typically uses certificates from the My folder since they contain the required private keys. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | My | -Type Filters certificates by their intended usage. Service returns only certificates with Server Authentication capability, All returns every certificate. Use Service (default) to find certificates that SQL Server can actually use for network encryption and TLS connections. Service certificates have the required Enhanced Key Usage extension (1.3.6.1.5.5.7.3.1) that enables them for server authentication scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Service | | Accepted Values | All,Service | -Path Specifies the file system path to a certificate file (.cer, .crt, .pfx) to load and analyze. Use this when you need to examine a certificate file before installing it to a certificate store. This bypasses the Store and Folder parameters since the certificate is loaded directly from the file system. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Thumbprint Filters results to return only certificates with the specified thumbprint(s). Accepts multiple thumbprints. Use this when you need to verify specific certificates exist or check their properties before configuring SQL Server network encryption. The thumbprint is the unique SHA-1 hash identifier that SQL Server uses in its certificate configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Security.Cryptography.X509Certificates.X509Certificate2 Returns one X509Certificate2 object per certificate found in the specified store and folder. Default display properties (via Select-DefaultView): ComputerName: The name of the computer where the certificate is stored Store: The certificate store location (CurrentUser or LocalMachine) Folder: The certificate folder/container name (My, Root, AddressBook, etc.) Name: The friendly name of the certificate (added via Add-Member) DnsNameList: Collection of DNS names associated with the certificate Thumbprint: The SHA-1 hash fingerprint uniquely identifying the certificate NotBefore: DateTime when the certificate becomes valid NotAfter: DateTime when the certificate expires Subject: The distinguished name of the subject (entity the certificate is issued to) Issuer: The distinguished name of the certificate issuer (CA that signed it) Algorithm: The signature algorithm used by the certificate (added via Add-Member) Additional properties available from the X509Certificate2 object: PublicKey: The public key cryptographic information PrivateKey: The private key (when available) Version: The X.509 certificate version SerialNumber: The serial number assigned by the issuer SignatureAlgorithm: Algorithm details for the certificate signature Extensions: Collection of certificate extensions SignatureAlgorithmOid: Object identifier for the signature algorithm IssuerName: X500DistinguishedName of the issuer SubjectName: X500DistinguishedName of the subject Verify: Method to verify the certificate &nbsp;"
  },
  {
    "name": "Get-DbaComputerSystem",
    "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.",
    "category": "Utilities",
    "tags": [
      "management",
      "computer",
      "os"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaComputerSystem",
    "popularityRank": 129,
    "synopsis": "Retrieves comprehensive hardware and system information from Windows computers hosting SQL Server instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaComputerSystem View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves comprehensive hardware and system information from Windows computers hosting SQL Server instances. 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. The 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. Use this command when documenting SQL Server environments, verifying system requirements before installations or upgrades, or investigating hardware-related performance bottlenecks. Syntax Get-DbaComputerSystem [[-ComputerName] ] [[-Credential] ] [-IncludeAws] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns information about the local computer&#39;s computer system PS C:\\> Get-DbaComputerSystem Example 2: Returns information about the sql2016&#39;s computer system PS C:\\> Get-DbaComputerSystem -ComputerName sql2016 Example 3: Returns information about the sql2016&#39;s computer system and includes additional properties around the EC2... PS C:\\> Get-DbaComputerSystem -ComputerName sql2016 -IncludeAws Returns information about the sql2016's computer system and includes additional properties around the EC2 instance. Optional Parameters -ComputerName Specifies the target computer(s) to collect system information from. Defaults to the local computer when not specified. Use this to inventory multiple SQL Server hosts at once or to gather system details from remote servers for capacity planning and troubleshooting. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Alternate credential object to use for accessing the target computer(s). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this switch when documenting cloud-hosted SQL Server environments or when you need AWS-specific details for compliance or cost management purposes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per computer specified, containing hardware and system information collected from WMI. Default display properties (via Select-DefaultView): ComputerName: The resolved computer name Domain: The domain name the computer belongs to DomainRole: Role of the computer (Standalone Workstation, Member Workstation, Standalone Server, Member Server, Backup Domain Controller, or Primary Domain Controller) Manufacturer: Hardware manufacturer name Model: Hardware model name SystemFamily: System family classification SystemType: System type (e.g., \"x64-based PC\") ProcessorName: Processor name from Win32_Processor ProcessorCaption: Processor description from Win32_Processor ProcessorMaxClockSpeed: Maximum processor speed in MHz NumberLogicalProcessors: Number of logical processors (includes hyperthreading virtual cores) NumberProcessors: Number of physical processor sockets IsHyperThreading: Boolean indicating if hyperthreading is detected (logical processors > physical processors) TotalPhysicalMemory: Total physical memory as a DbaSize object (shows human-readable format) IsSystemManagedPageFile: Boolean indicating if Windows manages the page file automatically PendingReboot: Boolean indicating if the system has a pending reboot, or $null if reboot status could not be determined Additional properties available but not shown by default: SystemSkuNumber: System SKU number from hardware IsDaylightSavingsTime: Boolean indicating if daylight saving time is enabled on the system DaylightInEffect: Boolean indicating if daylight saving time is currently in effect DnsHostName: DNS host name of the computer AdminPasswordStatus: Administrator password status (Disabled, Enabled, Not Implemented, or Unknown) When -IncludeAws is specified and the computer is detected as an AWS EC2 instance, the following properties are added: AwsAmiId: The AMI (Amazon Machine Image) ID AwsIamRoleArn: The IAM instance profile ARN AwsEc2InstanceId: The EC2 instance ID AwsEc2InstanceType: The EC2 instance type (e.g., t2.large, m5.xlarge) AwsAvailabilityZone: The AWS availability zone where the instance is located AwsPublicHostName: The public hostname assigned to the EC2 instance &nbsp;"
  },
  {
    "name": "Get-DbaConnectedInstance",
    "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's 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.",
    "category": "Server Management",
    "tags": [
      "connection"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaConnectedInstance",
    "popularityRank": 170,
    "synopsis": "Returns SQL Server instances currently cached in the dbatools connection pool",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaConnectedInstance View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Outputs Synopsis Returns SQL Server instances currently cached in the dbatools connection pool 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's 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. Syntax Get-DbaConnectedInstance [ ] &nbsp; Examples &nbsp; Example 1: Gets all connected SQL Server instances PS C:\\> Get-DbaConnectedInstance Example 2: Gets all connected SQL Server instances and shows the associated connectionstrings as well PS C:\\> Get-DbaConnectedInstance | Select Outputs PSCustomObject Returns one object per cached connection in the dbatools connection pool, containing details about each active or recently used SQL Server connection. Default display properties (via Select-DefaultView): SqlInstance: The SQL Server instance identifier (computer\\instance or server name) ConnectionType: The .NET type of the connection object (e.g., Microsoft.SqlServer.Management.Smo.Server or System.Data.SqlClient.SqlConnection) ConnectionObject: The actual connection object used internally by dbatools Pooled: Boolean indicating whether connection pooling is enabled for this connection Additional properties available: ConnectionString: The connection string used to establish the connection (with credentials redacted for security) Use Select-Object to view all properties including the full ConnectionString. &nbsp;"
  },
  {
    "name": "Get-DbaConnection",
    "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.\"",
    "category": "Utilities",
    "tags": [
      "connection"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaConnection",
    "popularityRank": 85,
    "synopsis": "Returns a bunch of information from dm_exec_connections.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaConnection View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Returns a bunch of information from dm_exec_connections. Description Returns a bunch of information from dm_exec_connections which, according to Microsoft: \"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.\" Syntax Get-DbaConnection [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns client connection information from sql2016 and sql2017 PS C:\\> Get-DbaConnection -SqlInstance sql2016, sql2017 Required Parameters -SqlInstance The target SQL Server instance or instances. Server(s) must be SQL Server 2005 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | Credential,Cred | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per connection on each SQL Server instance. Each object contains detailed information about the connection and its statistics. Properties: ComputerName: The name of the computer where SQL Server is running InstanceName: The SQL Server instance name (MSSQLSERVER for default instance) SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName format) SessionId: The session ID of the connection (integer) MostRecentSessionId: The most recent session ID associated with this connection (integer) ConnectTime: DateTime when the connection was established Transport: The network transport protocol used (e.g., \"Named pipes\", \"TCP/IP\", \"Shared memory\") ProtocolType: The protocol type used for the connection (e.g., \"TSQL\") ProtocolVersion: The version of the protocol being used (integer) EndpointId: The ID of the database mirroring endpoint (integer) EncryptOption: Encryption status of the connection (e.g., \"ENCRYPT_ON\", \"ENCRYPT_OFF\") AuthScheme: The authentication scheme used (e.g., \"WINDOWS\", \"SQL\") NodeAffinity: The node affinity of the connection for non-uniform memory access (NUMA) systems (integer) Reads: The number of read operations performed on this connection (integer) Writes: The number of write operations performed on this connection (integer) LastRead: DateTime of the most recent read operation on this connection LastWrite: DateTime of the most recent write operation on this connection PacketSize: The network packet size in bytes used for this connection (integer) ClientNetworkAddress: The IP address or network address of the client connecting to SQL Server ClientTcpPort: The TCP port used by the client to connect to SQL Server (integer) ServerNetworkAddress: The IP address or network address of the server's network interface ServerTcpPort: The TCP port on which SQL Server is listening (integer) ConnectionId: The unique identifier for this connection (integer, GUID-based) ParentConnectionId: The parent connection ID for connections that are part of a hierarchy (integer) MostRecentSqlHandle: The SQL handle of the most recently executed statement (binary) &nbsp;"
  },
  {
    "name": "Get-DbaCpuRingBuffer",
    "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's 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//",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "buffer",
      "cpu"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaCpuRingBuffer",
    "popularityRank": 419,
    "synopsis": "Retrieves historical CPU utilization data from SQL Server's internal ring buffer for performance analysis",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaCpuRingBuffer View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves historical CPU utilization data from SQL Server's internal ring buffer for performance analysis 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's diagnostic query, it provides minute-by-minute CPU usage breakdowns that help identify performance patterns and resource contention. The 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. Use 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. Reference: https://www.sqlskills.com/blogs/glenn/sql-server-diagnostic-information-queries-detailed-day-16// Syntax Get-DbaCpuRingBuffer [-SqlInstance] [[-SqlCredential] ] [[-CollectionMinutes] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets CPU Statistics from sys.dm_os_ring_buffers for servers sql2008 and sqlserver2012 for last 60 minutes PS C:\\> Get-DbaCpuRingBuffer -SqlInstance sql2008, sqlserver2012 Example 2: Gets CPU Statistics from sys.dm_os_ring_buffers for server sql2008 for last 240 minutes PS C:\\> Get-DbaCpuRingBuffer -SqlInstance sql2008 -CollectionMinutes 240 Example 3: Gets CPU Statistics from sys.dm_os_ring_buffers for server sql2008 for last 240 minutes into a Data Table PS C:\\> $output = Get-DbaCpuRingBuffer -SqlInstance sql2008 -CollectionMinutes 240 | Select-Object * | ConvertTo-DbaDataTable Example 4: Gets CPU Statistics from sys.dm_os_ring_buffers for servers sql2008 and sqlserver2012 PS C:\\> 'sql2008','sql2012' | Get-DbaCpuRingBuffer Example 5: Connects using sqladmin credential and returns CPU Statistics from sys.dm_os_ring_buffers from sql2008 PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Get-DbaCpuRingBuffer -SqlInstance sql2008 -SqlCredential $cred Required Parameters -SqlInstance Allows you to specify a comma separated list of servers to query. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. To use: $cred = Get-Credential, this pass this $cred to the param. Windows Authentication will be used if DestinationSqlCredential is not specified. To connect as a different Windows user, run PowerShell as that user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CollectionMinutes Specifies how many minutes of historical CPU data to retrieve from the ring buffer. Defaults to 60 minutes. Use 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 system activity. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 60 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per minute of CPU ring buffer data retrieved from the SQL Server instance. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) RecordId: The unique record identifier from the ring buffer entry EventTime: DateTime of the CPU sample (in local server time) SQLProcessUtilization: Percentage of CPU used by the SQL Server process (0-100) SystemIdle: Percentage of CPU that is idle (0-100) OtherProcessUtilization: Percentage of CPU used by other processes (0-100), calculated as 100 - SystemIdle - SQLProcessUtilization &nbsp;"
  },
  {
    "name": "Get-DbaCpuUsage",
    "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's 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.",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "performance",
      "cpu"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaCpuUsage",
    "popularityRank": 112,
    "synopsis": "Correlates SQL Server processes with Windows threads to identify which queries are consuming CPU resources",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaCpuUsage View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Correlates SQL Server processes with Windows threads to identify which queries are consuming CPU resources 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. The function queries both SQL Server's 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. Results 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. References: https://www.mssqltips.com/sqlservertip/2454/how-to-find-out-how-much-cpu-a-sql-server-process-is-really-using/ Note: This command returns results from all SQL instances on the destination server but the process column is specific to -SqlInstance passed. Syntax Get-DbaCpuUsage [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [[-Threshold] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Logs into the SQL Server instance &quot;sql2017&quot; and also the Computer itself (via WMI) to gather information PS C:\\> Get-DbaCpuUsage -SqlInstance sql2017 Example 2: Explores the processes (from Get-DbaProcess) associated with the usage results PS C:\\> $usage = Get-DbaCpuUsage -SqlInstance sql2017 PS C:\\> $usage.Process Example 3: Logs into the SQL instance using the SQL Login &#39;sqladmin&#39; and then Windows instance as &#39;ad\\sqldba&#39; PS C:\\> Get-DbaCpuUsage -SqlInstance sql2017 -SqlCredential sqladmin -Credential ad\\sqldba Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Allows you to login to the Windows Server using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Threshold Filters results to only show SQL Server threads with CPU usage at or above this percentage. Use this to focus on high-CPU consuming processes and ignore idle or low-activity threads during performance troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Win32_PerfFormattedData_PerfProc_Thread (with added properties) Returns one object per Windows thread of SQL Server processes with CPU usage at or above the specified threshold. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The thread identifier in format 'ProcessName_ProcessID_ThreadID' ContextSwitchesPersec: Number of context switches per second for this thread ElapsedTime: Time in seconds since the thread was created IDProcess: Windows process ID (PID) of the SQL Server process Spid: SQL Server session ID (SPID) associated with this thread PercentPrivilegedTime: Percentage of time thread spent in privileged mode PercentProcessorTime: Percentage of total processor time consumed by this thread PercentUserTime: Percentage of time thread spent in user mode PriorityBase: The base priority of the thread PriorityCurrent: The current priority of the thread StartAddress: Memory address where the thread code begins execution ThreadStateValue: Human-readable description of the thread state (e.g., 'Running', 'Waiting') ThreadWaitReasonValue: Human-readable description of the wait reason if thread is waiting Process: Associated SQL Server process object from Get-DbaProcess Query: The last T-SQL query executed by the process Additional properties available (from Win32_PerfFormattedData_PerfProc_Thread): IDThread: Windows thread ID ThreadState: Numeric value representing thread state (0=Initialized, 1=Ready, 2=Running, 3=Standby, 4=Terminated, 5=Waiting, 6=Transition, 7=Unknown) ThreadWaitReason: Numeric value representing the reason the thread is waiting All properties from the Win32_PerfFormattedData_PerfProc_Thread WMI class are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaCredential",
    "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.",
    "category": "Security",
    "tags": [
      "security",
      "credential"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaCredential",
    "popularityRank": 101,
    "synopsis": "Retrieves SQL Server Credentials configured for external authentication and resource access.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaCredential View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Credentials configured for external authentication and resource access. 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. Syntax Get-DbaCredential [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [[-ExcludeCredential] ] [[-Identity] ] [[-ExcludeIdentity] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all SQL Credentials on the local default SQL Server instance PS C:\\> Get-DbaCredential -SqlInstance localhost Example 2: Returns the SQL Credentials named &#39;PowerShell Proxy&#39; for the local and sql2016 SQL Server instances PS C:\\> Get-DbaCredential -SqlInstance localhost, sql2016 -Name 'PowerShell Proxy' Example 3: Returns the SQL Credentials for the account &#39;ad\\powershell&#39; on the local and sql2016 SQL Server instances PS C:\\> Get-DbaCredential -SqlInstance localhost, sql2016 -Identity ad\\powershell Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Filters results to only include SQL Server credentials with specific names. Accepts multiple credential names and supports wildcards. Use this when you need to check configuration for specific credentials like backup service accounts or external data source connections. Enclose names with spaces in quotes, such as \"My Backup Credential\". | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -ExcludeCredential Excludes SQL Server credentials with specified names from the results. Accepts multiple credential names to filter out. Useful when auditing all credentials except system or known service credentials that don't require review. | Property | Value | | --- | --- | | Alias | ExcludeName | | Required | False | | Pipeline | false | | Default Value | | -Identity Filters results to only include credentials that use specific Windows identities or SQL logins. Accepts multiple identity names. Use this to find all credentials associated with a particular service account or user across different credential objects. Enclose identities with spaces in quotes, such as \"DOMAIN\\Service Account\". | Property | Value | | --- | --- | | Alias | CredentialIdentity | | Required | False | | Pipeline | false | | Default Value | | -ExcludeIdentity Excludes credentials that use specified Windows identities or SQL logins from the results. Accepts multiple identity names. Helpful when auditing credentials but excluding known system accounts or service identities from the output. | Property | Value | | --- | --- | | Alias | ExcludeCredentialIdentity | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Credential Returns 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 access and authentication. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ID: Unique identifier for the credential within SQL Server Name: The name of the SQL Server credential Identity: The Windows identity, login, or external identity the credential uses (e.g., domain\\account or Azure URI) MappedClassType: The credential class type (None or CryptographicProvider for EKM) ProviderName: The name of the cryptographic provider (if MappedClassType is CryptographicProvider) Additional properties available (from SMO Credential object): CreateDate: DateTime when the credential was created DateLastModified: DateTime when the credential was last modified Parent: The Server object containing this credential Properties: Collection of extended properties assigned to the credential Urn: Uniform Resource Name identifier for the credential State: The current state of the SMO object All properties from the base SMO Credential object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaCustomError",
    "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.",
    "category": "Utilities",
    "tags": [
      "general",
      "error"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaCustomError",
    "popularityRank": 555,
    "synopsis": "Retrieves user-defined error messages from SQL Server instances for auditing and documentation.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaCustomError View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves user-defined error messages from SQL Server instances for auditing and documentation. 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. Syntax Get-DbaCustomError [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all Custom Error Message(s) on the local default SQL Server instance PS C:\\> Get-DbaCustomError -SqlInstance localhost Example 2: Returns all Custom Error Message(s) for the local and sql2016 SQL Server instances PS C:\\> Get-DbaCustomError -SqlInstance localhost, sql2016 Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.UserDefinedMessage Returns 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 are returned. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server host InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ID: The custom error message ID (50001-2147483647) Text: The text of the custom error message (max 255 characters) LanguageID: The language ID (numeric identifier from sys.syslanguages) Language: The language name (e.g., \"English\", \"French\", \"Deutsch\") Additional properties available (from SMO UserDefinedMessage object): Severity: The severity level of the error (1-25 integer) IsLogged: Boolean indicating if the error is logged to the Windows Application and SQL Server error logs Parent: Reference to the parent SMO Server object All properties from the base SMO object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDatabase",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaDatabase",
    "popularityRank": 7,
    "synopsis": "Retrieves database objects and metadata from SQL Server instances with advanced filtering and usage analytics.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDatabase View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com , Klaas Vandenberghe (@PowerDbaKlaas) , Simone Bizzotto (@niphlod) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database objects and metadata from SQL Server instances with advanced filtering and usage analytics. Description Retrieves detailed database information from one or more SQL Server instances, returning rich database objects instead of basic metadata queries. This 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. Unlike 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. Supports both on-premises SQL Server (2000+) and Azure SQL Database with automatic compatibility handling. Syntax Get-DbaDatabase [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Pattern] ] [-ExcludeUser] [-ExcludeSystem] [[-Owner] ] [-Encrypted] [[-Status] ] [[-Access] ] [[-RecoveryModel] ] [-NoFullBackup] [[-NoFullBackupSince] ] [-NoLogBackup] [[-NoLogBackupSince] ] [-EnableException] [-IncludeLastUsed] [-OnlyAccessible] [ ] &nbsp; Examples &nbsp; Example 1: Returns all databases on the local default SQL Server instance PS C:\\> Get-DbaDatabase -SqlInstance localhost Example 2: Returns only the system databases on the local default SQL Server instance PS C:\\> Get-DbaDatabase -SqlInstance localhost -ExcludeUser Example 3: Returns only the user databases on the local default SQL Server instance PS C:\\> Get-DbaDatabase -SqlInstance localhost -ExcludeSystem Example 4: Returns databases on multiple instances piped into the function PS C:\\> 'localhost','sql2016' | Get-DbaDatabase Example 5: Returns only the user databases in Full or Simple recovery model from SQL Server instance SQL1\\SQLExpress PS C:\\> Get-DbaDatabase -SqlInstance SQL1\\SQLExpress -RecoveryModel full,Simple Example 6: Returns only the user databases with status &#39;normal&#39; from SQL Server instance SQL1\\SQLExpress PS C:\\> Get-DbaDatabase -SqlInstance SQL1\\SQLExpress -Status Normal Example 7: Returns the databases from SQL Server instance SQL1\\SQLExpress and includes the last used information from... PS C:\\> Get-DbaDatabase -SqlInstance SQL1\\SQLExpress -IncludeLastUsed Returns the databases from SQL Server instance SQL1\\SQLExpress and includes the last used information from the sys.dm_db_index_usage_stats DMV. Example 8: Returns all databases except master and model from SQL Server instances SQL1\\SQLExpress and SQL2 PS C:\\> Get-DbaDatabase -SqlInstance SQL1\\SQLExpress,SQL2 -ExcludeDatabase model,master Example 9: Returns only databases using TDE from SQL Server instances SQL1\\SQLExpress and SQL2 PS C:\\> Get-DbaDatabase -SqlInstance SQL1\\SQLExpress,SQL2 -Encrypted Example 10: Returns only read only databases from SQL Server instances SQL1\\SQLExpress and SQL2 PS C:\\> Get-DbaDatabase -SqlInstance SQL1\\SQLExpress,SQL2 -Access ReadOnly Example 11: Returns databases &#39;OneDb&#39; and &#39;OtherDB&#39; from SQL Server instances SQL2 and SQL3 if databases by those names... PS C:\\> Get-DbaDatabase -SqlInstance SQL2,SQL3 -Database OneDB,OtherDB Returns databases 'OneDb' and 'OtherDB' from SQL Server instances SQL2 and SQL3 if databases by those names exist on those instances. Example 12: Returns all databases that match the regex pattern &quot;^dbatools_&quot; (e.g., dbatools_example1, dbatools_example2)... PS C:\\> Get-DbaDatabase -SqlInstance SQL2,SQL3 -Pattern \"^dbatools_\" Returns all databases that match the regex pattern \"^dbatools_\" (e.g., dbatools_example1, dbatools_example2) from SQL Server instances SQL2 and SQL3. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies one or more databases to include in the results using exact name matching. Use this when you need to retrieve specific databases instead of all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies one or more databases to exclude from the results using exact name matching. Use this to filter out specific databases like test or staging environments from your inventory. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Pattern Specifies a pattern for filtering databases using regular expressions. Use this when you need to match databases by pattern, such as \"^dbatools_\" or \"._prod$\". This parameter supports standard .NET regular expression syntax. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeUser Returns only system databases (master, model, msdb, tempdb). Use this when you need to focus on system database maintenance tasks or validation. This parameter cannot be used with -ExcludeSystem. | Property | Value | | --- | --- | | Alias | SystemDbOnly,NoUserDb,ExcludeAllUserDb | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeSystem Returns only user databases, excluding system databases (master, model, msdb, tempdb). Use this when you need to focus on application databases for maintenance, backup, or compliance reporting. This parameter cannot be used with -ExcludeUser. | Property | Value | | --- | --- | | Alias | UserDbOnly,NoSystemDb,ExcludeAllSystemDb | | Required | False | | Pipeline | false | | Default Value | False | -Owner Filters databases by their database owner (the principal listed as the database owner). Use this to find databases owned by specific accounts for security auditing or ownership cleanup. Accepts login names like 'sa', 'DOMAIN\\user', or service account names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Encrypted Returns only databases with Transparent Data Encryption (TDE) enabled. Use this for compliance reporting or to verify which databases have encryption configured for data protection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Status Filters databases by their current operational status. Returns only databases matching the specified status values. Use this to identify databases requiring attention (Suspect, Offline) or in specific states for maintenance planning. Valid options: EmergencyMode, Normal, Offline, Recovering, RecoveryPending, Restoring, Standby, Suspect. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @('EmergencyMode', 'Normal', 'Offline', 'Recovering', 'RecoveryPending', 'Restoring', 'Standby', 'Suspect') | | Accepted Values | 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. Use ReadOnly to find reporting databases or those temporarily set to read-only for maintenance. Valid options: ReadOnly, ReadWrite. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | ReadOnly,ReadWrite | -RecoveryModel Filters databases by their recovery model setting, which controls transaction log behavior and backup capabilities. Use this to verify recovery model consistency or find databases needing model changes for backup strategy compliance. Valid options: Full (point-in-time recovery), Simple (no log backups), BulkLogged (minimal logging for bulk operations). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @('Full', 'Simple', 'BulkLogged') | | Accepted Values | Full,Simple,BulkLogged | -NoFullBackup Returns only databases that have never had a full backup or only have CopyOnly full backups recorded in msdb. Use this to identify databases at risk due to missing backup coverage for disaster recovery planning. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoFullBackupSince Returns databases that haven't had a full backup since the specified date and time. Use this to identify databases with stale backups that may violate your backup policy or RTO requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoLogBackup Returns databases in Full or BulkLogged recovery model that have never had a transaction log backup. Use this to identify databases where transaction logs may be growing unchecked due to missing log backup strategy. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoLogBackupSince Returns databases that haven't had a transaction log backup since the specified date and time. Use this to find databases with overdue log backups that may cause transaction log growth or RPO violations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeLastUsed Adds LastRead and LastWrite columns showing when databases were last accessed based on index usage statistics. Use this to identify unused or rarely accessed databases for decommissioning or archival decisions. Data is retrieved from sys.dm_db_index_usage_stats and resets when SQL Server restarts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -OnlyAccessible Returns only databases that are currently accessible, excluding offline or inaccessible databases. Use this to improve performance when you only need databases that can be queried, providing significant speedup for SMO enumeration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Database Returns one SMO Database object for each database on the specified instances matching the filter criteria. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Database name Status: Current database status (EmergencyMode, Normal, Offline, Recovering, RecoveryPending, Restoring, Standby, Suspect) IsAccessible: Boolean indicating if the database is currently accessible RecoveryModel: Database recovery model (Full, Simple, BulkLogged) LogReuseWaitStatus: Status of transaction log reuse (LogSwitch, ChkptBkup, ActiveBkup, ActiveTran, etc.) Size: Database size in megabytes (MB) Compatibility: Database compatibility level (numeric value representing SQL Server version) Collation: Database collation setting Owner: Database owner login name Encrypted: Boolean indicating if Transparent Data Encryption (TDE) is enabled LastFullBackup: DateTime of the most recent full backup LastDiffBackup: DateTime of the most recent differential backup LastLogBackup: DateTime of the most recent transaction log backup When -NoFullBackup or -NoFullBackupSince is specified, an additional property is included: BackupStatus: String indicating backup state (e.g., \"Only CopyOnly backups\", $null for normal backups) When -IncludeLastUsed is specified, additional properties are included: LastIndexRead: DateTime of last read operation from sys.dm_db_index_usage_stats LastIndexWrite: DateTime of last write operation from sys.dm_db_index_usage_stats Additional properties available (from SMO Database object): IsCdcEnabled: Boolean indicating if Change Data Capture is enabled (SQL Server 2008+) And all other standard SMO Database properties (use Select-Object to see all) All properties from the base SMO Database object are accessible via Select-Object even though only default properties are displayed without using the -Property parameter. &nbsp;"
  },
  {
    "name": "Get-DbaDbAssembly",
    "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.",
    "category": "Database Operations",
    "tags": [
      "assembly",
      "database"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbAssembly",
    "popularityRank": 405,
    "synopsis": "Retrieves CLR assemblies registered in SQL Server databases for security auditing and inventory management.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbAssembly View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves CLR assemblies registered in SQL Server databases for security auditing and inventory management. 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. Syntax Get-DbaDbAssembly [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Name] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all Database Assembly on the local default SQL Server instance PS C:\\> Get-DbaDbAssembly -SqlInstance localhost Example 2: Returns all Database Assembly for the local and sql2016 SQL Server instances PS C:\\> Get-DbaDbAssembly -SqlInstance localhost, sql2016 Example 3: Will fetch details for the MyTechCo.Houids.SQLCLR assembly in the MyDb Database on the Server1 instance PS C:\\> Get-DbaDbAssembly -SqlInstance Server1 -Database MyDb -Name MyTechCo.Houids.SQLCLR Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for CLR assemblies. Accepts wildcards for pattern matching. Use this when auditing assemblies in specific databases rather than scanning the entire instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Filters results to assemblies with matching names. Supports exact assembly name matching only. Use this when investigating specific assemblies during security audits or troubleshooting CLR-related issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Assembly Returns one Assembly object for each CLR assembly found in the specified or accessible databases. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the assembly ID: Unique identifier for the assembly Name: Name of the assembly Owner: The principal that owns the assembly SecurityLevel: Assembly security level (Safe, ExternalAccess, or Unsafe) CreateDate: DateTime when the assembly was created IsSystemObject: Boolean indicating if the assembly is a system object Version: Version information of the assembly Additional properties available (from SMO Assembly object): DatabaseId: Unique identifier for the database containing the assembly FilePath: File path associated with the assembly AssemblySecurityLevel: Same as SecurityLevel property All properties from the base SMO Assembly object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbAsymmetricKey",
    "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's transparent data encryption and column-level encryption features.\nReturns detailed key properties to help with compliance reporting and security assessments.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbAsymmetricKey",
    "popularityRank": 542,
    "synopsis": "Retrieves asymmetric keys from SQL Server databases for encryption management and security auditing",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbAsymmetricKey View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves asymmetric keys from SQL Server databases for encryption management and security auditing Description Retrieves asymmetric keys stored in SQL Server databases, including their encryption algorithms, key lengths, owners, and thumbprints. This function is essential for security audits and encryption key management, allowing DBAs to inventory all asymmetric keys across databases without manually querying system catalogs. Asymmetric keys are used for encryption, digital signatures, and certificate creation in SQL Server's transparent data encryption and column-level encryption features. Returns detailed key properties to help with compliance reporting and security assessments. Syntax Get-DbaDbAsymmetricKey [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Name] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all Asymmetric Keys PS C:\\> Get-DbaDbAsymmetricKey -SqlInstance sql2016 Example 2: Gets the Asymmetric Keys for the db1 database PS C:\\> Get-DbaDbAsymmetricKey -SqlInstance Server1 -Database db1 Example 3: Gets the key1 Asymmetric Key within the db1 database PS C:\\> Get-DbaDbAsymmetricKey -SqlInstance Server1 -Database db1 -Name key1 Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for asymmetric keys. Accepts wildcards for pattern matching. Use this when you need to audit encryption keys in specific databases instead of scanning all databases on the instance. Essential for targeted security assessments or compliance audits of particular applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the asymmetric key scan. Accepts wildcards for pattern matching. Use this to skip system databases, test databases, or databases known to not contain encryption keys. Helps focus audits on production databases and reduces noise in security assessments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Filters results to asymmetric keys with specific names. Accepts wildcards and multiple key names. Use this when tracking specific keys during key rotation, compliance audits, or troubleshooting encryption issues. Common when validating that required encryption keys exist across multiple databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from the pipeline, typically from Get-DbaDatabase. Use this to chain database filtering with key retrieval, such as getting keys from databases with specific properties. Enables advanced filtering scenarios like scanning only databases created after a certain date or with particular owners. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.AsymmetricKey Returns one AsymmetricKey object per asymmetric key found in the specified databases. Each object represents a single asymmetric key stored in the database's encryption hierarchy. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the asymmetric key Name: The name of the asymmetric key Owner: The principal that owns the asymmetric key KeyEncryptionAlgorithm: The encryption algorithm used for the key (RSA_512, RSA_1024, RSA_2048, RSA_3072, RSA_4096) KeyLength: The length of the key in bits (512, 1024, 2048, 3072, or 4096) PrivateKeyEncryptionType: How the private key is encrypted (NoEncryption, EncryptedByMasterKey, EncryptedByPassword) Thumbprint: The thumbprint (fingerprint) of the asymmetric key for verification and identification Additional properties available (from SMO AsymmetricKey object): DatabaseId: Unique identifier of the database containing the key And all other standard SMO AsymmetricKey properties (use Select-Object * to see all) &nbsp;"
  },
  {
    "name": "Get-DbaDbBackupHistory",
    "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",
    "category": "Backup & Restore",
    "tags": [
      "disasterrecovery",
      "backup"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaDbBackupHistory",
    "popularityRank": 37,
    "synopsis": "Retrieves backup history records from MSDB for analysis and compliance reporting.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbBackupHistory View Source Chrissy LeMaire (@cl) , Stuart Moore (@napalmgram) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves backup history records from MSDB for analysis and compliance reporting. 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. Reference: http://www.sqlhub.com/2011/07/find-your-backup-history-in-sql-server.html Syntax Get-DbaDbBackupHistory -SqlInstance [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-IncludeCopyOnly] [-Since ] [-RecoveryFork ] [-Last] [-LastFull] [-LastDiff] [-LastLog] [-DeviceType ] [-Raw] [-LastLsn ] [-IncludeMirror] [-Type ] [-AgCheck] [-IgnoreDiffBackup] [-LsnSort ] [-EnableException] [ ] Get-DbaDbBackupHistory -SqlInstance [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-IncludeCopyOnly] [-Force] [-Since ] [-RecoveryFork ] [-Last] [-LastFull] [-LastDiff] [-LastLog] [-DeviceType ] [-Raw] [-LastLsn ] [-IncludeMirror] [-Type ] [-AgCheck] [-IgnoreDiffBackup] [-LsnSort ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns server name, database, username, backup type, date for all database backups still in msdb history on... PS C:\\> Get-DbaDbBackupHistory -SqlInstance SqlInstance2014a Returns 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 other examples. Example 2: Get-DbaDbBackupHistory -SqlInstance SqlInstance2014a -SqlCredential $cred Does the same as above but connect... PS C:\\> $cred = Get-Credential sqladmin Get-DbaDbBackupHistory -SqlInstance SqlInstance2014a -SqlCredential $cred Does the same as above but connect to SqlInstance2014a as SQL user \"sqladmin\" Example 3: Returns backup information only for databases db1 and db2 on SqlInstance2014a since July 1, 2016 at 10:47 AM PS C:\\> Get-DbaDbBackupHistory -SqlInstance SqlInstance2014a -Database db1, db2 -Since ([DateTime]'2016-07-01 10:47:00') Example 4: Returns information only for AdventureWorks2014 and pubs and formats the results as a table PS C:\\> Get-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014, pubs -Force | Format-Table Example 5: Returns information about the most recent full, differential and log backups for AdventureWorks2014 on... PS C:\\> Get-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last Returns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014. Example 6: Returns information about the most recent full, differential and log backups for AdventureWorks2014 on... PS C:\\> Get-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last -DeviceType Disk Returns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014, but only for backups to disk. Example 7: Returns information about the most recent full, differential and log backups for AdventureWorks2014 on... PS C:\\> Get-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Last -DeviceType 148,107 Returns information about the most recent full, differential and log backups for AdventureWorks2014 on sql2014, but only for backups with device_type 148 and 107. Example 8: Returns information about the most recent full backup for AdventureWorks2014 on sql2014 PS C:\\> Get-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -LastFull Example 9: Returns information about all Full backups for AdventureWorks2014 on sql2014 PS C:\\> Get-DbaDbBackupHistory -SqlInstance sql2014 -Database AdventureWorks2014 -Type Full Example 10: Returns database backup information for every database on every server listed in the Central Management... PS C:\\> Get-DbaRegServer -SqlInstance sql2016 | Get-DbaDbBackupHistory Returns database backup information for every database on every server listed in the Central Management Server on sql2016. Example 11: Returns detailed backup history for all databases on SqlInstance2014a and sql2016 PS C:\\> Get-DbaDbBackupHistory -SqlInstance SqlInstance2014a, sql2016 -Force Example 12: If db1 has multiple recovery forks, specifying the RecoveryFork GUID will restrict the search to that fork PS C:\\> Get-DbaDbBackupHistory -SqlInstance sql2016 -Database db1 -RecoveryFork 38e5e84a-3557-4643-a5d5-eed607bef9c6 -Last Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -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 are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies one or more databases to include in the backup history search. Accepts wildcards for pattern matching. Use this when you need backup history for specific databases rather than all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies one or more databases to exclude from the backup history search. Useful when you want history for most databases but need to skip system databases or specific user databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeCopyOnly Includes copy-only backups in the results, which are normally excluded by default. Copy-only backups don't break the backup chain and are commonly used for ad-hoc backups or moving databases to other environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Returns all columns from the MSDB backup tables instead of the filtered standard output. Use this when you need access to additional backup metadata fields for detailed analysis or troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Since Filters backup history to only include backups taken after the specified date and time. Accepts DateTime objects or TimeSpan objects (which get added to the current time). Times are compared using the SQL Server instance's timezone. Essential for limiting results when dealing with databases that have extensive backup history. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | ([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. Use this when a database has been restored from different backup chains or has experienced recovery fork scenarios, ensuring you get the correct backup sequence. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Last Returns the most recent complete backup chain (full, differential, and log backups) needed for point-in-time recovery. This provides the exact backup sequence you'd need to restore a database to its most current state. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LastFull Returns only the most recent full backup for each database. Use this to quickly identify the base backup needed for restore operations or to verify when the last full backup was taken. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LastDiff Returns only the most recent differential backup for each database. Useful for verifying differential backup schedules or identifying the latest differential backup in a restore scenario. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LastLog Returns only the most recent transaction log backup for each database. Critical for monitoring log backup frequency and identifying the latest point-in-time recovery option available. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DeviceType Filters backups by device type such as 'Disk', 'Tape', 'URL', or 'Virtual Device'. Use this to find backups stored on specific media types, particularly useful when backups go to different destinations like local disk vs cloud storage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Raw Returns one object per backup file instead of grouping striped backup sets into single objects. Use this when you need to see individual backup file details for striped backups or need to analyze backup file distribution. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LastLsn Filters to only include backups with LSNs greater than the specified value, improving query performance on large backup histories. Use this when you know the LSN range you're interested in, typically when building restore sequences or analyzing backup chains. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeMirror Includes mirror backup copies in the results, which are excluded by default. Use this when you need to see all backup copies created through backup mirroring, useful for verifying mirror backup configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Type Filters results to specific backup types: 'Full', 'Log', 'Differential', 'File', 'Differential File', 'Partial Full', or 'Partial Differential'. Use this to focus on particular backup types when analyzing backup strategies or troubleshooting specific backup issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. This parameter is maintained for backward compatibility but no longer functions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IgnoreDiffBackup Excludes differential backups from the results, showing only full and log backups. Useful when analyzing backup chains that don't use differential backups or when you want to focus on full and log backup patterns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LsnSort Determines which LSN column to use for sorting results: 'FirstLsn', 'DatabaseBackupLsn', or 'LastLsn' (default). Use this to control backup ordering when working with complex backup scenarios or when you need results sorted by specific LSN checkpoints. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | LastLsn | | Accepted Values | FirstLsn,DatabaseBackupLsn,LastLsn | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Data.DataRow (when -Raw is specified) Returns 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 require access to all MSDB backup columns without object wrapping. Additional property added to raw output: FullName: Copy of the Path property for consistency with grouped output Dataplat.Dbatools.Database.BackupHistory (default) Returns 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. Default display properties (via table format): SqlInstance: The SQL Server instance name Database: Database name Type: Backup type (Full, Log, Differential, File, Differential File, Partial Full, or Partial Differential) TotalSize: Total uncompressed backup size in bytes DeviceType: Storage device type (Disk, Tape, URL, Virtual Device, etc.) Start: Backup start date and time Duration: Duration of the backup operation End: Backup completion date and time All available properties on BackupHistory objects: ComputerName: Computer name where SQL Server instance resides InstanceName: SQL Server instance name SqlInstance: Full SQL Server instance name (ComputerName\\InstanceName) AvailabilityGroupName: Availability group name (if applicable) Database: Database name DatabaseId: SQL Server database ID UserName: Windows or SQL login that performed the backup Start: Backup start DateTime End: Backup completion DateTime Duration: TimeSpan duration of the backup Path: Array of file paths for the backup files TotalSize: Total uncompressed backup size in bytes CompressedBackupSize: Compressed backup size in bytes (NULL for SQL 2005) CompressionRatio: Ratio of total size to compressed size (1.0 for uncompressed) Type: Backup type string BackupSetId: Unique backup set identifier from MSDB DeviceType: Backup device type (Disk, Tape, Pipe, Virtual Device, URL, etc.) Software: Software that created the backup (e.g., \"Microsoft SQL Server\") FullName: Array of backup file paths (same as Path) FileList: Array of file objects with FileType, LogicalName, and PhysicalName properties Position: Position of this backup in the media set FirstLsn: First Log Sequence Number in the backup (string representation of binary(10)) DatabaseBackupLsn: LSN of the last database backup referenced by this backup CheckpointLsn: LSN of the checkpoint at the time the backup was created LastLsn: Last Log Sequence Number in the backup SoftwareVersionMajor: Major version number of SQL Server that created the backup IsCopyOnly: Boolean indicating if this is a copy-only backup LastRecoveryForkGUID: Unique identifier of the last recovery fork RecoveryModel: Database recovery model (Simple, Full, or Bulk-logged) EncryptorThumbprint: Thumbprint of the certificate used for backup encryption (SQL 2014+) EncryptorType: Encryption algorithm used (SQL 2014+) KeyAlgorithm: Key algorithm used for encryption (SQL 2014+) &nbsp;"
  },
  {
    "name": "Get-DbaDbccHelp",
    "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",
    "category": "Utilities",
    "tags": [
      "dbcc"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbccHelp",
    "popularityRank": 263,
    "synopsis": "Retrieves syntax help and parameter information for DBCC commands",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbccHelp View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves syntax help and parameter information for DBCC commands 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. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-help-transact-sql Syntax Get-DbaDbccHelp [-SqlInstance] [[-SqlCredential] ] [[-Statement] ] [-IncludeUndocumented] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Runs the command DBCC HELP(FREESYSTEMCACHE) WITH NO_INFOMSGS against the SQLInstance SQL Server instance PS C:\\> Get-DbaDbccHelp -SqlInstance SQLInstance -Statement FREESYSTEMCACHE -Verbose | Format-List Example 2: Sets Trace Flag 2588 on for the session and then runs the command DBCC HELP(WritePage) WITH NO_INFOMSGS... PS C:\\> Get-DbaDbccHelp -SqlInstance SQLInstance -Statement WritePage -IncludeUndocumented | Format-List Sets Trace Flag 2588 on for the session and then runs the command DBCC HELP(WritePage) WITH NO_INFOMSGS against the SQLInstance SQL Server instance. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Statement Specifies the DBCC command name to get syntax help for. Provide only the command portion after \"DBCC\" (e.g., CHECKDB, CHECKTABLE, SHRINKFILE). Use this when you need to verify command syntax before running maintenance operations or troubleshooting database issues. Common commands include CHECKDB for database integrity, SHRINKFILE for file management, or FREEPROCCACHE for memory management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeUndocumented Enables access to help for undocumented DBCC commands by setting trace flag 2588 for the session. Use this when troubleshooting advanced scenarios that require undocumented commands like WRITEPAGE or PAGE. Only works on SQL Server 2005 and higher, and should be used with caution as undocumented commands can affect system stability. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance containing the DBCC help information. Properties: Operation: The DBCC command name specified in the Statement parameter (e.g., \"CHECKDB\", \"SHRINKFILE\") Cmd: The complete DBCC command executed against SQL Server (e.g., \"DBCC HELP(CHECKDB)\") 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. &nbsp;"
  },
  {
    "name": "Get-DbaDbccMemoryStatus",
    "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",
    "category": "Performance",
    "tags": [
      "dbcc",
      "memory"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbccMemoryStatus",
    "popularityRank": 311,
    "synopsis": "Executes DBCC MEMORYSTATUS and returns memory usage details in a structured format",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbccMemoryStatus View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Executes DBCC MEMORYSTATUS and returns memory usage details in a structured format 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. Reference: https://blogs.msdn.microsoft.com/timchapman/2012/08/16/how-to-parse-dbcc-memorystatus-via-powershell/ https://support.microsoft.com/en-us/help/907877/how-to-use-the-dbcc-memorystatus-command-to-monitor-memory-usage-on-sq Syntax Get-DbaDbccMemoryStatus [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get output of DBCC MEMORYSTATUS for instances &quot;sqlcluster&quot; and &quot;sqlserver2012&quot; PS C:\\> Get-DbaDbccMemoryStatus -SqlInstance sqlcluster, sqlserver2012 Get output of DBCC MEMORYSTATUS for instances \"sqlcluster\" and \"sqlserver2012\". Returns results in a single recordset. Example 2: Get output of DBCC MEMORYSTATUS for all servers in Server Central Management Server PS C:\\> Get-DbaRegServer -SqlInstance sqlcluster | Get-DbaDbccMemoryStatus Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per memory metric returned by DBCC MEMORYSTATUS. Each metric is parsed into a structured object containing the metric name, value, and classification. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName) RecordSet: The recordset number from the DBCC MEMORYSTATUS output (identifies which section the metric belongs to) RowId: The sequential row ID across all recordsets RecordSetId: The row ID within the current recordset Type: The memory category/type from DBCC MEMORYSTATUS (e.g., Memory Manager, Buffer Manager, Resource Pool, etc.) Name: The name of the memory metric Value: The value of the memory metric (typically in KB) ValueType: The column name from DBCC MEMORYSTATUS output indicating the metric classification &nbsp;"
  },
  {
    "name": "Get-DbaDbccProcCache",
    "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",
    "category": "Utilities",
    "tags": [
      "dbcc"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbccProcCache",
    "popularityRank": 570,
    "synopsis": "Retrieves plan cache memory usage statistics from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbccProcCache View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves plan cache memory usage statistics from SQL Server instances 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. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-proccache-transact-sql Syntax Get-DbaDbccProcCache [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get results of DBCC PROCCACHE for Instance Server1 PS C:\\> Get-DbaDbccProcCache -SqlInstance Server1 Example 2: Get results of DBCC PROCCACHE for Instances Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbccProcCache Example 3: Connects using sqladmin credential and gets results of DBCC PROCCACHE for Instance Server1 PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Get-DbaDbccProcCache -SqlInstance Server1 -SqlCredential $cred Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per result row from DBCC PROCCACHE with the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (service name) SqlInstance: The full SQL Server instance name (computer\\instance) Count: Number of plan cache entries in use Used: Memory allocated for plan cache (in pages) Active: Number of active plan cache entries CacheSize: Total plan cache size (in pages) CacheUsed: Amount of plan cache currently used (in pages) CacheActive: Number of active cache entries (may differ from Active) &nbsp;"
  },
  {
    "name": "Get-DbaDbccSessionBuffer",
    "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",
    "category": "Utilities",
    "tags": [
      "dbcc"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbccSessionBuffer",
    "popularityRank": 612,
    "synopsis": "Retrieves session input or output buffer contents using DBCC INPUTBUFFER or DBCC OUTPUTBUFFER",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbccSessionBuffer View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves session input or output buffer contents using DBCC INPUTBUFFER or DBCC OUTPUTBUFFER 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. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-inputbuffer-transact-sql https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-outputbuffer-transact-sql Syntax Get-DbaDbccSessionBuffer [-SqlInstance] [[-SqlCredential] ] [[-Operation] ] [[-SessionId] ] [[-RequestId] ] [-All] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get results of DBCC INPUTBUFFER(51) for Instance Server1 PS C:\\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -Operation InputBuffer -SessionId 51 Example 2: Get results of DBCC OUTPUTBUFFER for SessionId&#39;s 51 and 52 for Instance Server1 PS C:\\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -Operation OutputBuffer -SessionId 51, 52 Example 3: Get results of DBCC INPUTBUFFER(51,0) for Instance Server1 PS C:\\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -Operation InputBuffer -SessionId 51 -RequestId 0 Example 4: Get results of DBCC OUTPUTBUFFER(51,0) for Instance Server1 PS C:\\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -Operation OutputBuffer -SessionId 51 -RequestId 0 Example 5: Get results of DBCC INPUTBUFFER for all user sessions for the instances Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbccSessionBuffer -Operation InputBuffer -All Example 6: Get results of DBCC OUTPUTBUFFER for all user sessions for the instances Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbccSessionBuffer -Operation OutputBuffer -All Example 7: Connects using sqladmin credential and gets results of DBCC INPUTBUFFER(51,0) for Instance Server1 PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -SqlCredential $cred -Operation InputBuffer -SessionId 51 -RequestId 0 Example 8: Connects using sqladmin credential and gets results of DBCC OUTPUTBUFFER(51,0) for Instance Server1 PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Get-DbaDbccSessionBuffer -SqlInstance Server1 -SqlCredential $cred -Operation OutputBuffer -SessionId 51 -RequestId 0 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use InputBuffer when troubleshooting blocking sessions, investigating suspicious activity, or identifying problematic queries. Use OutputBuffer when debugging client connectivity issues or examining what data is being transmitted to applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | InputBuffer | | Accepted Values | 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. Use this when you need to investigate specific sessions that are causing blocking, consuming resources, or exhibiting unusual behavior. Cannot be used together with the -All parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RequestId Specifies the exact request (batch) to examine within a session when multiple requests are active. Optional parameter that defaults to the current request. Use this when a session has multiple concurrent requests and you need to examine a specific batch rather than the most recent one. Find request IDs by querying sys.dm_exec_requests for the target session_id. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -All Retrieves buffer information for all active user sessions instead of specific session IDs. Excludes system sessions to focus on user activity. Use this when performing broad troubleshooting to identify which sessions are running problematic queries or consuming resources. This parameter overrides any SessionId or RequestId values and may return large result sets on busy servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per row of DBCC buffer output. The exact properties depend on the -Operation parameter value. When Operation is InputBuffer: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The fully qualified SQL Server instance name (computer\\instance) SessionId: The session ID being examined (integer) EventType: The event type of the SQL statement (string) Parameters: Parameters associated with the SQL statement (string) EventInfo: Additional event information or the SQL statement itself (string) When Operation is OutputBuffer: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The fully qualified SQL Server instance name (computer\\instance) SessionId: The session ID being examined (integer) Buffer: The output buffer contents in ASCII format with non-printable characters removed (string) HexBuffer: The raw hexadecimal representation of the output buffer data (string, available but not displayed by default) The default display via Select-DefaultView shows only ComputerName, InstanceName, SqlInstance, SessionId, and Buffer (or EventType/Parameters/EventInfo for InputBuffer) to maintain readability. Use Select-Object * to view all properties including HexBuffer. &nbsp;"
  },
  {
    "name": "Get-DbaDbccStatistic",
    "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.",
    "category": "Performance",
    "tags": [
      "dbcc",
      "statistics"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbccStatistic",
    "popularityRank": 272,
    "synopsis": "Retrieves statistics information from tables and indexed views for query performance analysis",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbccStatistic View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves statistics information from tables and indexed views for query performance analysis 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. Syntax Get-DbaDbccStatistic [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Object] ] [[-Target] ] [[-Option] ] [-NoInformationalMessages] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Will run the statement SHOW_STATISTICS WITH STAT_HEADER against all Statistics on all User Tables or views... PS C:\\> Get-DbaDbccStatistic -SqlInstance SQLServer2017 Will 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 Authentication. Example 2: Will run the statement SHOW_STATISTICS WITH DENSITY_VECTOR against all Statistics on all User Tables or views... PS C:\\> Get-DbaDbccStatistic -SqlInstance SQLServer2017 -Database MyDb -Option DensityVector Will 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. Example 3: Will run the statement SHOW_STATISTICS WITH HISTOGRAM against all Statistics on table UserTable for database... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Get-DbaDbccStatistic -SqlInstance SQLServer2017 -SqlCredential $cred -Database MyDb -Object UserTable -Option Histogram Will run the statement SHOW_STATISTICS WITH HISTOGRAM against all Statistics on table UserTable for database MyDb on instance SQLServer2017. Connects using sqladmin credential. Example 4: Runs the statement SHOW_STATISTICS(&#39;dbo.UserTable&#39;, &#39;MyStatistic&#39;) WITH STATS_STREAM against database MyDb on... PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbccStatistic -SqlInstance SQLServer2017 -Database MyDb -Object 'dbo.UserTable' -Target MyStatistic -Option StatsStream Runs the statement SHOW_STATISTICS('dbo.UserTable', 'MyStatistic') WITH STATS_STREAM against database MyDb on instances Sql1 and Sql2/sqlexpress. Connects using Windows Authentication. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for statistics information. Accepts multiple database names as an array. When omitted, the function processes all accessible databases on the instance, which is useful for instance-wide statistics analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Format two-part names as 'Schema.ObjectName' (e.g., 'dbo.Orders'). When specified without Target, all statistics on the object are analyzed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Accepts statistics names (like '_WA_Sys_CustomerID'), index names (like 'IX_Orders_CustomerID'), or column names. Can be enclosed in brackets, quotes, or left unquoted. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Option Controls which type of statistics data to return from DBCC SHOW_STATISTICS. Defaults to 'StatHeader' which shows when statistics were last updated and row counts. Use 'Histogram' to analyze data distribution patterns, 'DensityVector' to examine column uniqueness, or 'StatsStream' to get raw binary statistics data for advanced analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | StatHeader | | Accepted Values | StatHeader,DensityVector,Histogram,StatsStream | -NoInformationalMessages Suppresses informational messages from DBCC SHOW_STATISTICS output, providing cleaner results focused only on the statistics data. Use this when running automated scripts or when you only need the statistics data without additional DBCC messaging. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per row returned from the DBCC SHOW_STATISTICS command. The properties included vary based on the Option parameter. Common properties (all outputs): ComputerName: The name of the SQL Server instance's computer InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the statistics Object: The schema-qualified name of the table or indexed view (e.g., 'dbo.Orders') Target: The name of the statistics object, index, or column being analyzed Cmd: The full DBCC SHOW_STATISTICS command that was executed When Option is 'StatHeader' (default): Name: The name of the statistics object Updated: DateTime when statistics were last updated Rows: Total number of rows in the table or indexed view RowsSampled: Number of rows sampled when statistics were created Steps: Number of steps in the histogram Density: Overall density value for the statistics AverageKeyLength: Average length of the index key in bytes StringIndex: Indicates if the statistics are on a string column (Yes/No) FilterExpression: Filter expression if statistics are filtered UnfilteredRows: Number of rows if different from Rows due to filtering PersistedSamplePercent: Sample percent used when creating statistics When Option is 'DensityVector': AllDensity: String representation of density value for all leading columns AverageLength: Average length of the column in bytes Columns: Names of the columns included in the density vector When Option is 'Histogram': RangeHiKey: Upper boundary value of the histogram step RangeRows: Number of rows with values within the histogram step range EqualRows: Number of rows with values equal to RangeHiKey DistinctRangeRows: Number of distinct values within the histogram step AverageRangeRows: Average number of rows per distinct value When Option is 'StatsStream': StatsStream: Raw binary statistics data as a binary object (for advanced analysis) Rows: Total number of rows in the table DataPages: Number of data pages used by the table &nbsp;"
  },
  {
    "name": "Get-DbaDbccUserOption",
    "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",
    "category": "Utilities",
    "tags": [
      "dbcc"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbccUserOption",
    "popularityRank": 548,
    "synopsis": "Retrieves current session-level SET options and connection settings from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbccUserOption View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves current session-level SET options and connection settings from SQL Server instances 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. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-useroptions-transact-sql Syntax Get-DbaDbccUserOption [-SqlInstance] [[-SqlCredential] ] [[-Option] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get results of DBCC USEROPTIONS for Instance Server1 PS C:\\> Get-DbaDbccUserOption -SqlInstance Server1 Example 2: Get results of DBCC USEROPTIONS for Instances Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbccUserOption Example 3: Connects using sqladmin credential and gets results of DBCC USEROPTIONS for Instance Server1 PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Get-DbaDbccUserOption -SqlInstance Server1 -SqlCredential $cred Example 4: Gets results of DBCC USEROPTIONS for Instance Server1 PS C:\\> Get-DbaDbccUserOption -SqlInstance Server1 -Option ansi_nulls, ansi_warnings, datefirst Gets results of DBCC USEROPTIONS for Instance Server1. Only display results for the options ansi_nulls, ansi_warnings, datefirst Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 levels without seeing the full list of 13 available options. Accepts any values in set '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' | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per session option returned by DBCC USEROPTIONS. If the -Option parameter is specified, only matching options are returned. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name (service name) SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName or just the computer name for the default instance Option: The name of the session option (e.g., ansi_nulls, dateformat, isolation level) Value: The current value or setting of the option &nbsp;"
  },
  {
    "name": "Get-DbaDbCertificate",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbCertificate",
    "popularityRank": 167,
    "synopsis": "Retrieves database-level certificates from SQL Server databases for security auditing and certificate management",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbCertificate View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database-level certificates from SQL Server databases for security auditing and certificate management 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. Syntax Get-DbaDbCertificate [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Certificate] ] [[-Subject] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all certificates PS C:\\> Get-DbaDbCertificate -SqlInstance sql2016 Example 2: Gets the certificate for the db1 database PS C:\\> Get-DbaDbCertificate -SqlInstance Server1 -Database db1 Example 3: Gets the cert1 certificate within the db1 database PS C:\\> Get-DbaDbCertificate -SqlInstance Server1 -Database db1 -Certificate cert1 Example 4: Gets the certificate within the db1 database that has the subject &#39;Availability Group Cert&#39; PS C:\\> Get-DbaDbCertificate -SqlInstance Server1 -Database db1 -Subject 'Availability Group Cert' Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for certificates. Accepts one or more database names as strings. Use this when you need to audit certificates in specific databases rather than all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to skip when retrieving certificates. Accepts one or more database names as strings. Useful when you want to audit most databases but exclude system databases or specific databases that don't contain certificates of interest. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Certificate Filters results to specific certificates by their name property. Accepts one or more certificate names as strings. Use this when you need to check the status of known certificates across multiple databases, such as tracking TDE certificates or Service Broker certificates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Subject Filters results to certificates with specific subject names. Accepts one or more subject strings for exact matching. Helpful when searching for certificates based on their distinguished name or common name, particularly when certificate names aren't descriptive but subjects are standardized. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase through the PowerShell pipeline. This allows you to chain commands like Get-DbaDatabase | Get-DbaDbCertificate for more complex filtering scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Certificate Returns 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 Server instance. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the certificate Name: The name of the certificate Subject: The subject field of the certificate for identification StartDate: The date and time when the certificate becomes valid ActiveForServiceBrokerDialog: Boolean indicating if the certificate is active for Service Broker dialog security ExpirationDate: The date and time when the certificate expires Issuer: The issuer of the certificate LastBackupDate: The date and time of the most recent backup of the certificate Owner: The owner or principal that owns the certificate PrivateKeyEncryptionType: The encryption type used for the private key (None, Password, MasterKey) Serial: The serial number of the certificate Additional properties available from the SMO Certificate object: DatabaseId: The unique identifier of the database containing the certificate Thumbprint: The SHA-1 hash of the certificate CreateDate: The date and time when the certificate was created SignedByCertificate: Name of the certificate that signed this certificate (if applicable) PrivateKeyExists: Boolean indicating if the certificate has a private key All properties from the base SMO Certificate object are accessible via Select-Object * even though only default properties are displayed without explicit selection. &nbsp;"
  },
  {
    "name": "Get-DbaDbCheckConstraint",
    "description": "Gets database Checks constraints.",
    "category": "Database Operations",
    "tags": [
      "database"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbCheckConstraint",
    "popularityRank": 408,
    "synopsis": "Gets database Check constraints.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbCheckConstraint View Source Claudio Silva (@ClaudioESSilva), claudioessilva.eu Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Gets database Check constraints. Description Gets database Checks constraints. Syntax Get-DbaDbCheckConstraint [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-ExcludeSystemTable] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database check constraints PS C:\\> Get-DbaDbCheckConstraint -SqlInstance sql2016 Example 2: Gets the check constraints for the db1 database PS C:\\> Get-DbaDbCheckConstraint -SqlInstance Server1 -Database db1 Example 3: Gets the check constraints for all databases except db1 PS C:\\> Get-DbaDbCheckConstraint -SqlInstance Server1 -ExcludeDatabase db1 Example 4: Gets the check constraints for all databases that are not system objects PS C:\\> Get-DbaDbCheckConstraint -SqlInstance Server1 -ExcludeSystemTable Example 5: Gets the check constraints for the databases on Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbCheckConstraint Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for check constraints. Accepts wildcards and multiple database names. Use this when you need to examine constraints on specific databases rather than all accessible databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the check constraint search. Accepts multiple database names. Useful when you want to scan most databases but skip certain ones like development or temporary databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemTable Excludes check constraints from system tables when searching through databases. Use this to focus only on user-created tables and avoid system table constraints that are typically not relevant for DBA reviews. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Check Returns one Check object per check constraint found in the specified databases. Each object represents a single check constraint defined on a database table. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the check constraint Parent: The table object that contains this check constraint ID: Unique identifier of the check constraint CreateDate: DateTime when the check constraint was created DateLastModified: DateTime when the check constraint was last modified Name: The name of the check constraint IsEnabled: Boolean indicating if the check constraint is currently enabled IsChecked: Boolean indicating if the constraint is checked during INSERT/UPDATE operations NotForReplication: Boolean indicating if the constraint applies to replication operations Text: The actual check constraint definition/expression (the logic that validates the data) State: SMO object state (Existing, Creating, Dropping, etc.) Additional properties available (from SMO Check object): DatabaseEngineEdition: The SQL Server edition where the check constraint exists DatabaseEngineType: The type of database engine Urn: Unique Resource Name for the constraint ExtendedProperties: Extended properties attached to the constraint All properties from the base SMO Check object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbCompatibility",
    "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.",
    "category": "Database Operations",
    "tags": [
      "compatibility",
      "database"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbCompatibility",
    "popularityRank": 264,
    "synopsis": "Retrieves database compatibility levels from SQL Server instances for upgrade planning and compliance auditing.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbCompatibility View Source Garry Bargsley, blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database compatibility levels from SQL Server instances for upgrade planning and compliance auditing. 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. Syntax Get-DbaDbCompatibility [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Displays database compatibility level for all user databases on server localhost\\sql2017 PS C:\\> Get-DbaDbCompatibility -SqlInstance localhost\\sql2017 Example 2: Displays database compatibility level for database Test on server localhost\\sql2017 PS C:\\> Get-DbaDbCompatibility -SqlInstance localhost\\sql2017 -Database Test Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for compatibility levels. Accepts wildcards for pattern matching. Use this when you need to focus on specific databases rather than reviewing all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from the pipeline to check their compatibility levels directly. Use this when you already have database objects from Get-DbaDatabase or other dbatools commands and want to avoid additional server queries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database checked. Each object contains the following properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName) Database: The name of the database DatabaseId: The internal ID of the database 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) &nbsp;"
  },
  {
    "name": "Get-DbaDbCompression",
    "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.",
    "category": "Database Operations",
    "tags": [
      "compression",
      "table",
      "database"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbCompression",
    "popularityRank": 411,
    "synopsis": "Retrieves compression settings, sizes, and row counts for tables and indexes across SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbCompression View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves compression settings, sizes, and row counts for tables and indexes across SQL Server databases. 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. Syntax Get-DbaDbCompression [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Table] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns objects size and current compression level for all user databases PS C:\\> Get-DbaDbCompression -SqlInstance localhost Example 2: Returns objects size and current compression level for objects within the TestDatabase database PS C:\\> Get-DbaDbCompression -SqlInstance localhost -Database TestDatabase Example 3: Returns objects size and current compression level for objects in all databases except the TestDatabase... PS C:\\> Get-DbaDbCompression -SqlInstance localhost -ExcludeDatabase TestDatabases Returns objects size and current compression level for objects in all databases except the TestDatabase database. Example 4: Returns objects size and current compression level for table1 and table2 in all databases except the... PS C:\\> Get-DbaDbCompression -SqlInstance localhost -ExcludeDatabase TestDatabases -Table table1, table2 Returns objects size and current compression level for table1 and table2 in all databases except the TestDatabase database. Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for compression information. Accepts multiple database names as an array. Use this when you want to focus compression analysis on specific databases rather than scanning all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to skip during compression analysis. Accepts multiple database names as an array. Use this to exclude system databases, maintenance databases, or other databases you don't want included in compression reporting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Specifies which tables to analyze for compression information. Accepts multiple table names as an array. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per partition for each table and index analyzed, providing compression details for heaps, clustered indexes, and non-clustered indexes. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database containing the table DatabaseId: Unique identifier (ID) of the database Schema: Name of the schema containing the table TableName: Name of the table IndexName: Name of the index (null for heap partitions) Partition: The partition number within the partition scheme IndexID: Index ID number (0 for heaps, >0 for indexes) IndexType: Type of index structure (Heap, ClusteredIndex, NonClusteredIndex, or other types) DataCompression: Current compression type (None, Row, Page, or ColumnStore) SizeCurrent: Current size of the partition in bytes (dbasize object supporting multiple units: B, KB, MB, GB) RowCount: Number of rows in the partition &nbsp;"
  },
  {
    "name": "Get-DbaDbDataClassification",
    "description": "Retrieves data classification labels stored as extended properties on table columns. Data classification\nis used to tag sensitive data columns with information type and sensitivity labels, which helps with\ncompliance, data governance, and security auditing.\n\nClassification metadata is stored as four extended properties on each classified column:\n- sys_information_type_id: GUID identifying the information type\n- sys_information_type_name: Human-readable information type name (e.g., \"Financial\", \"Health\", \"Credentials\")\n- sys_sensitivity_label_id: GUID identifying the sensitivity label\n- sys_sensitivity_label_name: Human-readable sensitivity label (e.g., \"Public\", \"General\", \"Confidential\")\n\nThese properties are compatible with Microsoft Information Protection (MIP) labels used by SQL Server\nData Discovery & Classification in SSMS and Azure SQL Database.\n\nRequires SQL Server 2005 or later due to use of sys.extended_properties.",
    "category": "Utilities",
    "tags": [
      "dataclassification",
      "classification",
      "compliance",
      "security"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbDataClassification",
    "popularityRank": 0,
    "synopsis": "Retrieves data classification information for columns in SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbDataClassification View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves data classification information for columns in SQL Server databases Description Retrieves data classification labels stored as extended properties on table columns. Data classification is used to tag sensitive data columns with information type and sensitivity labels, which helps with compliance, data governance, and security auditing. Classification metadata is stored as four extended properties on each classified column: sys_information_type_id: GUID identifying the information type sys_information_type_name: Human-readable information type name (e.g., \"Financial\", \"Health\", \"Credentials\") sys_sensitivity_label_id: GUID identifying the sensitivity label sys_sensitivity_label_name: Human-readable sensitivity label (e.g., \"Public\", \"General\", \"Confidential\") These properties are compatible with Microsoft Information Protection (MIP) labels used by SQL Server Data Discovery & Classification in SSMS and Azure SQL Database. Requires SQL Server 2005 or later due to use of sys.extended_properties. Syntax Get-DbaDbDataClassification [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Schema] ] [[-Table] ] [[-Column] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all data classifications across all databases on sql2019 PS C:\\> Get-DbaDbDataClassification -SqlInstance sql2019 Example 2: Returns all data classifications in the AdventureWorks database PS C:\\> Get-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks Example 3: Returns data classifications for columns in the Customer table PS C:\\> Get-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks -Table Customer Example 4: Returns all data classifications in AdventureWorks by piping the database object PS C:\\> Get-DbaDatabase -SqlInstance sql2019 -Database AdventureWorks | Get-DbaDbDataClassification Example 5: Returns only columns classified as Highly Confidential in AdventureWorks PS C:\\> Get-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks | Where-Object SensitivityLabel -eq \"Highly Confidential\" Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for data classifications. Only applies when connecting directly via SqlInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Filters results to columns in the specified schema(s). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Filters results to columns in the specified table(s). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Column Filters results to the specified column name(s). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per classified column with the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name Database: The database name Schema: The schema name of the table Table: The table name Column: The column name InformationTypeId: GUID identifying the information type InformationType: Human-readable information type name SensitivityLabelId: GUID identifying the sensitivity label SensitivityLabel: Human-readable sensitivity label name &nbsp;"
  },
  {
    "name": "Get-DbaDbDbccOpenTran",
    "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's 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",
    "category": "Utilities",
    "tags": [
      "dbcc"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbDbccOpenTran",
    "popularityRank": 526,
    "synopsis": "Identifies the oldest active transactions in database transaction logs using DBCC OPENTRAN",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbDbccOpenTran View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies the oldest active transactions in database transaction logs using DBCC OPENTRAN 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. This function helps DBAs troubleshoot performance issues by revealing the oldest active transaction and any distributed or replicated transactions within each database's transaction log. When transactions remain open for extended periods, they prevent log truncation and can cause cascading blocking issues throughout your SQL Server instance. The 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. This 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. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-opentran-transact-sql Syntax Get-DbaDbDbccOpenTran [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Connects to instance SqlServer2017 using Windows Authentication and runs the command DBCC OPENTRAN WITH... PS C:\\> Get-DbaDbDbccOpenTran -SqlInstance SQLServer2017 Connects to instance SqlServer2017 using Windows Authentication and runs the command DBCC OPENTRAN WITH TABLERESULTS, NO_INFOMSGS against each database. Example 2: Connects to instance SqlServer2017 using Windows Authentication and runs the command DBCC OPENTRAN(CurrentDB)... PS C:\\> Get-DbaDbDbccOpenTran -SqlInstance SQLServer2017 -Database CurrentDB Connects to instance SqlServer2017 using Windows Authentication and runs the command DBCC OPENTRAN(CurrentDB) WITH TABLERESULTS, NO_INFOMSGS against the CurrentDB database. Example 3: Connects to instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the command DBCC OPENTRAN... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbDbccOpenTran -SqlCredential $cred Connects to instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the command DBCC OPENTRAN WITH TABLERESULTS, NO_INFOMSGS against each database. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for open transactions. Accepts database names or database IDs. Use this when investigating transaction issues in specific databases rather than scanning all databases on the instance. If omitted, DBCC OPENTRAN runs against all accessible databases, which may take longer on instances with many databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per active transaction found, or one object per database when no active transactions exist. Properties: ComputerName: The name of the server where the SQL Server instance is running InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName) Database: The database name that was scanned DatabaseId: The unique identifier of the database Cmd: The DBCC OPENTRAN command executed (for reference/debugging) Output: Human-readable summary of the result (\"Oldest active transaction\" or \"No active open transactions.\") 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 Data: The corresponding value for the Field (e.g., transaction ID number, SPID number, timestamp, program name), or $null if no active transactions When 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. When open transactions are found, Field and Data contain the result columns from DBCC OPENTRAN output, providing detailed transaction details. &nbsp;"
  },
  {
    "name": "Get-DbaDbDetachedFileInfo",
    "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's 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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "detach"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbDetachedFileInfo",
    "popularityRank": 414,
    "synopsis": "Reads detached SQL Server database files to extract metadata and file structure without attaching them.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbDetachedFileInfo View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Reads detached SQL Server database files to extract metadata and file structure without attaching them. 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. Perfect 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. The function reads the MDF file header using SQL Server's 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. Returns 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. Syntax Get-DbaDbDetachedFileInfo [-SqlInstance] [[-SqlCredential] ] [-Path] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns information about the detached database file M:\\Archive\\mydb.mdf using the SQL Server instance sql2016 PS C:\\> Get-DbaDbDetachedFileInfo -SqlInstance sql2016 -Path M:\\Archive\\mydb.mdf Returns 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. Required Parameters -SqlInstance Source SQL Server. This instance must be online and is required to parse the information contained with in the detached database file. This function will not attach the database file, it will only use SQL Server to read its contents. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. Use this when you need to examine database files in archives, backups, or migration staging areas before deciding whether to attach them. Supports multiple file paths and accepts wildcards, but each MDF file must be accessible from the specified SQL Server instance. | Property | Value | | --- | --- | | Alias | Mdf,FilePath,FullName | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per detached MDF file analyzed. Properties: ComputerName: The computer name of the SQL Server instance used to read the file InstanceName: The SQL Server instance name used to read the file SqlInstance: The full SQL Server instance name (computer\\instance) Name: The original database name stored in the detached MDF file Version: Human-readable SQL Server version name (e.g., \"SQL Server 2019\", \"SQL Server 2016\") ExactVersion: The raw internal version number from the MDF file header Collation: The database collation name, or the collation ID if the name cannot be resolved DataFiles: System.Collections.Specialized.StringCollection containing the paths of all data files that belonged to this database LogFiles: System.Collections.Specialized.StringCollection containing the paths of all transaction log files that belonged to this database &nbsp;"
  },
  {
    "name": "Get-DbaDbEncryption",
    "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.",
    "category": "Security",
    "tags": [
      "encryption"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbEncryption",
    "popularityRank": 266,
    "synopsis": "Retrieves comprehensive encryption inventory from SQL Server databases including TDE status, certificates, and keys.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbEncryption View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves comprehensive encryption inventory from SQL Server databases including TDE status, certificates, and keys. 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. Syntax Get-DbaDbEncryption [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-IncludeSystemDBs] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: List all encryption found on the instance by database PS C:\\> Get-DbaDbEncryption -SqlInstance DEV01 Example 2: List all encryption found for the MyDB database PS C:\\> Get-DbaDbEncryption -SqlInstance DEV01 -Database MyDB Example 3: List all encryption found for all databases except MyDB PS C:\\> Get-DbaDbEncryption -SqlInstance DEV01 -ExcludeDatabase MyDB Example 4: List all encryption found for all databases including the system databases PS C:\\> Get-DbaDbEncryption -SqlInstance DEV01 -IncludeSystemDBs Required Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to examine for encryption objects including TDE, certificates, and keys. Accepts database names as strings or arrays. Use this to focus encryption audits on specific databases rather than scanning all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the encryption inventory scan. Useful when you need to audit most databases but skip certain ones. Commonly used to exclude databases with known encryption issues or maintenance databases that don't require encryption compliance checks. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSystemDBs Includes system databases (master, model, msdb, tempdb) in the encryption inventory. By default, only user databases are scanned. Use this when conducting comprehensive security audits that require visibility into system database encryption objects and TDE configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties vary depending on the type of encryption object found. Common properties in all output objects: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the encryption object Encryption: The type of encryption object (EncryptionEnabled (TDE), Certificate, Asymmetric key, or Symmetric key) Name: The name of the encryption object Owner: The owner of the encryption object Object: The underlying SMO object (Certificate, AsymmetricKey, SymmetricKey, or DatabaseEncryptionKey) Additional properties specific to encryption type: LastBackup: DateTime of the last certificate backup (populated for TDE and Certificate types only) PrivateKeyEncryptionType: How the private key is encrypted (populated for TDE, Certificate, Asymmetric key, and Symmetric key types) EncryptionAlgorithm: The encryption algorithm used (populated for TDE and Asymmetric key types) KeyLength: The key length in bits (populated for Asymmetric key and Symmetric key types) ExpirationDate: DateTime when the certificate expires (populated for TDE and Certificate types only) Note: When TDE encryption is enabled on a database, the returned object includes details of the server certificate protecting the database encryption key. &nbsp;"
  },
  {
    "name": "Get-DbaDbEncryptionKey",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbEncryptionKey",
    "popularityRank": 255,
    "synopsis": "Retrieves Transparent Data Encryption (TDE) database encryption keys from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbEncryptionKey View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Transparent Data Encryption (TDE) database encryption keys from SQL Server databases 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. Syntax Get-DbaDbEncryptionKey [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all encryption keys from sql2016 PS C:\\> Get-DbaDbEncryptionKey -SqlInstance sql2016 Example 2: Gets the encryption key for the db1 database on the sql01 instance PS C:\\> Get-DbaDbEncryptionKey -SqlInstance sql01 -Database db1 Example 3: Gets the cert1 encryption key within the db1 database PS C:\\> Get-DbaDbEncryptionKey -SqlInstance sql01 -Database db1 -Certificate cert1 Example 4: Gets the encryption key within the db1 database that has the subject &#39;Availability Group Cert&#39; on sql01 PS C:\\> Get-DbaDbEncryptionKey -SqlInstance sql01 -Database db1 -Subject 'Availability Group Cert' Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to retrieve TDE encryption keys from. Accepts wildcards for pattern matching. Use this when you need to check encryption status for specific databases instead of all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the encryption key retrieval operation. Useful when scanning all databases except certain ones like system databases or test databases. Commonly used to skip tempdb or databases that are known to be unencrypted. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase or other dbatools commands. This allows you to filter databases using Get-DbaDatabase's extensive filtering options before checking encryption keys. Particularly useful for complex database selection scenarios or when working with specific database collections. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.DatabaseEncryptionKey Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the encryption key CreateDate: DateTime when the encryption key was created EncryptionAlgorithm: The encryption algorithm used (Aes128, Aes192, Aes256, or TripleDes) EncryptionState: Current encryption state (Encrypted, EncryptionInProgress, DecryptionInProgress, or EncryptionUnsupported) EncryptionType: Type of encryptor used (ServerCertificate or ServerAsymmetricKey) EncryptorName: Name of the certificate or asymmetric key protecting this encryption key ModifyDate: DateTime when the encryption key was last modified OpenedDate: DateTime when the encryption key was last opened RegenerateDate: DateTime when the encryption key was last regenerated SetDate: DateTime when the encryption key was last set Thumbprint: Thumbprint hash of the certificate protecting this encryption key All properties from the base SMO DatabaseEncryptionKey object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbExtentDiff",
    "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/",
    "category": "Backup & Restore",
    "tags": [
      "backup",
      "database"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbExtentDiff",
    "popularityRank": 454,
    "synopsis": "Calculates the percentage of database extents modified since the last full backup",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbExtentDiff View Source Viorel Ciucu, cviorel.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Calculates the percentage of database extents modified since the last full backup 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. For 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. Based 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/ Syntax Get-DbaDbExtentDiff [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get the changes for the DBA database PS C:\\> Get-DbaDbExtentDiff -SqlInstance SQL2016 -Database DBA Example 2: Get the changes for the DB01 database on multiple servers PS C:\\> $Cred = Get-Credential sqladmin PS C:\\> Get-DbaDbExtentDiff -SqlInstance SQL2017N1, SQL2017N2, SQL2016 -Database DB01 -SqlCredential $Cred Required Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for extent changes since the last full backup. Accepts multiple database names and supports wildcards. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during the extent change analysis. Accepts multiple database names and supports wildcards. Use this to exclude system databases, read-only databases, or databases where you don't need backup planning analysis, reducing execution time and focusing on relevant databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database analyzed, containing the extent change analysis since the last full backup. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: Name of the database analyzed ExtentsTotal: Total number of extents in the database ExtentsChanged: Number of extents that have been modified since the last full backup ChangedPerc: Percentage of the database that has changed since the last full backup (rounded to 2 decimal places) &nbsp;"
  },
  {
    "name": "Get-DbaDbFeatureUsage",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "deprecated"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbFeatureUsage",
    "popularityRank": 321,
    "synopsis": "Identifies Enterprise-edition features currently used in databases that prevent downgrading to Standard edition",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbFeatureUsage View Source Brandon Abshire, netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies Enterprise-edition features currently used in databases that prevent downgrading to Standard edition 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. Enterprise 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. Returns feature ID, feature name, and database information for each Enterprise feature found, making it easy to identify which databases need attention before edition changes. Syntax Get-DbaDbFeatureUsage [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Shows features that are enabled in the testdb and db2 databases but not supported on the all the editions of... PS C:\\> Get-DbaDatabase -SqlInstance sql2008 -Database testdb, db2 | Get-DbaDbFeatureUsage Shows features that are enabled in the testdb and db2 databases but not supported on the all the editions of SQL Server. Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for Enterprise edition features. Accepts wildcards for pattern matching. Use this when you need to check specific databases instead of scanning all databases on the instance. Helpful when planning edition downgrades for particular databases or troubleshooting feature usage in development environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the Enterprise feature scan. Accepts wildcards for pattern matching. Use this to skip system databases, read-only databases, or databases you know don't need to be downgraded. Commonly used to exclude tempdb, model, or archived databases from bulk scanning operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects directly from the pipeline, typically from Get-DbaDatabase output. Use this for advanced filtering scenarios or when you've already retrieved specific database objects. Allows you to chain database selection commands with feature usage checking in a single pipeline operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per Enterprise-edition feature found in the queried database(s). Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance (MSSQLSERVER for default instance) SqlInstance: The full SQL Server instance name (computer\\instance or just computer for default) Id: The feature ID from sys.dm_db_persisted_sku_features Feature: The name of the Enterprise-edition feature that is currently in use Database: The database where this Enterprise feature was detected No properties are returned if no Enterprise features are found in the queried database(s). &nbsp;"
  },
  {
    "name": "Get-DbaDbFile",
    "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.",
    "category": "Database Operations",
    "tags": [
      "storage",
      "data",
      "file",
      "log"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbFile",
    "popularityRank": 90,
    "synopsis": "Retrieves comprehensive database file information including size, growth, I/O statistics, and storage details.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbFile View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves comprehensive database file information including size, growth, I/O statistics, and storage details. 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. Syntax Get-DbaDbFile [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-FileGroup] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Will return an object containing all file groups and their contained files for every database on the sql2016... PS C:\\> Get-DbaDbFile -SqlInstance sql2016 Will return an object containing all file groups and their contained files for every database on the sql2016 SQL Server instance Example 2: Will return an object containing all file groups and their contained files for the Impromptu Database on the... PS C:\\> Get-DbaDbFile -SqlInstance sql2016 -Database Impromptu Will return an object containing all file groups and their contained files for the Impromptu Database on the sql2016 SQL Server instance Example 3: Will return an object containing all file groups and their contained files for the Impromptu and Trading... PS C:\\> Get-DbaDbFile -SqlInstance sql2016 -Database Impromptu, Trading Will return an object containing all file groups and their contained files for the Impromptu and Trading databases on the sql2016 SQL Server instance Example 4: Will accept piped input from Get-DbaDatabase and return an object containing all file groups and their... PS C:\\> Get-DbaDatabase -SqlInstance sql2016 -Database Impromptu, Trading | Get-DbaDbFile Will 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 Example 5: Return any files that are in the Index filegroup of the AdventureWorks2017 database PS C:\\> Get-DbaDbFile -SqlInstance sql2016 -Database AdventureWorks2017 -FileGroup Index Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for file information. Accepts wildcards for pattern matching. Use this when you need to focus on specific databases rather than scanning all databases on the instance. Particularly useful for capacity planning or troubleshooting file growth issues on targeted databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the file analysis. Accepts wildcards for pattern matching. Use this to skip system databases, test databases, or databases you don't need to analyze. Helpful when performing routine file space reviews while avoiding databases that don't require monitoring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileGroup Filters results to show only files within the specified filegroup name. Use this when analyzing specific filegroups for space utilization, I/O patterns, or growth planning. Particularly valuable when troubleshooting performance issues or planning filegroup-specific storage migrations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from other dbatools commands like Get-DbaDatabase. Use this for advanced filtering scenarios or when chaining multiple dbatools commands together. Allows you to pre-filter databases using complex criteria before analyzing their file information. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database file on the SQL Server instance(s). Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database containing the file DatabaseID: Internal ID of the database FileGroupName: Name of the filegroup containing this file (NULL for log files) ID: File ID within the database Type: Type of file - 0 for data file, 1 for log file (Integer) TypeDescription: Human-readable file type (ROWS or LOG) LogicalName: Logical name of the file within SQL Server PhysicalName: Operating system file path State: Current state of the file (ONLINE, OFFLINE, etc.) MaxSize: Maximum size the file can grow to - displays as dbasize object (KB, MB, GB, etc.) Growth: Growth increment - value depends on GrowthType GrowthType: How the file grows (Percent or KB) NextGrowthEventSize: Size added during next autogrow event - displays as dbasize object Size: Current size of the file - displays as dbasize object UsedSpace: Space currently used within the file - displays as dbasize object AvailableSpace: Free space within the file (Size - UsedSpace) - displays as dbasize object IsOffline: Boolean indicating if the file is offline IsReadOnly: Boolean indicating if the file is read-only IsReadOnlyMedia: Boolean indicating if the underlying storage media is read-only IsSparse: Boolean indicating if the file is sparse (snapshots) NumberOfDiskWrites: Count of write operations to the file since instance startup NumberOfDiskReads: Count of read operations from the file since instance startup ReadFromDisk: Total bytes read from the file since instance startup - displays as dbasize object WrittenToDisk: Total bytes written to the file since instance startup - displays as dbasize object VolumeFreeSpace: Free space available on the volume containing this file - displays as dbasize object FileGroupDataSpaceId: Internal ID of the filegroup data space FileGroupType: Type of filegroup (NULL for log files, or name for data filegroups) FileGroupTypeDescription: Description of filegroup type FileGroupDefault: Boolean indicating if this is the default filegroup FileGroupReadOnly: Boolean indicating if the filegroup is read-only Note: 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. &nbsp;"
  },
  {
    "name": "Get-DbaDbFileGroup",
    "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.",
    "category": "Database Operations",
    "tags": [
      "storage",
      "file",
      "data"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbFileGroup",
    "popularityRank": 460,
    "synopsis": "Retrieves filegroup configuration and storage details from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbFileGroup View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves filegroup configuration and storage details from SQL Server databases 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. Syntax Get-DbaDbFileGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-InputObject] ] [[-FileGroup] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Return all FileGroups for all databases on instance sql2016 PS C:\\> Get-DbaDbFileGroup -SqlInstance sql2016 Example 2: Return all FileGroups for database MyDB on instance sql2016 PS C:\\> Get-DbaDbFileGroup -SqlInstance sql2016 -Database MyDB Example 3: Returns information on filegroup called Primary if it exists in any database on the server sql2016 PS C:\\> Get-DbaDbFileGroup -SqlInstance sql2016 -FileGroup Primary Example 4: Returns information on all FileGroups for all databases on instances &#39;localhost&#39;,&#39;localhost\\namedinstance&#39; PS C:\\> 'localhost','localhost\\namedinstance' | Get-DbaDbFileGroup Example 5: Returns information on all FileGroups for all databases on instances &#39;localhost&#39;,&#39;localhost\\namedinstance&#39; PS C:\\> 'localhost','localhost\\namedinstance' | Get-DbaDbFileGroup Example 6: Returns information on all FileGroups for all databases except model and master on instances... PS C:\\> Get-DbaDatabase -SqlInstance SQL1\\SQLExpress,SQL2 -ExcludeDatabase model,master | Get-DbaDbFileGroup Returns information on all FileGroups for all databases except model and master on instances SQL1\\SQLExpress,SQL2 Optional Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for filegroup information. Accepts wildcards and multiple database names. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase pipeline input for processing filegroups. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -FileGroup Filters results to specific filegroups by name, such as 'PRIMARY' or custom filegroups. Use this when troubleshooting storage issues with particular filegroups or when you need to verify configuration of specific data placement strategies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.FileGroup Returns one FileGroup object per filegroup in the selected databases. For example, querying a database with PRIMARY, SECONDARY, and FILESTREAM filegroups returns three objects. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (service name) SqlInstance: The full SQL Server instance name (domain\\instance or instance) Parent: The parent Database object name FileGroupType: Type of filegroup (RowsFileGroup, FileStreamFileGroup, or MemoryOptimizedFileGroup) Name: Name of the filegroup (e.g., PRIMARY, SECONDARY, FILESTREAM) Size: Total size of the filegroup in kilobytes Additional properties available (from SMO FileGroup object): AbsolutePhysicalName: Absolute physical name of the filegroup DefaultFileGroup: Boolean indicating if this is the default filegroup Files: Collection of DataFile objects in the filegroup IsDefault: Boolean indicating if this is the default filegroup State: State of the filegroup (Normal, Offline, Defunct) All properties from the base SMO FileGroup object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbFileGrowth",
    "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.",
    "category": "Database Operations",
    "tags": [
      "storage",
      "data",
      "file",
      "log"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbFileGrowth",
    "popularityRank": 206,
    "synopsis": "Retrieves database file auto-growth settings and maximum size limits",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbFileGrowth View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database file auto-growth settings and maximum size limits 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. Syntax Get-DbaDbFileGrowth [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database file growths on sql2017, sql2016, sql2012 PS C:\\> Get-DbaDbFileGrowth -SqlInstance sql2017, sql2016, sql2012 Example 2: Gets the database file growth info for pubs on sql2017, sql2016, sql2012 PS C:\\> Get-DbaDbFileGrowth -SqlInstance sql2017, sql2016, sql2012 -Database pubs Example 3: Gets the test database file growth information on sql2016 PS C:\\> Get-DbaDatabase -SqlInstance sql2016 -Database test | Get-DbaDbFileGrowth Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for file growth settings. Accepts wildcards for pattern matching. Use this when you need to check growth configuration for specific databases instead of all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase via pipeline input. Use this when you want to analyze file growth settings for databases already retrieved by another dbatools command. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database file across all specified databases. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database containing the file MaxSize: Maximum size the file can grow to - displays as dbasize object (KB, MB, GB, etc.) GrowthType: How the file grows - either \"Percent\" or \"kb\" Growth: Growth increment value - interpretation depends on GrowthType (percentage or KB) File: Logical name of the file within SQL Server (aliased from LogicalName) FileName: Operating system file path (aliased from PhysicalName) State: Current state of the file (ONLINE, OFFLINE, etc.) Additional properties available (from Get-DbaDbFile object): DatabaseID: Internal ID of the database FileGroupName: Name of the filegroup containing this file (NULL for log files) ID: File ID within the database Type: Type of file - 0 for data file, 1 for log file (Integer) TypeDescription: Human-readable file type (ROWS or LOG) LogicalName: Logical name of the file within SQL Server PhysicalName: Operating system file path NextGrowthEventSize: Size that will be added during the next autogrow event - displays as dbasize object Size: Current size of the file - displays as dbasize object UsedSpace: Space currently used within the file - displays as dbasize object AvailableSpace: Free space within the file (Size - UsedSpace) - displays as dbasize object IsOffline: Boolean indicating if the file is offline IsReadOnly: Boolean indicating if the file is read-only IsReadOnlyMedia: Boolean indicating if the underlying storage media is read-only IsSparse: Boolean indicating if the file is sparse (snapshots) NumberOfDiskWrites: Count of write operations to the file since instance startup NumberOfDiskReads: Count of read operations from the file since instance startup ReadFromDisk: Total bytes read from the file since instance startup - displays as dbasize object WrittenToDisk: Total bytes written to the file since instance startup - displays as dbasize object VolumeFreeSpace: Free space available on the volume containing this file - displays as dbasize object FileGroupDataSpaceId: Internal ID of the filegroup data space FileGroupType: Type of filegroup (NULL for log files, or name for data filegroups) FileGroupTypeDescription: Description of filegroup type FileGroupDefault: Boolean indicating if this is the default filegroup FileGroupReadOnly: Boolean indicating if the filegroup is read-only All properties from the base object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbFileMapping",
    "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's file groups and creates a complete mapping that preserves the original file structure during restore operations.",
    "category": "Backup & Restore",
    "tags": [
      "storage",
      "file",
      "data",
      "log",
      "backup"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbFileMapping",
    "popularityRank": 276,
    "synopsis": "Creates file mapping hashtable from existing database for use in restore operations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbFileMapping View Source Chrissy LeMaire (@cl), netnerds.net , Andreas Jordan (@JordanOrdix), ordix.de Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates file mapping hashtable from existing database for use in restore operations 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's file groups and creates a complete mapping that preserves the original file structure during restore operations. Syntax Get-DbaDbFileMapping [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Restores test to sql2019 using the file structure built from the existing database on sql2016 PS C:\\> $filemap = Get-DbaDbFileMapping -SqlInstance sql2016 -Database test PS C:\\> Get-ChildItem \\\\nas\\db\\backups\\test | Restore-DbaDatabase -SqlInstance sql2019 -Database test -FileMapping $filemap.FileMapping Optional Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to extract file mappings from. Accepts wildcards for pattern matching. Use this when you need file mappings for specific databases instead of all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects directly from Get-DbaDatabase or other dbatools database functions via pipeline. Use this when you want to chain database operations or work with pre-filtered database collections. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per accessible database provided as input. Each object contains the file mapping information needed for restore operations. Properties: ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The instance name of the SQL Server (e.g., \"MSSQLSERVER\" or \"SQLEXPRESS\") SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database from which file mappings were extracted FileMapping: A hashtable mapping logical file names (keys) to their physical file paths (values), compatible with Restore-DbaDatabase &nbsp;"
  },
  {
    "name": "Get-DbaDbForeignKey",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "foreignkey",
      "table"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbForeignKey",
    "popularityRank": 390,
    "synopsis": "Retrieves foreign key constraints from SQL Server database tables",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbForeignKey View Source Claudio Silva (@ClaudioESSilva), claudioessilva.eu Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves foreign key constraints from SQL Server database tables Description Retrieves all foreign key constraint definitions from tables across one or more SQL Server databases. Essential for documenting referential integrity relationships, analyzing table dependencies before migrations, and troubleshooting cascade operations. Returns detailed foreign key properties including referenced tables, schema information, and constraint status (enabled/disabled, checked/unchecked). Supports filtering by database and excluding system tables to focus on user-defined constraints. Syntax Get-DbaDbForeignKey [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-ExcludeSystemTable] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database Foreign Keys PS C:\\> Get-DbaDbForeignKey -SqlInstance sql2016 Example 2: Gets the Foreign Keys for the db1 database PS C:\\> Get-DbaDbForeignKey -SqlInstance Server1 -Database db1 Example 3: Gets the Foreign Keys for all databases except db1 PS C:\\> Get-DbaDbForeignKey -SqlInstance Server1 -ExcludeDatabase db1 Example 4: Gets the Foreign Keys from all tables that are not system objects from all databases PS C:\\> Get-DbaDbForeignKey -SqlInstance Server1 -ExcludeSystemTable Example 5: Gets the Foreign Keys for the databases on Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbForeignKey Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for foreign key constraints. Accepts database names, wildcards, or arrays. Use this when you need to focus on specific databases rather than scanning all accessible databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the foreign key scan. Useful for skipping large databases, test environments, or databases known to have no relevant constraints. Commonly used to exclude system databases like master, model, msdb, and tempdb when focusing on user databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemTable Excludes system tables from the foreign key analysis, focusing only on user-created tables. Use this switch when documenting application schemas or analyzing business logic relationships, as system table foreign keys are typically not relevant for most DBA tasks. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.ForeignKey Returns one ForeignKey object per foreign key constraint found in the specified databases. Each object represents a single foreign key relationship between tables. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the foreign key Schema: The schema name containing the table with the foreign key Table: The table name that contains the foreign key (referencing table) ID: Unique identifier of the foreign key constraint CreateDate: DateTime when the foreign key constraint was created DateLastModified: DateTime when the foreign key constraint was last modified Name: The name of the foreign key constraint IsEnabled: Boolean indicating if the foreign key constraint is currently enabled IsChecked: Boolean indicating if the constraint is enforced during INSERT/UPDATE operations NotForReplication: Boolean indicating if the constraint applies to replication operations ReferencedKey: The primary key or unique key being referenced by this foreign key ReferencedTable: The name of the table being referenced (referenced table) ReferencedTableSchema: The schema name of the referenced table Additional properties available (from SMO ForeignKey object): Columns: Collection of columns that make up the foreign key DeleteAction: Action to take when the referenced row is deleted (NoAction, Cascade, SetNull, SetDefault) UpdateAction: Action to take when the referenced key is updated (NoAction, Cascade, SetNull, SetDefault) DatabaseEngineEdition: The SQL Server edition where the foreign key exists DatabaseEngineType: The type of database engine IsMemoryOptimized: Boolean indicating if the parent table is memory-optimized IsSystemNamed: Boolean indicating if the constraint was system-generated (auto-named) State: SMO object state (Existing, Creating, Dropping, etc.) Urn: Unique Resource Name for the constraint ExtendedProperties: Extended properties attached to the constraint All properties from the base SMO ForeignKey object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbIdentity",
    "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's 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",
    "category": "Utilities",
    "tags": [
      "dbcc"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbIdentity",
    "popularityRank": 395,
    "synopsis": "Retrieves current identity values from tables without reseeding using DBCC CHECKIDENT",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbIdentity View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves current identity values from tables without reseeding using DBCC CHECKIDENT 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. DBAs 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. The NORESEED option ensures no changes are made to your tables - it's purely informational. The function parses the DBCC output to extract specific identity metrics, making it ideal for scripted monitoring and reporting workflows. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql Syntax Get-DbaDbIdentity [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Table] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Connects to AdventureWorks2014 on instance SqlServer2017 using Windows Authentication and runs the command... PS C:\\> Get-DbaDbIdentity -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Table 'Production.ScrapReason' Connects to AdventureWorks2014 on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKIDENT('Production.ScrapReason', NORESEED) to return the current identity value. Example 2: Connects to AdventureWorks2014 on instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbIdentity -SqlCredential $cred -Database AdventureWorks2014 -Table 'Production.ScrapReason' Connects to AdventureWorks2014 on instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the command DBCC CHECKIDENT('Production.ScrapReason', NORESEED) to return the current identity value. Example 3: is_memory_optimized = 0&quot; Checks the current identity value for all non memory optimized tables with an... PS C:\\> $query = \"SELECT QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + 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 PS C:\\> $IdentityTables = Invoke-DbaQuery -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Query $query -As SingleValue PS C:\\> Get-DbaDbIdentity -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Table $IdentityTables is_memory_optimized = 0\" Checks the current identity value for all non memory optimized tables with an Identity in the AdventureWorks2014 database on the SQLServer2017 instance. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for identity column values. If not specified, all accessible databases on the instance are processed. Use this to focus on specific databases when you don't need identity information from every database on the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Specifies the table names to check for current identity seed and column values. Accepts schema-qualified names like 'Production.ScrapReason'. This 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per table checked. Each object contains the current identity seed value and the actual highest value in the identity column. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (service name) SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the table Table: The name of the table that was checked (schema-qualified) Cmd: The T-SQL DBCC CHECKIDENT command that was executed IdentityValue: The current seed value of the identity column (integer or null if unable to determine) ColumnValue: The highest value currently in the identity column (integer or null if unable to determine) Output: The raw DBCC output message from SQL Server &nbsp;"
  },
  {
    "name": "Get-DbaDbLogShipError",
    "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't 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.",
    "category": "Utilities",
    "tags": [
      "logshipping"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbLogShipError",
    "popularityRank": 245,
    "synopsis": "Retrieves log shipping error details from msdb to troubleshoot failed backup, copy, and restore operations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbLogShipError View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves log shipping error details from msdb to troubleshoot failed backup, copy, and restore operations Description Queries the log shipping monitor error detail table in msdb to return comprehensive error information when log shipping operations fail. Identifies which specific action failed (backup on primary, copy, or restore on secondary) along with session details and error messages. Saves time by consolidating error details from both primary and secondary instances into a single view, so you don't have to manually query multiple system tables. Essential for troubleshooting log shipping failures and determining whether issues occurred during backup, file copy, or database restore phases. Syntax Get-DbaDbLogShipError [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Action] ] [[-DateTimeFrom] ] [[-DateTimeTo] ] [-Primary] [-Secondary] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get all the log shipping errors that occurred PS C:\\> Get-DbaDbLogShipError -SqlInstance sql1 Example 2: Get the errors that have something to do with the backup of the databases PS C:\\> Get-DbaDbLogShipError -SqlInstance sql1 -Action Backup Example 3: Get the errors that occurred on the secondary instance PS C:\\> Get-DbaDbLogShipError -SqlInstance sql1 -Secondary Get the errors that occurred on the secondary instance. This will return the copy of the restore actions because those only occur on the secondary instance Example 4: Get the errors that have occurred from &quot;01/05/2018&quot; PS C:\\> Get-DbaDbLogShipError -SqlInstance sql1 -DateTimeFrom \"01/05/2018\" Get the errors that have occurred from \"01/05/2018\". This can also be of format \"yyyy-MM-dd\" Example 5: Get the errors that have occurred between &quot;01/05/2018&quot; and &quot;01/07/2018&quot; PS C:\\> Get-DbaDbLogShipError -SqlInstance sql1 -Secondary -DateTimeFrom \"01/05/2018\" -DateTimeTo \"2018-01-07\" Get the errors that have occurred between \"01/05/2018\" and \"01/07/2018\". See that is doesn't matter how the date is represented. Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to include when retrieving log shipping errors. Requires exact database names, not wildcards. Use this when troubleshooting specific databases rather than reviewing all log shipped databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the log shipping error results. Requires exact database names, not wildcards. Useful when you want to see errors for all databases except certain ones, like excluding test databases from production error reviews. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Action Filters errors by log shipping operation type: Backup (primary), Copy (between servers), or Restore (secondary). Use this to isolate which phase of log shipping is failing when troubleshooting multi-step log shipping workflows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Backup,Copy,Restore | -DateTimeFrom Sets the earliest date and time for error records to include in results. Essential for focusing on recent failures or analyzing errors that occurred after a specific event or change. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DateTimeTo Sets the latest date and time for error records to include in results. Combined with DateTimeFrom, this creates a specific time window for analyzing log shipping failures during maintenance windows or incidents. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Primary Returns only errors from backup operations that occur on the primary server. Use this when troubleshooting backup failures or primary-side log shipping issues like insufficient disk space or backup device problems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Secondary Returns only errors from copy and restore operations that occur on secondary servers. Use this when troubleshooting file transfer failures or restore issues on the destination server, such as network connectivity or disk space problems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per log shipping error found. If no errors exist, nothing is returned. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: Name of the database involved in the log shipping error Instance: The role where the error occurred - either \"Primary\" (backup operation) or \"Secondary\" (copy or restore operation) Action: The type of log shipping operation that failed - \"Backup\" (primary server), \"Copy\" (between servers), or \"Restore\" (secondary server) SessionID: Unique identifier for the log shipping session in which the error occurred SequenceNumber: Sequential number of this error within the session for ordering multiple errors LogTime: DateTime when the error was recorded in the log shipping monitor tables Message: The detailed error message describing what went wrong (e.g., file not found, insufficient disk space, network timeout) &nbsp;"
  },
  {
    "name": "Get-DbaDbLogSpace",
    "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.",
    "category": "Utilities",
    "tags": [
      "storage",
      "space",
      "log",
      "file"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbLogSpace",
    "popularityRank": 274,
    "synopsis": "Retrieves transaction log space usage and capacity information from SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbLogSpace View Source Jess Pomfret, JessPomfret.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves transaction log space usage and capacity information from SQL Server databases. 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. Essential 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. Syntax Get-DbaDbLogSpace [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-ExcludeSystemDatabase] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the transaction log usage information for all databases on Server1 PS C:\\> Get-DbaDbLogSpace -SqlInstance Server1 Example 2: Returns the transaction log usage information for both Database1 and Database 2 on Server1 PS C:\\> Get-DbaDbLogSpace -SqlInstance Server1 -Database Database1, Database2 Example 3: Returns the transaction log usage information for all databases on Server1, except Database3 PS C:\\> Get-DbaDbLogSpace -SqlInstance Server1 -ExcludeDatabase Database3 Example 4: Returns the transaction log usage information for all databases on Server1, except the system databases PS C:\\> Get-DbaDbLogSpace -SqlInstance Server1 -ExcludeSystemDatabase Example 5: Returns the transaction log usage information for Database1 for a group of servers from SQL Server Central... PS C:\\> Get-DbaRegisteredServer -SqlInstance cmsServer | Get-DbaDbLogSpace -Database Database1 Returns the transaction log usage information for Database1 for a group of servers from SQL Server Central Management Server (CMS). Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for transaction log space usage. Accepts wildcards for pattern matching. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip when checking transaction log space usage. Accepts wildcards for pattern matching. Use this to exclude databases you don't need to monitor regularly, such as test databases, read-only databases, or databases with known stable log usage patterns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemDatabase Excludes system databases (master, model, msdb, tempdb) from the transaction log space report. Use this when focusing on user databases only, as system database log usage is typically managed differently and may not require the same monitoring attention. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database containing transaction log space usage metrics. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (service name) SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database LogSize: The total size of the transaction log file(s) for the database, formatted as a dbasize object (e.g., \"10 MB\", \"1 GB\") LogSpaceUsedPercent: The percentage of the transaction log that is currently in use (0-100) LogSpaceUsed: The amount of space currently used in the transaction log file(s), formatted as a dbasize object The 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. &nbsp;"
  },
  {
    "name": "Get-DbaDbMail",
    "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.",
    "category": "Utilities",
    "tags": [
      "mail",
      "dbmail",
      "email"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbMail",
    "popularityRank": 160,
    "synopsis": "Retrieves Database Mail configuration including profiles, accounts, and settings from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbMail View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Database Mail configuration including profiles, accounts, and settings from SQL Server instances 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. Syntax Get-DbaDbMail [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the db mail server object on sql01\\sharepoint PS C:\\> Get-DbaDbMail -SqlInstance sql01\\sharepoint Example 2: Returns the db mail server object on sql01\\sharepoint then return a bunch more columns PS C:\\> Get-DbaDbMail -SqlInstance sql01\\sharepoint | Select-Object Example 3: Returns the db mail server object for &quot;sql2014&quot;,&quot;sql2016&quot; and &quot;sqlcluster\\sharepoint&quot; PS C:\\> $servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\" PS C:\\> $servers | Get-DbaDbMail Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Mail.SqlMail Returns 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 that instance. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Profiles: Collection of Database Mail profile objects configured on the instance Accounts: Collection of Database Mail account objects configured on the instance ConfigurationValues: Collection of Database Mail configuration settings (MaxFileSize, ProhibitedExtensions, etc.) Properties: Collection of additional mail properties All 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 detailed information about specific profiles, accounts, configuration settings, and mail servers from these collections. &nbsp;"
  },
  {
    "name": "Get-DbaDbMailAccount",
    "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.",
    "category": "Utilities",
    "tags": [
      "mail",
      "dbmail",
      "email"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbMailAccount",
    "popularityRank": 349,
    "synopsis": "Retrieves Database Mail account configurations from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbMailAccount View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Database Mail account configurations from SQL Server instances 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. Syntax Get-DbaDbMailAccount [[-SqlInstance] ] [[-SqlCredential] ] [[-Account] ] [[-ExcludeAccount] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns Database Mail accounts on sql01\\sharepoint PS C:\\> Get-DbaDbMailAccount -SqlInstance sql01\\sharepoint Example 2: Returns &#39;The DBA Team&#39; Database Mail account from sql01\\sharepoint PS C:\\> Get-DbaDbMailAccount -SqlInstance sql01\\sharepoint -Account 'The DBA Team' Example 3: Returns the Database Mail accounts on sql01\\sharepoint then return a bunch more columns PS C:\\> Get-DbaDbMailAccount -SqlInstance sql01\\sharepoint | Select-Object Example 4: Returns the Database Mail accounts for sql2014, sql2016 and sqlcluster\\sharepoint PS C:\\> $servers = sql2014, sql2016, sqlcluster\\sharepoint PS C:\\> $servers | Get-DbaDbMail | Get-DbaDbMailAccount Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Account Specifies one or more Database Mail account names to retrieve. Accepts exact account names and supports multiple values. Use this when you need to check specific mail accounts rather than retrieving all configured accounts on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeAccount Specifies one or more Database Mail account names to exclude from results. Accepts exact account names and supports multiple values. Use this when you want to retrieve most accounts but skip specific ones, such as excluding test or deprecated accounts from auditing reports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts SqlMail objects from the pipeline, typically from Get-DbaDbMail. Allows you to chain Database Mail commands together. Use this when processing multiple instances through Get-DbaDbMail or when working with previously retrieved Database Mail configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Mail.SqlMailAccount Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ID: The unique identifier (int) for the Database Mail account within the instance Name: The name of the Database Mail account DisplayName: The display name used in the \"From\" field of emails sent by this account Description: Text description of the account EmailAddress: The email address used as the sender (from address) for this account ReplyToAddress: The reply-to email address for emails sent from this account IsBusyAccount: Boolean indicating if the account is currently busy sending messages MailServers: Collection of SMTP servers configured for this account MailProfile: Collection of Database Mail profile names associated with this account Additional properties available (from SMO SqlMailAccount object): Account: The account owner or associated account information AccountType: Type of the account CreateDate: DateTime when the account was created Urn: The unified resource name (URN) for the object Parent: Reference to the parent SqlMail object Properties: Collection of property objects for the account State: Current state of the account object (Existing, Creating, Deleting) Uid: Unique identifier for the account Use Select-Object to access all available properties if needed. &nbsp;"
  },
  {
    "name": "Get-DbaDbMailConfig",
    "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.",
    "category": "Utilities",
    "tags": [
      "mail",
      "dbmail",
      "email"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbMailConfig",
    "popularityRank": 354,
    "synopsis": "Retrieves Database Mail configuration settings from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbMailConfig View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Database Mail configuration settings from SQL Server instances Description Retrieves all Database Mail configuration values from SQL Server, including settings like MaxFileSize, ProhibitedExtensions, DatabaseMailExeMinLifeTime, and LoggingLevel. This function helps DBAs audit current Database Mail configurations, troubleshoot email delivery issues, and verify compliance with organizational email policies. You can retrieve all configuration settings or filter by specific configuration names to focus on particular settings. The output includes the configuration name, current value, and description for each setting across your SQL Server environment. Syntax Get-DbaDbMailConfig [[-SqlInstance] ] [[-SqlCredential] ] [[-Name] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns DBMail configs on sql01\\sharepoint PS C:\\> Get-DbaDbMailConfig -SqlInstance sql01\\sharepoint Example 2: Returns the ProhibitedExtensions configuration on sql01\\sharepoint PS C:\\> Get-DbaDbMailConfig -SqlInstance sql01\\sharepoint -Name ProhibitedExtensions Example 3: Returns the DBMail configs on sql01\\sharepoint then return a bunch more columns PS C:\\> Get-DbaDbMailConfig -SqlInstance sql01\\sharepoint | Select-Object Example 4: Returns the DBMail configs for &quot;sql2014&quot;,&quot;sql2016&quot; and &quot;sqlcluster\\sharepoint&quot; PS C:\\> $servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\" PS C:\\> $servers | Get-DbaDbMail | Get-DbaDbMailConfig Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies which Database Mail configuration settings to retrieve by name, such as MaxFileSize, ProhibitedExtensions, or LoggingLevel. Use this when you need to check specific configuration values instead of retrieving all Database Mail settings. Accepts multiple configuration names and supports aliases Config and ConfigName. | Property | Value | | --- | --- | | Alias | Config,ConfigName | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Database Mail objects from Get-DbaDbMail for pipeline processing. Use this when chaining multiple Database Mail functions together or when you already have Database Mail objects loaded. Allows you to retrieve configurations from multiple SQL Server instances efficiently through the pipeline. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Mail.ConfigurationValue Returns one Database Mail configuration setting per object with added properties from the parent SqlMail object. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The configuration setting name (e.g., MaxFileSize, ProhibitedExtensions, DatabaseMailExeMinLifeTime, LoggingLevel) Value: The current value of the configuration setting Description: Human-readable description of what the configuration setting controls Additional properties available (from SMO ConfigurationValue object): Parent: Reference to the parent SqlMail object Urn: The uniform resource name for the configuration value object Properties: Collection of SQL Server object properties State: The current state of the object (Existing, Creating, Pending, etc.) All properties from the base SMO ConfigurationValue object are accessible using Select-Object even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Get-DbaDbMailHistory",
    "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.",
    "category": "Utilities",
    "tags": [
      "mail",
      "dbmail",
      "email"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbMailHistory",
    "popularityRank": 604,
    "synopsis": "Retrieves Database Mail history from SQL Server's msdb database for troubleshooting and compliance",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbMailHistory View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Database Mail history from SQL Server's msdb database for troubleshooting and compliance 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. Syntax Get-DbaDbMailHistory [[-SqlInstance] ] [[-SqlCredential] ] [[-Since] ] [[-Status] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the entire DBMail history on sql01\\sharepoint PS C:\\> Get-DbaDbMailHistory -SqlInstance sql01\\sharepoint Example 2: Returns the entire DBMail history on sql01\\sharepoint then return a bunch more columns PS C:\\> Get-DbaDbMailHistory -SqlInstance sql01\\sharepoint | Select-Object Example 3: Returns the all DBMail history for &quot;sql2014&quot;,&quot;sql2016&quot; and &quot;sqlcluster\\sharepoint&quot; PS C:\\> $servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\" PS C:\\> $servers | Get-DbaDbMailHistory Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Since Filters mail history to only include emails sent after the specified date and time. Use this when troubleshooting recent delivery issues or generating reports for specific time periods. Accepts standard PowerShell DateTime objects like (Get-Date).AddDays(-7) for the past week. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Status Filters results to only show emails with the specified delivery status. Use 'Failed' to identify delivery problems, 'Unsent' for queued messages, or 'Retrying' for current retry attempts. Accepts multiple values: Unsent, Sent, Failed, and Retrying. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per Database Mail message from the MSDB sysmail_allitems table. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Profile: The Database Mail profile name associated with this message Recipients: Email addresses of the primary recipients CopyRecipients: Email addresses of the CC recipients BlindCopyRecipients: Email addresses of the BCC recipients Subject: The subject line of the email message Importance: The importance level (Low, Normal, High) Sensitivity: The sensitivity level (Normal, Personal, Private, Confidential) FileAttachments: File attachments included with the message AttachmentEncoding: Character encoding used for attachments SendRequestDate: DateTime when the message was requested to be sent SendRequestUser: Windows or SQL login that initiated the email SentStatus: The delivery status (Unsent, Sent, Failed, Retrying) SentDate: DateTime when the message was actually sent (or failed) Additional properties available (via Select-Object ):** MailItemId: Unique identifier for this mail message in the sysmail_allitems table ProfileId: Unique identifier of the Database Mail profile Body: The message body text BodyFormat: The body format (HTML or TEXT) Query: T-SQL query that generated query results attached to the message ExecuteQueryDatabase: Database where the query was executed AttachQueryResultAsFile: Whether query results were attached as a file QueryResultHeader: Whether query result headers were included in the attachment QueryResultWidth: Width of the query result output QueryResultSeparator: Character used to separate columns in query results ExcludeQueryOutput: Whether to exclude the query execution output AppendQueryError: Whether to append query errors to the output SentAccountId: Account ID used to send the message LastModDate: DateTime when this mail item record was last modified LastModUser: Login that last modified this mail item record &nbsp;"
  },
  {
    "name": "Get-DbaDbMailLog",
    "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.",
    "category": "Utilities",
    "tags": [
      "mail",
      "dbmail",
      "email"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbMailLog",
    "popularityRank": 569,
    "synopsis": "Retrieves Database Mail event logs from msdb for troubleshooting email delivery issues",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbMailLog View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Database Mail event logs from msdb for troubleshooting email delivery issues 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. Syntax Get-DbaDbMailLog [[-SqlInstance] ] [[-SqlCredential] ] [[-Since] ] [[-Type] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the entire DBMail log on sql01\\sharepoint PS C:\\> Get-DbaDbMailLog -SqlInstance sql01\\sharepoint Example 2: Returns the entire DBMail log on sql01\\sharepoint, includes all returned information PS C:\\> Get-DbaDbMailLog -SqlInstance sql01\\sharepoint | Select-Object Example 3: Returns only the Error and Information DBMail log for &quot;sql2014&quot;,&quot;sql2016&quot; and &quot;sqlcluster\\sharepoint&quot; PS C:\\> $servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\" PS C:\\> $servers | Get-DbaDbMailLog -Type Error, Information Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Since Filters log entries to only include events that occurred on or after the specified date and time. Use this when troubleshooting recent mail delivery issues or investigating problems within a specific timeframe. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Filters log entries by event type to focus troubleshooting on specific mail system behaviors. Use 'Error' to identify failed deliveries, 'Warning' for potential issues, 'Success' to verify deliveries, 'Information' for general events, or 'Internal' for system-level Database Mail operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per log entry in the Database Mail event log. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) LogDate: DateTime when the event was logged EventType: The type of event (Error, Warning, Success, Information, or Internal) Description: Detailed description of the event or error message Login: The user who last modified this log entry Additional properties available (accessible via Select-Object ):* LogId: Unique identifier for the log entry (integer) ProcessId: Process ID associated with the event (integer) MailItemId: Identifier of the mail item, if applicable (integer) AccountId: Identifier of the Database Mail account (integer) LastModDate: DateTime when the log entry was last modified LastModUser: The user who last modified the log entry All properties are accessible even though only default properties are displayed without using Select-Object . &nbsp;"
  },
  {
    "name": "Get-DbaDbMailProfile",
    "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.",
    "category": "Utilities",
    "tags": [
      "mail",
      "dbmail",
      "email"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbMailProfile",
    "popularityRank": 351,
    "synopsis": "Retrieves Database Mail profiles and their configuration details from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbMailProfile View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Database Mail profiles and their configuration details from SQL Server instances 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. Syntax Get-DbaDbMailProfile [[-SqlInstance] ] [[-SqlCredential] ] [[-Profile] ] [[-ExcludeProfile] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns DBMail profiles on sql01\\sharepoint PS C:\\> Get-DbaDbMailProfile -SqlInstance sql01\\sharepoint Example 2: Returns The DBA Team DBMail profile from sql01\\sharepoint PS C:\\> Get-DbaDbMailProfile -SqlInstance sql01\\sharepoint -Profile 'The DBA Team' Example 3: Returns the DBMail profiles on sql01\\sharepoint then return a bunch more columns PS C:\\> Get-DbaDbMailProfile -SqlInstance sql01\\sharepoint | Select-Object Example 4: Returns the DBMail profiles for &quot;sql2014&quot;, &quot;sql2016&quot; and &quot;sqlcluster\\sharepoint&quot; PS C:\\> $servers = \"sql2014\", \"sql2016\", \"sqlcluster\\sharepoint\" PS C:\\> $servers | Get-DbaDbMail | Get-DbaDbMailProfile Example 5: Returns the DBMail profiles for &quot;sql2014&quot;, &quot;sql2016&quot; and &quot;sqlcluster\\sharepoint&quot; PS C:\\> $servers = \"sql2014\", \"sql2016\", \"sqlcluster\\sharepoint\" PS C:\\> Get-DbaDbMailProfile -SqlInstance $servers Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Accepts exact profile names and is case-sensitive to match SQL Server Database Mail profile naming. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Helps focus on production profiles during compliance reviews or troubleshooting scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Eliminates the need to specify SqlInstance when you already have Database Mail objects from a previous command. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Mail.MailProfile Returns 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 alerts. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ID: The unique identifier (int) for the Database Mail profile within the instance Name: The name of the Database Mail profile Description: Text description of the profile's purpose or intended use ForceDeleteForActiveProfiles: Boolean indicating if the profile will be forcefully deleted even if actively used IsBusyProfile: Boolean indicating if the profile is currently busy processing mail messages MailAccount: Collection of Database Mail account names associated with this profile Additional properties available (from SMO MailProfile object): Parent: Reference to the parent SqlMail object Properties: Collection of property objects for the profile State: Current state of the profile object (Existing, Creating, Deleting) Urn: The unified resource name (URN) for the object Uid: Unique identifier for the profile MailAccountMemberships: Collection of mail accounts associated with this profile LastModificationTime: DateTime when the profile was last modified (if available) Use Select-Object to access all available properties if needed. &nbsp;"
  },
  {
    "name": "Get-DbaDbMailServer",
    "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.",
    "category": "Utilities",
    "tags": [
      "mail",
      "dbmail",
      "email"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbMailServer",
    "popularityRank": 440,
    "synopsis": "Retrieves SMTP server configurations from SQL Server Database Mail accounts",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbMailServer View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SMTP server configurations from SQL Server Database Mail accounts 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. Syntax Get-DbaDbMailServer [[-SqlInstance] ] [[-SqlCredential] ] [[-Server] ] [[-Account] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all DBMail servers on sql01\\sharepoint PS C:\\> Get-DbaDbMailServer -SqlInstance sql01\\sharepoint Example 2: Returns The DBA Team DBMail server from sql01\\sharepoint PS C:\\> Get-DbaDbMailServer -SqlInstance sql01\\sharepoint -Server DbaTeam Example 3: Returns the DBMail servers on sql01\\sharepoint then return a bunch more columns PS C:\\> Get-DbaDbMailServer -SqlInstance sql01\\sharepoint | Select-Object Example 4: Returns the DBMail servers for &quot;sql2014&quot;,&quot;sql2016&quot; and &quot;sqlcluster\\sharepoint&quot; PS C:\\> $servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\" PS C:\\> $servers | Get-DbaDbMail | Get-DbaDbMailServer Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Accepts exact server names like 'smtp.company.com' or 'mail-relay-01'. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -Account Restricts results to mail servers associated with specific Database Mail account names. Use this when troubleshooting email issues for particular applications or services. Helpful for isolating server configurations when you have multiple Database Mail accounts with different SMTP settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Database Mail objects from Get-DbaDbMail via pipeline. Allows you to chain Database Mail operations together. Use this when you need to process mail server configurations from a filtered set of SQL instances or specific Database Mail setups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Mail.MailServer Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Account: The name of the Database Mail account that uses this server Name: The name or hostname of the SMTP server Port: The SMTP port number used for connections (typically 25, 465, or 587) EnableSsl: Boolean indicating whether SSL/TLS encryption is enabled for this server ServerType: The type of mail server (typically \"SMTP\") UserName: The username used to authenticate with the SMTP server, if required UseDefaultCredentials: Boolean indicating whether default Windows credentials are used NoCredentialChange: Boolean indicating the credential policy for the server All properties from the SMO MailServer object are accessible via Select-Object if needed. &nbsp;"
  },
  {
    "name": "Get-DbaDbMasterKey",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbMasterKey",
    "popularityRank": 384,
    "synopsis": "Retrieves database master key information from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbMasterKey View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database master key information from SQL Server databases 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. Syntax Get-DbaDbMasterKey [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all master database keys PS C:\\> Get-DbaDbMasterKey -SqlInstance sql2016 Example 2: Gets the master key for the db1 database PS C:\\> Get-DbaDbMasterKey -SqlInstance Server1 -Database db1 Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for database master keys. Accepts wildcards for pattern matching. Use this when you need to audit encryption keys for specific databases instead of scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip when checking for master keys. Accepts wildcards for pattern matching. Use this to exclude system databases or databases you know don't use encryption features during security audits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase through the pipeline for master key analysis. Use this when you need to check master keys for databases that match specific criteria like compatibility level or size. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.MasterKey Returns 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). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database containing the master key CreateDate: DateTime when the master key was created DateLastModified: DateTime when the master key was last modified IsEncryptedByServer: Boolean indicating if the master key is encrypted by the server master key All properties from the base SMO MasterKey object are accessible via Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbMemoryUsage",
    "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/",
    "category": "Performance",
    "tags": [
      "memory",
      "database"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbMemoryUsage",
    "popularityRank": 229,
    "synopsis": "Retrieves detailed buffer pool memory consumption by database and page type for performance analysis.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbMemoryUsage View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed buffer pool memory consumption by database and page type for performance analysis. 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. The 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. This command is based on query provided by Aaron Bertrand. Reference: https://www.mssqltips.com/sqlservertip/2393/determine-sql-server-memory-use-by-database-and-object/ Syntax Get-DbaDbMemoryUsage [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-IncludeSystemDb] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the buffer pool consumption for all user databases PS C:\\> Get-DbaDbMemoryUsage -SqlInstance sqlserver2014a Example 2: Returns the buffer pool consumption for all user databases and system databases PS C:\\> Get-DbaDbMemoryUsage -SqlInstance sqlserver2014a -IncludeSystemDb Example 3: Returns the buffer pool consumption for tempdb database only PS C:\\> Get-DbaDbMemoryUsage -SqlInstance sql1 -IncludeSystemDb -Database tempdb Example 4: Returns the buffer pool consumption for all user databases and tempdb database PS C:\\> Get-DbaDbMemoryUsage -SqlInstance sql2 -IncludeSystemDb -Exclude 'master','model','msdb','ResourceDb' Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Restricts analysis to specific databases by name. Accepts multiple database names or wildcard patterns. Use this when investigating memory usage for particular databases rather than analyzing the entire instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -ExcludeDatabase Excludes specific databases from the memory analysis by name. Accepts multiple database names. Useful for filtering out known databases that aren't relevant to your current investigation or capacity planning. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSystemDb Includes system databases (master, model, msdb, tempdb, ResourceDb) in the memory consumption analysis. Use this when troubleshooting overall instance memory pressure or when tempdb memory usage is a concern. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per page type per database showing buffer pool memory consumption. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database consuming the buffer pool pages PageType: Type of page in the buffer (e.g., data pages, index pages, etc.) Size: Amount of memory consumed by this database and page type (in MB, as DbaSize object) PercentUsed: Percentage of total buffer pool consumed by this database and page type (0-100) Additional properties available: PageCount: The number of 8KB pages allocated to this database and page type in the buffer pool All properties are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbMirror",
    "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's mirroring properties in SSMS.",
    "category": "Utilities",
    "tags": [
      "mirroring",
      "mirror",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbMirror",
    "popularityRank": 379,
    "synopsis": "Retrieves database mirroring configuration and status for mirrored databases and their witness servers",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbMirror View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database mirroring configuration and status for mirrored databases and their witness servers 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's mirroring properties in SSMS. Syntax Get-DbaDbMirror [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets properties of database mirrors and mirror witnesses on localhost PS C:\\> Get-DbaDbMirror -SqlInstance localhost Example 2: Gets properties of database mirrors and mirror witnesses on localhost and sql2016 SQL Server instances PS C:\\> Get-DbaDbMirror -SqlInstance localhost, sql2016 Example 3: Gets properties of database mirrors and mirror witnesses on localhost and sql2016 SQL Server instances for... PS C:\\> Get-DbaDbMirror -SqlInstance localhost, sql2016 -Database mymirror Gets properties of database mirrors and mirror witnesses on localhost and sql2016 SQL Server instances for databases named mymirror Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for mirroring configuration. Accepts multiple database names and supports wildcards. Use this when you want to examine mirroring status for specific databases instead of checking all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Database Returns one Database object for each mirrored database found on the instance. For databases with witness servers, the witness information is added as additional properties. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Database name MirroringSafetyLevel: Safety level of the mirroring partnership (OFF, FULL, HIGH) MirroringStatus: Current mirroring status (CONNECTED, DISCONNECTED, SUSPENDED, PENDING_FAILOVER) MirroringPartner: Server name of the mirroring partner MirroringPartnerInstance: Instance name of the mirroring partner MirroringFailoverLogSequenceNumber: Log sequence number for failover MirroringID: Unique identifier for the mirroring partnership MirroringRedoQueueMaxSize: Maximum redo queue size in KB MirroringRoleSequence: Current role sequence number MirroringSafetySequence: Current safety level sequence number MirroringTimeout: Mirroring timeout in seconds MirroringWitness: Server name of the witness server (if configured) MirroringWitnessStatus: Status of the witness server connection (CONNECTED, DISCONNECTED, UNKNOWN, SUSPENDED) For databases with witness servers, MirroringPartner, MirroringSafetyLevel, and MirroringWitnessStatus may be updated with values from the sys.database_mirroring_witnesses system view. &nbsp;"
  },
  {
    "name": "Get-DbaDbMirrorMonitor",
    "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.",
    "category": "Utilities",
    "tags": [
      "mirroring",
      "mirror",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbMirrorMonitor",
    "popularityRank": 485,
    "synopsis": "Retrieves database mirroring performance metrics and monitoring history from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbMirrorMonitor View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database mirroring performance metrics and monitoring history from SQL Server instances 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. Use 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. The 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. Syntax Get-DbaDbMirrorMonitor [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-InputObject] ] [-Update] [[-LimitResults] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns last two hours&#39; worth of status rows for a monitored database from the status table on sql2008 and... PS C:\\> Get-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012 Returns last two hours' worth of status rows for a monitored database from the status table on sql2008 and sql2012. Example 2: Updates monitor stats then returns the last 24 hours worth of status rows for a monitored database from the... PS C:\\> Get-DbaDbMirrorMonitor -SqlInstance sql2005 -LimitResults LastDay -Update Updates monitor stats then returns the last 24 hours worth of status rows for a monitored database from the status table on sql2008 and sql2012. Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which mirrored databases to monitor. Only databases configured for mirroring will return results. Use this to focus monitoring on specific databases instead of checking all mirrored databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase pipeline input. Use this when you want to filter databases first before checking their mirroring status. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Update Forces a refresh of mirroring statistics before retrieving results by calling sp_dbmmonitorupdate. Use this when you need the most current metrics, though SQL Server automatically limits updates to once every 15 seconds and requires sysadmin privileges. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LimitResults Controls how much historical monitoring data to retrieve from the msdb.dbo.dbm_monitor_data table. Choose shorter time periods for recent performance analysis or longer periods for trend analysis. Row-based options return the most recent entries regardless of time. Options include: LastRow LastTwoHours LastFourHours LastEightHours LastDay LastTwoDays Last100Rows Last500Rows Last1000Rows Last1000000Rows | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | LastTwoHours | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per monitoring record retrieved from the database mirroring monitor table. Multiple records may be returned depending on the -LimitResults parameter value. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: Name of the mirrored database Role: The role of the server instance - Principal or Mirror MirroringState: Current mirroring state (Synchronizing, Synchronized, Suspended, Disconnected, etc.) WitnessStatus: Status of the witness server (Connected, Disconnected, Quorum Lost, etc.) LogGenerationRate: Rate at which transaction log is being generated on the principal (KB/sec) UnsentLog: Amount of log not yet sent to the mirror (KB) SendRate: Rate at which log is being sent to the mirror (KB/sec) UnrestoredLog: Amount of log not yet restored on the mirror (KB) RecoveryRate: Rate at which log is being restored on the mirror (KB/sec) TransactionDelay: Delay caused by database mirroring for committed transactions (milliseconds) TransactionsPerSecond: Number of transactions per second being processed AverageDelay: Average transaction delay (milliseconds) TimeRecorded: DateTime when this monitoring record was recorded TimeBehind: Amount the mirror lags behind the principal (milliseconds) LocalTime: Local time on the server when the record was generated &nbsp;"
  },
  {
    "name": "Get-DbaDbObjectTrigger",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "trigger"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbObjectTrigger",
    "popularityRank": 458,
    "synopsis": "Retrieves triggers attached to tables and views across SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbObjectTrigger View Source Claudio Silva (@claudioessilva), claudioessilva.eu Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves triggers attached to tables and views across SQL Server databases. 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. Syntax Get-DbaDbObjectTrigger [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Type] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all database triggers PS C:\\> Get-DbaDbObjectTrigger -SqlInstance sql2017 Example 2: Returns all triggers for database supa on sql2017 PS C:\\> Get-DbaDatabase -SqlInstance sql2017 -Database supa | Get-DbaDbObjectTrigger Example 3: Returns all triggers for database supa on sql2017 PS C:\\> Get-DbaDbObjectTrigger -SqlInstance sql2017 -Database supa Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for table and view triggers. Accepts wildcards for pattern matching. Use this when you need to audit triggers in specific databases rather than scanning the entire instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to exclude from trigger enumeration. Accepts wildcards for pattern matching. Useful when you want to skip system databases or databases known to have no custom triggers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Filters triggers by the type of object they are attached to: Table, View, or All (default). Use 'Table' or 'View' when you need to focus on triggers for specific object types during auditing or troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | All | | Accepted Values | All,Table,View | -InputObject Accepts specific table or view objects from Get-DbaDbTable and Get-DbaDbView via pipeline input. Use this when you want to check triggers on particular tables or views rather than scanning entire databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Trigger Returns one Trigger object for each DML trigger found on the specified tables and views. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the trigger Parent: Reference to the parent table or view object that the trigger is attached to IsEnabled: Boolean indicating if the trigger is currently enabled DateLastModified: DateTime when the trigger was last modified Additional properties available (from SMO Trigger object): ID: The unique identifier for the trigger AnsiNullsStatus: Boolean indicating if ANSI_NULLS was set when trigger was created AssemblyName: Name of the .NET assembly for CLR triggers BodyStartIndex: Index position where trigger body starts in the text ClassName: The CLR class name for CLR-based triggers CreateDate: DateTime when the trigger was created DdlTriggerEvents: List of DDL events that trigger this trigger (if database-level) ExecutionContext: Execution context setting for the trigger ExecutionContextLogin: Login used for execution context ImplementationType: Type of trigger implementation (T-SQL or CLR) IsDesignMode: Boolean indicating design mode status IsEncrypted: Boolean indicating if trigger definition is encrypted IsSystemObject: Boolean indicating if this is a system object MethodName: Method name for CLR-based triggers QuotedIdentifierStatus: Boolean indicating QUOTED_IDENTIFIER setting State: Current state of the trigger object TextHeader: Header text of the trigger definition TextMode: Text mode setting of the trigger All properties from the SMO Trigger object are accessible via Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbOrphanUser",
    "description": "An orphan user is defined by a user that does not have their matching login. (Login property = \"\").\n\nNote: Users in contained databases (Partial or Full containment type) are not considered orphaned for SQL logins,\nas these users authenticate directly to the database without requiring a server-level login.\nWindows users are still checked for orphaned status regardless of containment type.",
    "category": "Security",
    "tags": [
      "orphan",
      "database",
      "user",
      "login"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbOrphanUser",
    "popularityRank": 66,
    "synopsis": "Get orphaned users.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbOrphanUser View Source Claudio Silva (@ClaudioESSilva) , Garry Bargsley (@gbargsley) , Simone Bizzotto (@niphlod) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Get orphaned users. Description An orphan user is defined by a user that does not have their matching login. (Login property = \"\"). Note: Users in contained databases (Partial or Full containment type) are not considered orphaned for SQL logins, as these users authenticate directly to the database without requiring a server-level login. Windows users are still checked for orphaned status regardless of containment type. Syntax Get-DbaDbOrphanUser [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Finds all orphan users without matching Logins in all databases present on server &#39;localhost\\sql2016&#39; PS C:\\> Get-DbaDbOrphanUser -SqlInstance localhost\\sql2016 Example 2: Finds all orphan users without matching Logins in all databases present on server &#39;localhost\\sql2016&#39; PS C:\\> Get-DbaDbOrphanUser -SqlInstance localhost\\sql2016 -SqlCredential $cred Finds all orphan users without matching Logins in all databases present on server 'localhost\\sql2016'. SQL Server authentication will be used in connecting to the server. Example 3: Finds orphan users without matching Logins in the db1 database present on server &#39;localhost\\sql2016&#39; PS C:\\> Get-DbaDbOrphanUser -SqlInstance localhost\\sql2016 -Database db1 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for orphaned users. Accepts database names, wildcards, or arrays. Use this when you need to focus the orphaned user search on specific databases rather than checking all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip when checking for orphaned users. Useful for excluding system databases or databases under maintenance. Commonly used to exclude tempdb, distribution, or databases where orphaned users are expected and acceptable. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per orphaned user found across the specified databases. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: Name of the database containing the orphaned user User: Name of the orphaned user Additional properties available: SmoUser: The underlying Microsoft.SqlServer.Management.Smo.User object with all SMO properties &nbsp;"
  },
  {
    "name": "Get-DbaDbPageInfo",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "database",
      "page"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbPageInfo",
    "popularityRank": 441,
    "synopsis": "Retrieves detailed page allocation information from SQL Server databases for storage analysis and troubleshooting",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbPageInfo View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed page allocation information from SQL Server databases for storage analysis and troubleshooting 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. Use this when troubleshooting storage issues, analyzing space utilization patterns, or investigating page-level performance problems in your databases. Results can be filtered by specific databases, schemas, and tables to focus your analysis on problem areas. Requires SQL Server 2012 or higher as it depends on the sys.dm_db_database_page_allocations DMV. Syntax Get-DbaDbPageInfo [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Schema] ] [[-Table] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns page information for all databases on sql2017 PS C:\\> Get-DbaDbPageInfo -SqlInstance sql2017 Example 2: Returns page information for the testdb on sql2017 and sql2016 PS C:\\> Get-DbaDbPageInfo -SqlInstance sql2017, sql2016 -Database testdb Example 3: Returns page information for the testdb on all $servers PS C:\\> $servers | Get-DbaDatabase -Database testdb | Get-DbaDbPageInfo Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for page allocation information. Accepts wildcards for pattern matching. Use this when you need to focus on specific databases rather than scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Limits the analysis to tables within specific schemas only. Multiple schema names can be provided. Helpful when troubleshooting page issues in specific application schemas or when you want to exclude system schemas from results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Restricts page information retrieval to specific tables only. Can be combined with Schema parameter for precise targeting. Use this when investigating page allocation problems for known problematic tables or when performing focused storage analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase, allowing you to chain commands together. This enables scenarios like getting databases from multiple instances and then analyzing their page information in a single pipeline. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Data.DataRow Returns 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 databases. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name Database: The name of the database containing the table Schema: The schema name containing the table Table: The table name PageType: Type of the page (e.g., 'DATA_PAGE', 'INDEX_PAGE', 'LOB_DATA_PAGE') PageFreePercent: Percentage of free space available on the page (0-100) IsAllocated: String value ('True' or 'False') indicating if the page is allocated IsMixedPage: String value ('True' or 'False') indicating if this is a mixed page allocation &nbsp;"
  },
  {
    "name": "Get-DbaDbPartitionFunction",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "partition"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbPartitionFunction",
    "popularityRank": 470,
    "synopsis": "Retrieves partition function definitions and metadata from SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbPartitionFunction View Source Klaas Vandenberghe (@PowerDbaKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves partition function definitions and metadata from SQL Server databases. 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. Syntax Get-DbaDbPartitionFunction [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-PartitionFunction] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database partition functions PS C:\\> Get-DbaDbPartitionFunction -SqlInstance sql2016 Example 2: Gets the partition functions for the db1 database PS C:\\> Get-DbaDbPartitionFunction -SqlInstance Server1 -Database db1 Example 3: Gets the partition functions for all databases except db1 PS C:\\> Get-DbaDbPartitionFunction -SqlInstance Server1 -ExcludeDatabase db1 Example 4: Gets the partition functions for the databases on Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbPartitionFunction Example 5: Gets the partition function partFun01 for the TestDB on localhost PS C:\\> Get-DbaDbPartitionFunction -SqlInstance localhost -Database TestDB -PartitionFunction partFun01 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for partition functions. Accepts multiple database names as an array. Use this when you need to examine partition functions in specific databases rather than scanning all accessible databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to skip when searching for partition functions. Accepts multiple database names as an array. Use this to avoid scanning system databases or databases where you know partition functions don't exist, improving performance on instances with many databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PartitionFunction Specifies which partition functions to retrieve by name. Accepts multiple function names as an array and supports wildcards. Use this when you need details about specific partition functions rather than retrieving all partition functions from the target databases. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.PartitionFunction Returns one PartitionFunction object for each partition function found in the target databases. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the partition function CreateDate: DateTime when the partition function was created Name: Name of the partition function NumberOfPartitions: The number of partitions defined by this function Additional properties available (from SMO PartitionFunction object): ParameterType: The data type used as the partitioning column data type Urn: Uniform Resource Name identifying the object within the SQL Server hierarchy Parent: Reference to the parent Database object All properties from the base SMO object are accessible via Select-Object * even though only default properties are displayed without it. &nbsp;"
  },
  {
    "name": "Get-DbaDbPartitionScheme",
    "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's 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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "partition"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbPartitionScheme",
    "popularityRank": 541,
    "synopsis": "Retrieves partition schemes from SQL Server databases for table partitioning management.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbPartitionScheme View Source Klaas Vandenberghe (@PowerDbaKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves partition schemes from SQL Server databases for table partitioning management. 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's 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. Syntax Get-DbaDbPartitionScheme [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-PartitionScheme] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database partition schemes PS C:\\> Get-DbaDbPartitionScheme -SqlInstance sql2016 Example 2: Gets the partition schemes for the db1 database PS C:\\> Get-DbaDbPartitionScheme -SqlInstance Server1 -Database db1 Example 3: Gets the partition schemes for all databases except db1 PS C:\\> Get-DbaDbPartitionScheme -SqlInstance Server1 -ExcludeDatabase db1 Example 4: Gets the partition schemes for the databases on Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbPartitionScheme Example 5: Gets the partition scheme partSch01 for the TestDB on localhost PS C:\\> Get-DbaDbPartitionScheme -SqlInstance localhost -Database TestDB -PartitionScheme partSch01 Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for partition schemes. Accepts multiple database names. Use this when you need to check partition schemes in specific databases rather than all accessible databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip when scanning for partition schemes. Accepts multiple database names. Use this to exclude system databases or specific databases you don't want to check, such as development or staging databases during production audits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PartitionScheme Specifies which partition schemes to retrieve by name. Accepts multiple scheme names for targeted retrieval. Use 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. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.PartitionScheme Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database containing this partition scheme Name: The name of the partition scheme PartitionFunction: The name of the partition function used by this scheme Additional properties available (from SMO PartitionScheme object): PartitionFunctionName: The partition function name (same as PartitionFunction) Urn: The Uniform Resource Name of the partition scheme object State: The current state of the SMO object (Existing, Creating, Pending, Dropping, etc.) Parent: The database object that contains this partition scheme All properties from the base SMO PartitionScheme object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbQueryStoreOption",
    "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.",
    "category": "Utilities",
    "tags": [
      "querystore"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbQueryStoreOption",
    "popularityRank": 402,
    "synopsis": "Retrieves Query Store configuration settings from databases across SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbQueryStoreOption View Source Enrico van de Laar (@evdlaar) , Klaas Vandenberghe (@PowerDBAKlaas) , Tracy Boggiano (@TracyBoggiano) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Query Store configuration settings from databases across SQL Server instances. 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. Syntax Get-DbaDbQueryStoreOption [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns Query Store configuration settings for every database on the ServerA\\sql instance PS C:\\> Get-DbaDbQueryStoreOption -SqlInstance ServerA\\sql Example 2: Returns the Query Store configuration for all databases on ServerA\\sql where the Query Store feature is in... PS C:\\> Get-DbaDbQueryStoreOption -SqlInstance ServerA\\sql | Where-Object {$_.ActualState -eq \"ReadWrite\"} Returns the Query Store configuration for all databases on ServerA\\sql where the Query Store feature is in Read/Write mode. Example 3: Returns Query Store configuration settings for every database on the ServerA\\sql instance inside a table... PS C:\\> Get-DbaDbQueryStoreOption -SqlInstance localhost | format-table -AutoSize -Wrap Returns Query Store configuration settings for every database on the ServerA\\sql instance inside a table format. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which user databases to retrieve Query Store configuration from. Accepts database names, wildcards, or arrays for multiple databases. Use this when you need to audit Query Store settings for specific databases rather than scanning your entire instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from Query Store configuration retrieval. System databases (master, tempdb, model) are automatically excluded. Useful for skipping databases that you know don't need Query Store monitoring or have restricted access permissions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.QueryStoreOptions Returns 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 version. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database ActualState: Current Query Store state (ReadWrite, ReadOnly, or Off) DataFlushIntervalInSeconds: Interval in seconds for flushing data to storage StatisticsCollectionIntervalInMinutes: Interval in minutes for statistics collection MaxStorageSizeInMB: Maximum storage size allocated for Query Store (in megabytes) CurrentStorageSizeInMB: Current storage size being used by Query Store (in megabytes) QueryCaptureMode: Query capture mode (All, Auto, None, or Custom) SizeBasedCleanupMode: Cleanup mode when max storage is exceeded (Off, Auto) StaleQueryThresholdInDays: Number of days after which a query is considered stale for cleanup Additional properties for SQL Server 2017 (v14) and later: MaxPlansPerQuery: Maximum number of plans tracked per query WaitStatsCaptureMode: Wait statistics capture mode (Off, On) Additional properties for SQL Server 2019 (v15) and later: CustomCapturePolicyExecutionCount: Custom capture policy execution count threshold CustomCapturePolicyTotalCompileCPUTimeMS: Custom capture policy compile CPU time threshold in milliseconds CustomCapturePolicyTotalExecutionCPUTimeMS: Custom capture policy execution CPU time threshold in milliseconds CustomCapturePolicyStaleThresholdHours: Custom capture policy stale threshold in hours All 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 varies based on the SQL Server version of the target instance. &nbsp;"
  },
  {
    "name": "Get-DbaDbRecoveryModel",
    "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.",
    "category": "Backup & Restore",
    "tags": [
      "recovery",
      "recoverymodel",
      "backup"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbRecoveryModel",
    "popularityRank": 239,
    "synopsis": "Retrieves database recovery model settings and backup history information from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbRecoveryModel View Source Viorel Ciucu (@viorelciucu), cviorel.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database recovery model settings and backup history information from SQL Server instances. 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. Syntax Get-DbaDbRecoveryModel [-SqlInstance] [[-SqlCredential] ] [[-RecoveryModel] ] [[-Database] ] [[-ExcludeDatabase] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all databases on SQL Server instance sql2014 having RecoveryModel set to BulkLogged PS C:\\> Get-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Verbose Example 2: Gets recovery model information for TestDB PS C:\\> Get-DbaDbRecoveryModel -SqlInstance sql2014 -Database TestDB Gets recovery model information for TestDB. If TestDB does not exist on the instance nothing is returned. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RecoveryModel Filters results to show only databases using the specified recovery model (Simple, Full, or BulkLogged). Use this to identify databases with incorrect recovery models for your backup strategy or to audit compliance with recovery model policies. Details about the recovery models can be found here: https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/recovery-models-sql-server | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Simple,Full,BulkLogged | -Database Specifies which databases to retrieve recovery model information for. Accepts database names, wildcards, or arrays. Use this when you need to check recovery models for specific databases rather than all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the recovery model check. Accepts database names, wildcards, or arrays. Useful for skipping system databases or databases you don't manage when reviewing recovery model compliance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Database Returns one SMO Database object for each database on the specified instance(s), with the following properties displayed: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Database name Status: Current database status (EmergencyMode, Normal, Offline, Recovering, RecoveryPending, Restoring, Standby, Suspect) IsAccessible: Boolean indicating if the database is currently accessible RecoveryModel: Database recovery model (Full, Simple, or BulkLogged) LastFullBackup: DateTime of the most recent full backup LastDiffBackup: DateTime of the most recent differential backup LastLogBackup: DateTime of the most recent transaction log backup Note: 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 Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbRestoreHistory",
    "description": "Queries the MSDB database's 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.",
    "category": "Backup & Restore",
    "tags": [
      "disasterrecovery",
      "backup",
      "restore"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbRestoreHistory",
    "popularityRank": 218,
    "synopsis": "Retrieves database restore history from MSDB for compliance reporting and recovery analysis.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbRestoreHistory View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database restore history from MSDB for compliance reporting and recovery analysis. Description Queries the MSDB database's 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. Use 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. This eliminates the need to manually query MSDB system tables or write complex SQL joins to gather restore history information across multiple instances. Thanks 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. Syntax Get-DbaDbRestoreHistory [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Since] ] [-Force] [-Last] [[-RestoreType] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns server name, database, username, restore type, date for all restored databases on sql2016 PS C:\\> Get-DbaDbRestoreHistory -SqlInstance sql2016 Example 2: Returns restore information only for databases db1 and db2 on sql2016 since July 1, 2016 at 10:47 AM PS C:\\> Get-DbaDbRestoreHistory -SqlInstance sql2016 -Database db1, db2 -Since '2016-07-01 10:47:00' Example 3: Returns restore information for all databases except db1 on sql2014 and sql2016 PS C:\\> Get-DbaDbRestoreHistory -SqlInstance sql2014, sql2016 -Exclude db1 Example 4: Returns database restore information for AdventureWorks2014 and pubs database on sql2014, connects using SQL... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Get-DbaDbRestoreHistory -SqlInstance sql2014 -Database AdventureWorks2014, pubs -SqlCredential $cred | Format-Table Returns database restore information for AdventureWorks2014 and pubs database on sql2014, connects using SQL Authentication via sqladmin account. Formats the data as a table. Example 5: Returns database restore information for every database on every server listed in the Central Management... PS C:\\> Get-DbaRegServer -SqlInstance sql2016 | Get-DbaDbRestoreHistory Returns database restore information for every database on every server listed in the Central Management Server on sql2016. Example 6: Returns log restore information for every database on the sql2016 instance PS C:\\> Get-DbaDbRestoreHistory -SqlInstance sql2016 -RestoreType Log Required Parameters -SqlInstance Specifies the SQL Server instance(s) to operate on. Requires SQL Server 2005 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Filters restore history to specific database(s). Accepts wildcards for pattern matching. Use this when investigating restore activity for particular databases rather than reviewing all restore operations on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific database(s) from the restore history results. Accepts wildcards for pattern matching. Useful when you need to filter out system databases or other databases that aren't relevant to your investigation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Since Filters restore history to operations that occurred on or after the specified date and time. Use this when investigating recent restore activity or limiting results to a specific time period for compliance reporting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force This parameter is deprecated and no longer used. Previously controlled whether to return all available columns, but this functionality has been removed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Last Returns only the most recent restore operation for each database, filtering out all earlier restore history. Use this when you need to quickly identify when each database was last restored without seeing the full restore timeline. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -RestoreType Filters results to a specific type of restore operation: Database, File, Filegroup, Differential, Log, Verifyonly, or Revert. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Data.DataRow Returns one object per restore operation found in MSDB. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database that was restored Username: Login name of the user who performed the restore RestoreType: Type of restore operation (Database, File, Filegroup, Differential, Log, Verifyonly, or Revert) Date: Timestamp when the restore operation completed From: Comma-separated list of physical device names where the backup source(s) are located To: Comma-separated list of physical file paths where the database files were restored Additional properties available (from MSDB backupset/restorehistory tables): first_lsn: First log sequence number in the backup last_lsn: Last log sequence number in the backup checkpoint_lsn: Checkpoint log sequence number database_backup_lsn: Log sequence number of database backup BackupStartDate: Timestamp when the backup operation started BackupFinishDate: Timestamp when the backup operation completed StopAt: The point-in-time stop value specified during the restore operation (NULL if not specified) LastRestorePoint: The effective point in time the database was restored to (StopAt if specified, otherwise BackupStartDate) All properties from the underlying DataRow object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbRole",
    "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.",
    "category": "Utilities",
    "tags": [
      "role",
      "user"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbRole",
    "popularityRank": 119,
    "synopsis": "Retrieves database roles from SQL Server instances for security auditing and permission analysis.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbRole View Source Ben Miller (@DBAduck) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database roles from SQL Server instances for security auditing and permission analysis. 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. Syntax Get-DbaDbRole [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Role] ] [[-ExcludeRole] ] [-ExcludeFixedRole] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all database roles in all databases on the local default SQL Server instance PS C:\\> Get-DbaDbRole -SqlInstance localhost Example 2: Returns all roles of all database(s) on the local and sql2016 SQL Server instances PS C:\\> Get-DbaDbRole -SqlInstance localhost, sql2016 Example 3: Returns roles of all database(s) for every server in C:\\servers.txt PS C:\\> $servers = Get-Content C:\\servers.txt PS C:\\> $servers | Get-DbaDbRole Example 4: Returns roles of the database msdb on localhost PS C:\\> Get-DbaDbRole -SqlInstance localhost -Database msdb Example 5: Returns all non-fixed roles in the msdb database on localhost PS C:\\> Get-DbaDbRole -SqlInstance localhost -Database msdb -ExcludeFixedRole Example 6: Returns the db_owner role in the msdb database on localhost PS C:\\> Get-DbaDbRole -SqlInstance localhost -Database msdb -Role 'db_owner' Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to examine for role information. Accepts wildcards for pattern matching. Use this when you need to audit roles in specific databases rather than scanning all databases on the instance. Particularly useful for focusing on user databases while skipping system databases, or for compliance audits of specific applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specified databases from role enumeration. Accepts wildcards for pattern matching. Use this to skip databases you don't need to audit, such as development databases during production security reviews. Commonly used to exclude system databases or databases with known standard configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Role Specifies which database roles to retrieve by name. Accepts wildcards for pattern matching. Use this when investigating specific roles across databases, such as checking for custom application roles or finding all instances of a particular role name. Particularly useful for security audits focusing on elevated permissions like 'db_owner' or custom admin roles. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeRole Excludes specified roles from the results by name. Accepts wildcards for pattern matching. Use this to filter out roles you're not interested in, such as excluding standard fixed roles when focusing on custom application roles. Helpful for reducing noise in reports when you want to see only non-standard or suspicious role configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeFixedRole Excludes all built-in fixed database roles from the results, showing only custom user-defined roles. Use this when auditing custom role implementations or when you need to focus on application-specific security configurations. Fixed roles like db_owner, db_datareader, and db_datawriter are filtered out, along with the public role. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database objects from Get-DbaDatabase through the pipeline for role enumeration. Use this when you need to chain database selection criteria with role analysis, such as filtering databases by size, compatibility level, or other properties first. Allows for more complex filtering scenarios than the basic Database parameter provides. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Role Returns one Role object per database role found. The output is filtered based on the -Role, -ExcludeRole, and -ExcludeFixedRole parameters. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name Database: The name of the database containing the role Name: The name of the database role IsFixedRole: Boolean indicating if this is a built-in fixed database role (db_owner, db_datareader, etc.) or a custom user-defined role Additional properties available (from SMO Role object): Owner: The principal that owns the role CreateDate: DateTime when the role was created DateLastModified: DateTime when the role was last modified ID: The role's unique object ID within the database Urn: The Urn identifier for the role All properties from the base SMO Role object are accessible via Select-Object * even though only default properties are displayed. &nbsp;"
  },
  {
    "name": "Get-DbaDbRoleMember",
    "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.",
    "category": "Utilities",
    "tags": [
      "role",
      "user"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbRoleMember",
    "popularityRank": 94,
    "synopsis": "Retrieves all users and nested roles that are members of database roles across SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbRoleMember View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves all users and nested roles that are members of database roles across SQL Server instances 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. Syntax Get-DbaDbRoleMember [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Role] ] [[-ExcludeRole] ] [-ExcludeFixedRole] [-IncludeSystemUser] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all members of all database roles on the local default SQL Server instance PS C:\\> Get-DbaDbRoleMember -SqlInstance localhost Example 2: Returns all members of all database roles on the local and sql2016 SQL Server instances PS C:\\> Get-DbaDbRoleMember -SqlInstance localhost, sql2016 Example 3: Returns all members of all database roles for every server in C:\\servers.txt PS C:\\> $servers = Get-Content C:\\servers.txt PS C:\\> $servers | Get-DbaDbRoleMember Example 4: Returns non-system members of all roles in the msdb database on localhost PS C:\\> Get-DbaDbRoleMember -SqlInstance localhost -Database msdb Example 5: Returns all members of non-fixed roles in the msdb database on localhost PS C:\\> Get-DbaDbRoleMember -SqlInstance localhost -Database msdb -IncludeSystemUser -ExcludeFixedRole Example 6: Returns all members of the db_owner role in the msdb database on localhost PS C:\\> Get-DbaDbRoleMember -SqlInstance localhost -Database msdb -Role 'db_owner' Example 7: Returns all members of the db_owner role in the msdb database on localhost PS C:\\> $roles = Get-DbaDbRole -SqlInstance localhost -Database msdb -Role 'db_owner' PS C:\\> $roles | Get-DbaDbRoleMember Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for role membership. Accepts wildcards for pattern matching. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from role membership analysis. Supports wildcards for pattern matching. Use this to skip system databases like tempdb or databases under maintenance when performing enterprise-wide role audits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Role Limits the analysis to specific database roles by name. Accepts wildcards for pattern matching. Use this when investigating membership of particular roles like 'db_owner', 'db_datareader', or custom application roles during security reviews or troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeRole Excludes specific database roles from the membership analysis. Supports wildcards for pattern matching. Use this to filter out roles you're not interested in, such as excluding 'public' role or application-specific roles during focused security audits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeFixedRole Excludes members of SQL Server's built-in database roles like db_owner, db_datareader, db_datawriter, etc. Use this when you want to focus only on custom application roles and their memberships, filtering out the standard SQL Server role assignments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSystemUser Includes SQL Server system users like 'dbo', 'guest', 'sys', and 'INFORMATION_SCHEMA' in the results. Use this for comprehensive security audits or when troubleshooting system-level permission issues. Normally these accounts are excluded to focus on business user accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts piped objects from Get-DbaDbRole, Get-DbaDatabase, or SQL Server instances for processing. Use this to chain commands together, such as first filtering roles with Get-DbaDbRole then analyzing their membership, or to process multiple database objects efficiently. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per member (user or nested role) found in each database role. Properties: ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName Database: The database name containing the role Role: The name of the database role UserName: The name of the user account (populated when the member is a user; $null when the member is a nested role) Login: The SQL Server login associated with the user (populated for user members; $null for nested roles) MemberRole: The name of the nested role (populated when the member is another role; $null when the member is a user) SmoRole: The SMO DatabaseRole object representing the parent role SmoUser: The SMO User object (populated for user members; $null for nested role members) SmoMemberRole: The SMO DatabaseRole object for nested role members ($null for user members) Use Select-Object to filter properties if you only need specific information, or access SMO objects directly for advanced operations. &nbsp;"
  },
  {
    "name": "Get-DbaDbSchema",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "schema"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbSchema",
    "popularityRank": 117,
    "synopsis": "Retrieves database schema objects from SQL Server instances for inventory, security auditing, and management tasks",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbSchema View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database schema objects from SQL Server instances for inventory, security auditing, and management tasks 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. Syntax Get-DbaDbSchema [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Schema] ] [[-SchemaOwner] ] [-IncludeSystemDatabases] [-IncludeSystemSchemas] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Gets all non-system database schemas from all user databases on the localhost instance PS C:\\> Get-DbaDbSchema -SqlInstance localhost Gets all non-system database schemas from all user databases on the localhost instance. Note: the dbo schema is a system schema and won't be included in the output from this example. To include the dbo schema specify -IncludeSystemSchemas Example 2: Returns the dbo schema from the databases on the localhost instance PS C:\\> Get-DbaDbSchema -SqlInstance localhost -Schema dbo -IncludeSystemSchemas Example 3: Gets all database schemas from all databases on the localhost instance PS C:\\> Get-DbaDbSchema -SqlInstance localhost -IncludeSystemDatabases -IncludeSystemSchemas Example 4: Finds and returns the TestSchema schema from the localhost instance PS C:\\> Get-DbaDbSchema -SqlInstance localhost -Schema TestSchema Example 5: Finds and returns the schemas owned by DBUser1 from the localhost instance PS C:\\> Get-DbaDbSchema -SqlInstance localhost -SchemaOwner DBUser1 Example 6: Finds and returns the schemas owned by DBUser1 in the TestDB database from the localhost instance PS C:\\> Get-DbaDbSchema -SqlInstance localhost -Database TestDB -SchemaOwner DBUser1 Example 7: Finds the TestSchema in the TestDB on the localhost instance and then changes the schema owner to DBUser2 PS C:\\> $schema = Get-DbaDbSchema -SqlInstance localhost -Database TestDB -Schema TestSchema PS C:\\> $schema.Owner = DBUser2 PS C:\\> $schema.Alter() Example 8: Finds the TestSchema in the TestDB on the localhost instance and then drops it PS C:\\> $schema = Get-DbaDbSchema -SqlInstance localhost -Database TestDB -Schema TestSchema PS C:\\> $schema.Drop() Finds 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. Example 9: Finds the TestSchema in the TestDB which is passed via pipeline into the Get-DbaDbSchema command PS C:\\> $db = Get-DbaDatabase -SqlInstance localhost -Database TestDB PS C:\\> $schema = $db | Get-DbaDbSchema -Schema TestSchema Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to retrieve schemas from. Accepts wildcards for pattern matching. Use this when you need to focus on specific databases instead of all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Filters results to include only schemas with the specified names. Accepts multiple schema names. Use this when you need to check specific schemas like custom application schemas or verify particular schema configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SchemaOwner Filters results to schemas owned by the specified database users or roles. Accepts multiple owner names. Use this for security audits to identify all schemas owned by specific users, or when troubleshooting schema ownership issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSystemDatabases Includes system databases (master, model, msdb, tempdb) in the schema retrieval. Use this when you need to audit or document schema configurations across all databases including system databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSystemSchemas Includes built-in system schemas like dbo, sys, guest, and INFORMATION_SCHEMA in the results. Use this when you need complete schema inventory including system schemas, or when specifically working with dbo schema objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database objects from Get-DbaDatabase via pipeline input for processing. Use this to chain database operations or when you already have database objects and want to retrieve their schemas efficiently. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Schema Returns one Schema object per database schema found, filtered based on the -Schema, -SchemaOwner, and -IncludeSystemSchemas parameters. Returns multiple objects when querying multiple databases. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the schema IsSystemObject: Boolean indicating if this is a built-in system schema (dbo, sys, guest, INFORMATION_SCHEMA) or a custom user-defined schema Additional properties available (from SMO Schema object): DatabaseName: The name of the database containing the schema DatabaseId: The unique identifier (ID) of the database Owner: The principal that owns the schema CreateDate: DateTime when the schema was created DateLastModified: DateTime when the schema was last modified ID: The schema's unique object ID within the database Urn: The Urn identifier for the schema All 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 Alter() and Drop() as shown in the examples. &nbsp;"
  },
  {
    "name": "Get-DbaDbSequence",
    "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.",
    "category": "Utilities",
    "tags": [
      "data",
      "sequence",
      "table"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbSequence",
    "popularityRank": 553,
    "synopsis": "Retrieves SQL Server sequence objects and their configuration details from specified databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbSequence View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server sequence objects and their configuration details from specified databases. 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. Syntax Get-DbaDbSequence [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Sequence] ] [[-Schema] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Finds the sequence TestSequence in the TestDB database on the sqldev01 instance PS C:\\> Get-DbaDbSequence -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence Example 2: Using a pipeline this command finds the sequence named TestSchema.TestSequence in the TestDB database on the... PS C:\\> Get-DbaDatabase -SqlInstance sqldev01 -Database TestDB | Get-DbaDbSequence -Sequence TestSequence -Schema TestSchema Using a pipeline this command finds the sequence named TestSchema.TestSequence in the TestDB database on the sqldev01 instance. Example 3: Finds all the sequences on the localhost instance PS C:\\> Get-DbaDbSequence -SqlInstance localhost Example 4: Finds all the sequences in the db database on the localhost instance PS C:\\> Get-DbaDbSequence -SqlInstance localhost -Database db Example 5: Finds all the sequences named seq on the localhost instance PS C:\\> Get-DbaDbSequence -SqlInstance localhost -Sequence seq Example 6: Finds all the sequences in the sch schema on the localhost instance PS C:\\> Get-DbaDbSequence -SqlInstance localhost -Schema sch Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for sequence objects. Accepts wildcards and multiple database names. Use this when you need to limit the search to specific databases instead of scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Sequence Filters results to sequences with specific names. Accepts multiple sequence names and supports exact name matching. Use this when you need to find specific sequences across databases rather than retrieving all sequences. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -Schema Filters results to sequences within specific schemas. Accepts multiple schema names for searching across different schemas. Use this when you need to examine sequences in particular schemas, such as application-specific schemas or custom organizational structures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase pipeline input, allowing you to target specific databases already retrieved. Use this approach when you need to chain commands or work with databases that meet specific criteria from previous filtering operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Sequence Returns 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. Default display properties (via Select-DefaultView): ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database containing the sequence Schema: The schema where the sequence is created Name: The name of the sequence object DataType: The data type of values the sequence will generate (e.g., bigint, int, tinyint, smallint) StartValue: The initial value the sequence will return on first use (the current starting point) IncrementValue: The amount the sequence will increase (or decrease if negative) with each NEXT VALUE FOR call Additional properties available (from SMO Sequence object): CurrentValue: The current value that will be returned by the next NEXT VALUE FOR call MinValue: The minimum value the sequence can generate MaxValue: The maximum value the sequence can generate IsCycleEnabled: Boolean indicating whether the sequence will cycle from MaxValue back to MinValue CacheSize: The number of sequence values pre-allocated in memory (0 means no cache) SequenceCacheType: The cache behavior setting (DefaultCache, NoCache, or CacheWithSize) Parent: Reference to the parent Database SMO object Urn: The Uniform Resource Name (URN) identifying the sequence in the SMO object hierarchy State: The state of the SMO object (Existing, Creating, Altering, Dropping, etc.) All properties from the base SMO Sequence object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbServiceBrokerQueue",
    "description": "Gets database Sservice broker queue",
    "category": "Performance",
    "tags": [
      "database",
      "servicebroker",
      "queue"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbServiceBrokerQueue",
    "popularityRank": 647,
    "synopsis": "Gets database service broker queues",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbServiceBrokerQueue View Source Ant Green (@ant_green) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Gets database service broker queues Description Gets database Sservice broker queue Syntax Get-DbaDbServiceBrokerQueue [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-ExcludeSystemQueue] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database service broker queues PS C:\\> Get-DbaDbServiceBrokerQueue -SqlInstance sql2016 Example 2: Gets the service broker queues for the db1 database PS C:\\> Get-DbaDbServiceBrokerQueue -SqlInstance Server1 -Database db1 Example 3: Gets the service broker queues for all databases except db1 PS C:\\> Get-DbaDbServiceBrokerQueue -SqlInstance Server1 -ExcludeDatabase db1 Example 4: Gets the service broker queues for all databases that are not system objects PS C:\\> Get-DbaDbServiceBrokerQueue -SqlInstance Server1 -ExcludeSystemQueue Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to retrieve Service Broker queues from. Accepts wildcards for pattern matching. Use this when you need to focus on specific databases instead of scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to exclude from the Service Broker queue retrieval. Accepts wildcards for pattern matching. Useful when you want to scan most databases but skip specific ones like test or development databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemQueue Excludes system-created Service Broker queues from the results, showing only user-created queues. Use this to focus on application-specific queues and filter out SQL Server's internal messaging queues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.ServiceBrokerQueue Returns one ServiceBrokerQueue object per queue found across the specified databases. System queues are included by default but can be excluded using the -ExcludeSystemQueue parameter. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the queue Schema: The schema containing the queue QueueID: The unique object ID of the queue within the database CreateDate: DateTime when the queue was created DateLastModified: DateTime when the queue was last modified Name: The name of the Service Broker queue ProcedureName: Name of the stored procedure that activates the queue (if configured) ProcedureSchema: Schema containing the activation procedure Additional properties available (from SMO ServiceBrokerQueue object): IsSystemObject: Boolean indicating if this is a system queue created by SQL Server IsActivationEnabled: Boolean indicating if queue activation is enabled MaxReaders: Maximum number of simultaneous queue readers State: Queue state (Available, Unavailable, etc.) Owner: The principal that owns the queue Urn: The Urn identifier for the queue All properties from the base SMO ServiceBrokerQueue object are accessible via Select-Object * even though only default properties are displayed. &nbsp;"
  },
  {
    "name": "Get-DbaDbServiceBrokerService",
    "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.",
    "category": "Server Management",
    "tags": [
      "service",
      "servicebroker"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbServiceBrokerService",
    "popularityRank": 494,
    "synopsis": "Retrieves Service Broker services from SQL Server databases for auditing and troubleshooting messaging configurations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbServiceBrokerService View Source Ant Green (@ant_green) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Service Broker services from SQL Server databases for auditing and troubleshooting messaging configurations 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. Syntax Get-DbaDbServiceBrokerService [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-ExcludeSystemService] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database service broker queues PS C:\\> Get-DbaDbServiceBrokerService -SqlInstance sql2016 Example 2: Gets the service broker queues for the db1 database PS C:\\> Get-DbaDbServiceBrokerService -SqlInstance Server1 -Database db1 Example 3: Gets the service broker queues for all databases except db1 PS C:\\> Get-DbaDbServiceBrokerService -SqlInstance Server1 -ExcludeDatabase db1 Example 4: Gets the service broker queues for all databases that are not system objects PS C:\\> Get-DbaDbServiceBrokerService -SqlInstance Server1 -ExcludeSystemService Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to query for Service Broker services. Accepts multiple database names. Use this when you need to limit the search to specific databases instead of scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the Service Broker service search. Accepts multiple database names. Useful when you want to audit most databases but skip known databases without Service Broker configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemService Excludes system-created Service Broker services from the results, showing only user-defined services. Use this to focus on custom messaging implementations and avoid clutter from built-in SQL Server services. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.ServiceBrokerService Returns 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 parameter. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the service Owner: The principal that owns the Service Broker service ServiceID: The unique object ID of the service within the database Name: The name of the Service Broker service QueueSchema: The schema containing the associated queue QueueName: The name of the queue associated with this service Additional properties available (from SMO ServiceBrokerService object): IsSystemObject: Boolean indicating if this is a system service created by SQL Server CreateDate: DateTime when the service was created DateLastModified: DateTime when the service was last modified State: Service state (Existing, Creating, Pending, etc.) Urn: The Urn identifier for the service All properties from the base SMO ServiceBrokerService object are accessible via Select-Object * even though only default properties are displayed. &nbsp;"
  },
  {
    "name": "Get-DbaDbSharePoint",
    "description": "Discovers and returns database objects for all databases that are part of a SharePoint farm by querying the SharePoint Configuration database's 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's 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.",
    "category": "Utilities",
    "tags": [
      "sharepoint"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbSharePoint",
    "popularityRank": 481,
    "synopsis": "Identifies all databases belonging to a SharePoint farm by querying the SharePoint Configuration database.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbSharePoint View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies all databases belonging to a SharePoint farm by querying the SharePoint Configuration database. Description Discovers and returns database objects for all databases that are part of a SharePoint farm by querying the SharePoint Configuration database's 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. The function queries the SharePoint Configuration database to find registered SharePoint databases using SharePoint's 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. Syntax Get-DbaDbSharePoint [[-SqlInstance] ] [[-SqlCredential] ] [[-ConfigDatabase] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns databases that are part of a SharePoint Farm, as found in SharePoint_Config on sqlcluster PS C:\\> Get-DbaDbSharePoint -SqlInstance sqlcluster Example 2: Returns databases that are part of a SharePoint Farm, as found in SharePoint_Config_2016 on sqlcluster PS C:\\> Get-DbaDatabase -SqlInstance sqlcluster -Database SharePoint_Config_2016 | Get-DbaDbSharePoint Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ConfigDatabase Specifies the name of the SharePoint Configuration database to query for farm database information. Defaults to SharePoint_Config. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | SharePoint_Config | -InputObject Accepts database objects from Get-DbaDatabase to directly analyze specific SharePoint Configuration databases. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Database Returns 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 including content databases, service application databases, and other associated databases. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Database name Status: Current database status (EmergencyMode, Normal, Offline, Recovering, RecoveryPending, Restoring, Standby, Suspect) IsAccessible: Boolean indicating if the database is currently accessible RecoveryModel: Database recovery model (Full, Simple, BulkLogged) LogReuseWaitStatus: Status of transaction log reuse (LogSwitch, ChkptBkup, ActiveBkup, ActiveTran, etc.) Size: Database size in megabytes (MB) Compatibility: Database compatibility level (numeric value representing SQL Server version) Collation: Database collation setting Owner: Database owner login name Encrypted: Boolean indicating if Transparent Data Encryption (TDE) is enabled LastFullBackup: DateTime of the most recent full backup LastDiffBackup: DateTime of the most recent differential backup LastLogBackup: DateTime of the most recent transaction log backup Additional properties available (from SMO Database object): IsCdcEnabled: Boolean indicating if Change Data Capture is enabled (SQL Server 2008+) And all other standard SMO Database properties (use Select-Object * to see all) All properties from the base SMO Database object are accessible via Select-Object even though only default properties are displayed without using the -Property parameter. &nbsp;"
  },
  {
    "name": "Get-DbaDbSnapshot",
    "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's 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.",
    "category": "Utilities",
    "tags": [
      "snapshot"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbSnapshot",
    "popularityRank": 289,
    "synopsis": "Retrieves database snapshots with their source databases, creation times, and disk usage",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbSnapshot View Source Simone Bizzotto (@niphlod) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database snapshots with their source databases, creation times, and disk usage 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's 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. Syntax Get-DbaDbSnapshot [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Snapshot] ] [[-ExcludeSnapshot] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a custom object displaying Server, Database, DatabaseCreated, SnapshotOf, SizeMB, DatabaseCreated PS C:\\> Get-DbaDbSnapshot -SqlInstance sqlserver2014a Example 2: Returns information for database snapshots having HR and Accounting as base dbs PS C:\\> Get-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting Example 3: Returns information for database snapshots HR_snapshot and Accounting_snapshot PS C:\\> Get-DbaDbSnapshot -SqlInstance sqlserver2014a -Snapshot HR_snapshot, Accounting_snapshot Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 'HR' or 'Accounting'. Accepts multiple database names and is useful for focusing on snapshots from databases you're actively managing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes snapshots created from specific base databases from the results. Use this to filter out snapshots from databases you don't want to see, such as system databases or databases managed by other teams. Helpful when you want a comprehensive view but need to omit certain source databases from the output. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Snapshot Returns information for specific database snapshots by their snapshot names. Use this when you need details about particular snapshots like 'HR_BeforeUpdate_20240101' or 'Production_Backup_Snapshot'. Accepts multiple snapshot names and is ideal for checking the status or disk usage of known snapshots. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSnapshot Excludes specific database snapshots from the results by their snapshot names. Use this to filter out snapshots you don't want to see in the output, such as automated system snapshots or snapshots from other environments. Helpful for focusing on production snapshots while excluding development or test snapshots. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Database Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the database snapshot SnapshotOf: The name of the base database from which this snapshot was created (alias for DatabaseSnapshotBaseName) CreateDate: DateTime when the snapshot was created DiskUsage: The amount of disk space consumed by the snapshot (formatted as appropriate unit: KB, MB, GB, etc.) Additional properties available (from SMO Database object): DatabaseSnapshotBaseName: The name of the source database IsDatabaseSnapshot: Boolean indicating if the database is a snapshot SnapshotIsolationState: Snapshot isolation setting DatabaseGuid: Unique identifier for the database Owner: Database owner login name Compatibility: Database compatibility level All properties from the base SMO Database object are accessible via Select-Object * even though only default properties are displayed without using the -Property parameter. &nbsp;"
  },
  {
    "name": "Get-DbaDbSpace",
    "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's DMV scripts (http://www.sqlskills.com/blogs/glenn/category/dmv-queries/)",
    "category": "Database Operations",
    "tags": [
      "database",
      "space"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbSpace",
    "popularityRank": 67,
    "synopsis": "Retrieves detailed space usage metrics for all database files including used space, free space, and growth settings.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbSpace View Source Michael Fal (@Mike_Fal), mikefal.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed space usage metrics for all database files including used space, free space, and growth settings. 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. File free space script borrowed and modified from Glenn Berry's DMV scripts (http://www.sqlskills.com/blogs/glenn/category/dmv-queries/) Syntax Get-DbaDbSpace [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-IncludeSystemDBs] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all user database files and free space information for the localhost PS C:\\> Get-DbaDbSpace -SqlInstance localhost Example 2: Returns all user database files and free space information for the local host PS C:\\> Get-DbaDbSpace -SqlInstance localhost | Where-Object {$_.PercentUsed -gt 80} Returns 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%. Example 3: Returns all user database files and free space information for the localhost and localhost\\namedinstance SQL... PS C:\\> 'localhost','localhost\\namedinstance' | Get-DbaDbSpace Returns all user database files and free space information for the localhost and localhost\\namedinstance SQL Server instances. Processes data via the pipeline. Example 4: Returns database files and free space information for the db1 and db2 on localhost where there is only 1MB... PS C:\\> Get-DbaDbSpace -SqlInstance localhost -Database db1, db2 | Where-Object { $_.SpaceUntilMaxSize.Megabyte -lt 1 } Returns 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 Example 5: Returns database files and free space information for the db1 and db2 on localhost where there is only 1GB... PS C:\\> Get-DbaDbSpace -SqlInstance localhost -Database db1, db2 | Where-Object { $_.SpaceUntilMaxSize.Gigabyte -lt 1 } Returns 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 Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Limits space analysis to specific databases by name. Accepts multiple values and supports wildcards. Use this when monitoring space usage for critical databases or investigating specific capacity issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from space analysis by name. Accepts multiple values and supports wildcards. Useful for skipping test databases, staging environments, or databases with known space issues when doing server-wide capacity reviews. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSystemDBs This parameter is deprecated and will cause the function to stop with an error message. To include system databases in space analysis, pipe results from Get-DbaDatabase with the -IncludeSystem parameter instead. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database objects piped from Get-DbaDatabase for space analysis. This allows for advanced filtering scenarios, such as analyzing only databases with specific properties like recovery models or creation dates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database file (data and log files). Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the file FileName: The logical name of the database file FileGroup: The name of the filegroup the file belongs to (null for log files) PhysicalName: The full physical file path on disk FileType: The type of file (ROWS for data files, LOG for transaction log files) UsedSpace: Amount of space currently in use (dbasize object, convertible to Bytes, KB, MB, GB, TB) FreeSpace: Amount of free space available within the file (dbasize object) FileSize: Total size of the file (dbasize object) PercentUsed: Percentage of the file currently in use (0-100 integer) AutoGrowth: The autogrowth increment amount (dbasize object) AutoGrowType: Type of autogrowth setting (MB for fixed size, pct for percentage, Unknown if error) SpaceUntilMaxSize: Amount of space remaining before reaching max file size limit (dbasize object) AutoGrowthPossible: Maximum additional space available through autogrowth (dbasize object) UnusableSpace: Space that remains after all possible autogrowth operations (dbasize object) Note: All size-related properties use the dbasize object which supports conversion to multiple units (.Bytes, .Kilobytes, .Megabytes, .Gigabytes, .Terabytes properties are available). &nbsp;"
  },
  {
    "name": "Get-DbaDbState",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbState",
    "popularityRank": 183,
    "synopsis": "Retrieves database state information including read/write status, availability, and user access mode",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbState View Source Simone Bizzotto (@niphlod) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database state information including read/write status, availability, and user access mode Description Gets three key database state properties from sys.databases that DBAs frequently need to check: \"RW\" options: READ_ONLY or READ_WRITE (whether database accepts modifications) \"Status\" options: ONLINE, OFFLINE, EMERGENCY, RESTORING (database availability state) \"Access\" options: SINGLE_USER, RESTRICTED_USER, MULTI_USER (user connection restrictions) This 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. Returns an object with SqlInstance, DatabaseName, RW, Status, and Access properties for each user database. Syntax Get-DbaDbState [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets options for all databases of the sqlserver2014a instance PS C:\\> Get-DbaDbState -SqlInstance sqlserver2014a Example 2: Gets options for both HR and Accounting database of the sqlserver2014a instance PS C:\\> Get-DbaDbState -SqlInstance sqlserver2014a -Database HR, Accounting Example 3: Gets options for all databases of the sqlserver2014a instance except HR PS C:\\> Get-DbaDbState -SqlInstance sqlserver2014a -Exclude HR Example 4: Gets options for all databases of sqlserver2014a and sqlserver2014b instances PS C:\\> 'sqlserver2014a', 'sqlserver2014b' | Get-DbaDbState Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which user databases to check for state information. Accepts multiple database names as an array. Use this when you need to audit specific databases rather than checking all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which user databases to exclude from the state check. Accepts multiple database names as an array. Use this when you want to check most databases but skip specific ones, such as databases under maintenance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database queried. Each object contains the database state information for a specific database on the target instance. Default display properties (via Select-DefaultView): SqlInstance: The SQL Server instance name (computer\\instance or just computer) InstanceName: The SQL Server service name (instance name only) ComputerName: The computer name where the SQL Server instance is running DatabaseName: The name of the database RW: The read/write status (READ_WRITE or READ_ONLY) Status: The database availability state (ONLINE, OFFLINE, EMERGENCY, or RESTORING) Access: The user connection restriction level (SINGLE_USER, RESTRICTED_USER, or MULTI_USER) Additional properties available: Database: The SMO Database object for this database (hidden from default display) &nbsp;"
  },
  {
    "name": "Get-DbaDbStoredProcedure",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "storedprocedure",
      "proc"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbStoredProcedure",
    "popularityRank": 92,
    "synopsis": "Retrieves stored procedures from SQL Server databases with detailed metadata and filtering options",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbStoredProcedure View Source Klaas Vandenberghe (@PowerDbaKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves stored procedures from SQL Server databases with detailed metadata and filtering options 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. Syntax Get-DbaDbStoredProcedure [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-ExcludeSystemSp] [[-Name] ] [[-Schema] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database Stored Procedures PS C:\\> Get-DbaDbStoredProcedure -SqlInstance sql2016 Example 2: Gets the Stored Procedures for the db1 database PS C:\\> Get-DbaDbStoredProcedure -SqlInstance Server1 -Database db1 Example 3: Gets the Stored Procedures for all databases except db1 PS C:\\> Get-DbaDbStoredProcedure -SqlInstance Server1 -ExcludeDatabase db1 Example 4: Gets the Stored Procedures for all databases that are not system objects PS C:\\> Get-DbaDbStoredProcedure -SqlInstance Server1 -ExcludeSystemSp Example 5: Gets the Stored Procedures for the databases on Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbStoredProcedure Example 6: Pipe the databases from Get-DbaDatabase into Get-DbaDbStoredProcedure PS C:\\> Get-DbaDatabase -SqlInstance Server1 -ExcludeSystem | Get-DbaDbStoredProcedure Example 7: Gets the Stored Procedure proc1 in the schema1 schema in the db1 database PS C:\\> Get-DbaDbStoredProcedure -SqlInstance Server1 -Database db1 -Name schema1.proc1 Example 8: Gets the Stored Procedure proc1 in the schema1 schema in the db1 database PS C:\\> Get-DbaDbStoredProcedure -SqlInstance Server1 -Name db1.schema1.proc1 Example 9: Gets the Stored Procedure proc1 in the db1 database PS C:\\> Get-DbaDbStoredProcedure -SqlInstance Server1 -Database db1 -Name proc1 Example 10: Gets the Stored Procedures in schema1 for the db1 database PS C:\\> Get-DbaDbStoredProcedure -SqlInstance Server1 -Database db1 -Schema schema1 Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for stored procedures. Accepts database names and supports wildcards. Use this when you need to focus on specific databases instead of searching across all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specified databases from the stored procedure search. Accepts database names and supports wildcards. Useful when you want results from most databases but need to skip specific ones like development or staging databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemSp Excludes system stored procedures from results, showing only user-defined stored procedures. Use this when you want to focus on custom business logic and avoid the hundreds of built-in SQL Server system procedures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Name Specifies exact stored procedure names to retrieve. Supports two-part names (schema.procedure) and three-part names (database.schema.procedure). Use this when searching for specific procedures by name rather than browsing all procedures in a database or schema. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Filters results to stored procedures within the specified schema(s). Accepts multiple schema names. Useful for organizing results by application area or when working with multi-tenant databases that separate objects by schema. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase for pipeline processing. Use this to chain commands when you need to filter databases first, then retrieve stored procedures from the filtered results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.StoredProcedure Returns 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 filtered. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the stored procedure Schema: The schema in which the stored procedure is defined ObjectId: The unique identifier for the stored procedure object (displayed as ID) CreateDate: The date and time when the stored procedure was created DateLastModified: The date and time when the stored procedure was last modified Name: The name of the stored procedure ImplementationType: The implementation type (T-SQL or CLR) Startup: Boolean indicating if the procedure is marked as a startup procedure Additional properties available (from SMO StoredProcedure object): DatabaseId: The unique identifier of the database containing the procedure IsSystemObject: Boolean indicating if this is a system-defined stored procedure And all other standard SMO StoredProcedure properties (use Select-Object * to see all) When -ExcludeSystemSp is specified, system stored procedures are filtered out and only user-defined procedures are returned. &nbsp;"
  },
  {
    "name": "Get-DbaDbSynonym",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "synonym"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbSynonym",
    "popularityRank": 479,
    "synopsis": "Retrieves database synonyms and their target object mappings from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbSynonym View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database synonyms and their target object mappings from SQL Server instances 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. Syntax Get-DbaDbSynonym [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Schema] ] [[-ExcludeSchema] ] [[-Synonym] ] [[-ExcludeSynonym] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Returns all database synonyms in all databases on the local default SQL Server instance PS C:\\> Get-DbaDbSynonym -SqlInstance localhost Example 2: Returns all synonyms of all database(s) on the local and sql2016 SQL Server instances PS C:\\> Get-DbaDbSynonym -SqlInstance localhost, sql2016 Example 3: Returns synonyms of all database(s) for every server in C:\\servers.txt PS C:\\> $servers = Get-Content C:\\servers.txt PS C:\\> $servers | Get-DbaDbSynonym Example 4: Returns synonyms of the database db1 on localhost PS C:\\> Get-DbaDbSynonym -SqlInstance localhost -Database db1 Example 5: Returns the synonym1 synonym in the db1 database on localhost PS C:\\> Get-DbaDbSynonym -SqlInstance localhost -Database db1 -Synonym 'synonym1' Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which database(s) to search for synonyms. Accepts wildcards for pattern matching. Use this when you need to focus on specific databases instead of scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific database(s) from the synonym search. Accepts wildcards for pattern matching. Useful for skipping system databases, test environments, or databases you know don't contain relevant synonyms. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Filters synonyms to only those in the specified schema(s). Accepts wildcards for pattern matching. Use this when you need to focus on synonyms within specific schemas, such as application-specific or departmental schemas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSchema Excludes synonyms from specific schema(s) in the results. Accepts wildcards for pattern matching. Helpful for filtering out system schemas or schemas that contain synonyms you're not interested in analyzing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Synonym Specifies exact synonym name(s) to retrieve. Accepts multiple synonym names as an array. Use this when you need details about specific synonyms, such as checking where a particular synonym points or verifying its target object. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSynonym Excludes specific synonym(s) from the results by name. Accepts multiple synonym names as an array. Useful when you want to see all synonyms except certain ones you already know about or don't need to review. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase via pipeline input. Allows you to chain database filtering commands. Use this to process synonyms only from databases that meet specific criteria, such as specific compatibility levels or last backup dates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Synonym Returns one Synonym object per database synonym found. The output includes details about each synonym and its target object mapping. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance hosting the synonym InstanceName: The SQL Server instance name where the synonym is located SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName) Database: The database containing the synonym Schema: The schema that contains the synonym Name: The name of the synonym object BaseServer: The linked server name if the synonym references a remote object, or the server name for local references BaseDatabase: The database containing the target object that the synonym references BaseSchema: The schema containing the target object that the synonym references BaseObject: The name of the target object that the synonym references (table, view, function, etc.) All properties from the base SMO Synonym object are accessible through Select-Object * even though only the default properties are displayed without using Select-Object. &nbsp;"
  },
  {
    "name": "Get-DbaDbTable",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "tables"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaDbTable",
    "popularityRank": 31,
    "synopsis": "Retrieves table metadata including space usage, row counts, and table features from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbTable View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves table metadata including space usage, row counts, and table features from SQL Server databases 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. Syntax Get-DbaDbTable [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-IncludeSystemDBs] [[-Table] ] [[-Schema] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Return all tables in the Test1 database PS C:\\> Get-DbaDbTable -SqlInstance DEV01 -Database Test1 Example 2: Return only information on the table MyTable from the database MyDB PS C:\\> Get-DbaDbTable -SqlInstance DEV01 -Database MyDB -Table MyTable Example 3: Return only information on the table MyTable from the database MyDB and only from the schema MySchema PS C:\\> Get-DbaDbTable -SqlInstance DEV01 -Database MyDB -Table MyTable -Schema MySchema Example 4: Returns information on table called MyTable if it exists in any database on the server, under any schema PS C:\\> Get-DbaDbTable -SqlInstance DEV01 -Table MyTable Example 5: Returns information on table called First.Table on schema dbo if it exists in any database on the server PS C:\\> Get-DbaDbTable -SqlInstance DEV01 -Table dbo.[First.Table] Example 6: Returns information on the CommandLog table in the DBA database on both instances localhost and the named... PS C:\\> 'localhost','localhost\\namedinstance' | Get-DbaDbTable -Database DBA -Table Commandlog Returns information on the CommandLog table in the DBA database on both instances localhost and the named instance localhost\\namedinstance Example 7: Return table information for instance Dev01 and table Process with special characters in the schema name PS C:\\> Get-DbaDbTable -SqlInstance DEV01 -Table \"[[DbName]]].[Schema.With.Dots].[`\"[Process]]`\"]\" -Verbose Optional Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to retrieve table information from. Accepts multiple database names and wildcards. Use this when you need table data from specific databases instead of scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from table retrieval. Accepts multiple database names and wildcards. Helpful when you want most databases but need to skip problematic or irrelevant ones like temp databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSystemDBs Includes system databases (master, model, msdb, tempdb) in the table scan. By default system databases are excluded since they rarely contain user tables of interest. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Table Specifies specific tables to retrieve using one, two, or three-part naming (table, schema.table, or database.schema.table). Use this when you need information on particular tables instead of all tables in the database. Wrap names containing special characters in square brackets and escape actual ] characters by doubling them. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -Schema Filters results to tables within specific schemas. Accepts multiple schema names. Useful for focusing on application schemas while excluding utility or system schemas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase via pipeline input. Use this when you have already filtered databases and want to pass them directly for table processing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Table Returns one Table object per table found in the specified databases. Each object is enhanced with dbatools-specific properties for server connection context. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the table Schema: The schema name that contains the table Name: The table name IndexSpaceUsed: Total space used by indexes for the table (in KB, not available in Azure SQL Database) DataSpaceUsed: Space used by data for the table (in KB, not available in Azure SQL Database) RowCount: Number of rows in the table HasClusteredIndex: Boolean indicating if table has a clustered index Version-specific properties (included in output when available): IsPartitioned: Boolean indicating if table is partitioned (SQL Server 2005+) ChangeTrackingEnabled: Boolean indicating if change tracking is enabled (SQL Server 2008+) IsFileTable: Boolean indicating if table is a FileTable (SQL Server 2012+) IsMemoryOptimized: Boolean indicating if table is memory-optimized (SQL Server 2014+) IsNode: Boolean indicating if table is a node table for graph database (SQL Server 2017+) IsEdge: Boolean indicating if table is an edge table for graph database (SQL Server 2017+) Additional properties available from the SMO Table object: FullTextIndex: FullTextIndex object for accessing full-text search configuration (if configured) CreateDate: DateTime when the table was created DateLastModified: DateTime when the table was last modified IsSystemObject: Boolean indicating if this is a system table FileStreamPartitionColumn: Name of the column used for FileStream partitioning AnsiNullsStatus: Boolean indicating ANSI NULLs setting QuotedIdentifierStatus: Boolean indicating QUOTED_IDENTIFIER setting All properties from the base SMO Table object are accessible via Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbTrigger",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "trigger"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbTrigger",
    "popularityRank": 401,
    "synopsis": "Retrieves database-level DDL triggers from SQL Server instances for security auditing and change tracking analysis.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbTrigger View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database-level DDL triggers from SQL Server instances for security auditing and change tracking analysis. 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. Syntax Get-DbaDbTrigger [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all database triggers PS C:\\> Get-DbaDbTrigger -SqlInstance sql2017 Example 2: Returns all triggers for database supa on sql2017 PS C:\\> Get-DbaDatabase -SqlInstance sql2017 -Database supa | Get-DbaDbTrigger Example 3: Returns all triggers for database supa on sql2017 PS C:\\> Get-DbaDbTrigger -SqlInstance sql2017 -Database supa Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for DDL triggers. Accepts wildcards for pattern matching. Use this when you need to audit triggers in specific databases rather than checking all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the trigger scan. Useful for skipping system databases or databases under maintenance. Commonly used to exclude tempdb, model, or databases that don't require trigger auditing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase via pipeline input for targeted trigger analysis. Use this when you want to process a pre-filtered set of database objects instead of specifying database names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.DatabaseDdlTrigger Returns one DatabaseDdlTrigger object per database trigger found on the specified databases. The function enhances the SMO object with additional dbatools properties via Add-Member. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the database-level DDL trigger IsEnabled: Boolean indicating whether the trigger is enabled DateLastModified: DateTime when the trigger was last modified Additional properties available (from SMO DatabaseDdlTrigger object): CreateDate: DateTime when the trigger was created EventSet: The set of DDL events that fire the trigger (CREATE_TABLE, ALTER_TABLE, DROP_TABLE, etc.) ExecutionContext: The execution context of the trigger (Caller, Owner, or specific user) TextHeader: The header portion of the trigger definition TextBody: The body portion of the trigger SQL code Text: The complete T-SQL definition of the trigger Urn: The uniform resource name (URN) uniquely identifying the trigger State: The state of the SMO object (Existing, Creating, Dropping, etc.) All properties from the base SMO DatabaseDdlTrigger object are accessible via Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbUdf",
    "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.",
    "category": "Database Operations",
    "tags": [
      "udf",
      "database"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbUdf",
    "popularityRank": 356,
    "synopsis": "Retrieves User Defined Functions and User Defined Aggregates from SQL Server databases with filtering and metadata",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbUdf View Source Klaas Vandenberghe (@PowerDbaKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves User Defined Functions and User Defined Aggregates from SQL Server databases with filtering and metadata 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. Syntax Get-DbaDbUdf [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-ExcludeSystemUdf] [[-Schema] ] [[-ExcludeSchema] ] [[-Name] ] [[-ExcludeName] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database User Defined Functions and User Defined Aggregates PS C:\\> Get-DbaDbUdf -SqlInstance sql2016 Example 2: Gets the User Defined Functions and User Defined Aggregates for the db1 database PS C:\\> Get-DbaDbUdf -SqlInstance Server1 -Database db1 Example 3: Gets the User Defined Functions and User Defined Aggregates for all databases except db1 PS C:\\> Get-DbaDbUdf -SqlInstance Server1 -ExcludeDatabase db1 Example 4: Gets the User Defined Functions and User Defined Aggregates for all databases that are not system objects... PS C:\\> Get-DbaDbUdf -SqlInstance Server1 -ExcludeSystemUdf Gets 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) Example 5: Gets the User Defined Functions and User Defined Aggregates for the databases on Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbUdf Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to retrieve User Defined Functions from. Accepts wildcards for pattern matching. Use this when you need to audit UDFs in specific databases rather than scanning the entire instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip when retrieving User Defined Functions. Useful for excluding system databases or databases under maintenance. Commonly used to exclude tempdb, model, or large databases that don't contain custom business logic. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemUdf Filters out built-in SQL Server system functions from the results, showing only custom user-created functions. Essential when auditing business logic since system databases can contain 100+ built-in UDFs that obscure custom code. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Schema Limits results to User Defined Functions within specific schemas. Accepts multiple schema names. Useful for focusing on functions owned by particular applications or development teams, such as 'Sales' or 'Reporting' schemas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSchema Excludes User Defined Functions from specific schemas when retrieving results. Helpful for filtering out legacy schemas, test schemas, or third-party application schemas that aren't relevant to your analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Retrieves specific User Defined Functions by name. Accepts multiple function names and supports wildcards. Use this when searching for particular functions during troubleshooting or when documenting specific business logic components. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeName Excludes specific User Defined Functions from results by name. Supports wildcards for pattern matching. Useful for filtering out known test functions, deprecated functions, or utility functions that clutter audit reports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.UserDefinedFunction, Microsoft.SqlServer.Management.Smo.UserDefinedAggregate Returns 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 always being user-created (no system aggregates exist in SQL Server). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the function/aggregate Schema: The schema that contains the function/aggregate CreateDate: DateTime when the function/aggregate was originally created DateLastModified: DateTime of the most recent modification to the function/aggregate Name: The name of the User Defined Function or User Defined Aggregate DataType: The return data type of the function/aggregate (for example, 'int', 'varchar', 'table', etc.) Additional properties available from SMO (UserDefinedFunction): IsSystemObject: Boolean indicating if this is a system-created object (True for system functions, False for user-created) AssemblyName: Name of the .NET assembly if this is a CLR-based function ClassName: Class name within the assembly for CLR-based functions ExecutionContext: Whether function executes in caller or owner context IsInlineTableValuedFunction: Boolean for inline table-valued functions IsSqlTabular: Boolean indicating if this is a SQL table-valued function QuotedIdentifierStatus: Boolean indicating quoted identifier setting ReturnsNullOnNullInput: Boolean indicating NULL handling behavior Text: The T-SQL source code or assembly reference of the function Note: 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). &nbsp;"
  },
  {
    "name": "Get-DbaDbUser",
    "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.",
    "category": "Database Operations",
    "tags": [
      "user",
      "database"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaDbUser",
    "popularityRank": 33,
    "synopsis": "Retrieves database user accounts and their associated login mappings from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbUser View Source Klaas Vandenberghe (@PowerDbaKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database user accounts and their associated login mappings from SQL Server databases 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. Syntax Get-DbaDbUser [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-ExcludeSystemUser] [[-User] ] [[-Login] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database users PS C:\\> Get-DbaDbUser -SqlInstance sql2016 Example 2: Gets the users for the db1 database PS C:\\> Get-DbaDbUser -SqlInstance Server1 -Database db1 Example 3: Gets the users for all databases except db1 PS C:\\> Get-DbaDbUser -SqlInstance Server1 -ExcludeDatabase db1 Example 4: Gets the users for all databases that are not system objects, like &#39;dbo&#39;, &#39;guest&#39; or &#39;INFORMATION_SCHEMA&#39; PS C:\\> Get-DbaDbUser -SqlInstance Server1 -ExcludeSystemUser Example 5: Gets the users for the databases on Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbUser Example 6: Gets the users &#39;user1&#39; and &#39;user2&#39; from the db1 database PS C:\\> Get-DbaDbUser -SqlInstance Server1 -Database db1 -User user1, user2 Example 7: Gets the users associated with the logins &#39;login1&#39; and &#39;login2&#39; PS C:\\> Get-DbaDbUser -SqlInstance Server1 -Login login1, login2 Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to query for user accounts. Accepts multiple database names and supports wildcards. Use this when you need to audit users in specific databases rather than scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip when retrieving user accounts. Useful for excluding system databases or databases you don't manage. Common practice is to exclude tempdb, model, or development databases when focusing on production user access reviews. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemUser Excludes built-in system users like 'dbo', 'guest', 'INFORMATION_SCHEMA', and other system-created accounts. Use this switch during security audits to focus only on custom user accounts that require regular access review and management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -User Filters results to specific database user names. Accepts multiple user names for targeted queries. Use this when investigating specific user accounts or verifying permissions for particular users during access reviews or troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Filters results to database users associated with specific server logins. Shows which databases a login has user accounts in. Essential for understanding a login's database-level access across the instance, especially during user access audits or when removing departing employees. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.User Returns one User object per database user found. The output is filtered based on the -User, -Login, and -ExcludeSystemUser parameters. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the user CreateDate: DateTime when the user was created DateLastModified: DateTime when the user was last modified Name: The name of the database user Login: The associated server login name (empty string if user is an orphan) LoginType: The type of login (SqlLogin, WindowsUser, WindowsGroup, Certificate, AsymmetricKey, or ExternalUser) AuthenticationType: The authentication method (Database or Windows) State: The object state (Existing, Creating, Dropping, etc.) HasDbAccess: Boolean indicating if the user has database access DefaultSchema: The default schema associated with the user Additional properties available (from SMO User object): ID: Unique object ID within the database IsSystemObject: Boolean indicating if this is a built-in system user (dbo, guest, INFORMATION_SCHEMA, etc.) IsDisabled: Boolean indicating if the user is disabled Urn: Uniform Resource Name identifier for the user Sid: Security identifier for Windows-authenticated users MustChangePassword: Boolean indicating if user must change password on next login (SQL logins only) PasswordExpirationEnabled: Boolean indicating if password expiration policy is enabled PasswordExpired: Boolean indicating if password has expired All properties from the base SMO User object are accessible via Select-Object * even though only default properties are displayed. &nbsp;"
  },
  {
    "name": "Get-DbaDbUserDefinedTableType",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "userdefinedtabletype",
      "type"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbUserDefinedTableType",
    "popularityRank": 482,
    "synopsis": "Retrieves user-defined table types from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbUserDefinedTableType View Source Ant Green (@ant_green) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves user-defined table types from SQL Server databases 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. Syntax Get-DbaDbUserDefinedTableType [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Type] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database user defined table types in all the databases PS C:\\> Get-DbaDbUserDefinedTableType -SqlInstance sql2016 Example 2: Gets all the user defined table types for the db1 database PS C:\\> Get-DbaDbUserDefinedTableType -SqlInstance Server1 -Database db1 Example 3: Gets type1 user defined table type from db1 database PS C:\\> Get-DbaDbUserDefinedTableType -SqlInstance Server1 -Database db1 -Type type1 Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to retrieve user-defined table types from. Accepts database names and supports wildcards for pattern matching. Use this when you need to examine table types in specific databases rather than all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to exclude from the search for user-defined table types. Accepts database names and wildcards. Use this when you want to scan most databases but skip specific ones like system databases or inactive databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Filters results to include only specific user-defined table type names. Accepts an array of type names for multiple selections. Use this when you need to examine particular table types across databases, such as auditing usage of a specific custom type. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.UserDefinedTableType Returns one UserDefinedTableType object per user-defined table type found. System objects are automatically excluded. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the user-defined table type ID: The unique identifier (ID) of the user-defined table type within the database Name: The name of the user-defined table type Columns: The collection of columns defined in the table type (ColumnCollection object) Owner: The owner (schema) of the user-defined table type CreateDate: The date and time when the user-defined table type was created IsSystemObject: Boolean indicating whether this is a system object (always False for returned results) Version: The internal version number of the user-defined table type Additional properties available (from SMO UserDefinedTableType object): DefaultSchema: The default schema for the table type ExtendedProperties: Extended properties (key/value pairs) for the table type Urn: Unique resource name identifying the object in the SQL Server instance State: The state of the object (Existing, Creating, Pending, etc.) All properties from the base SMO object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaDbView",
    "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.",
    "category": "Database Operations",
    "tags": [
      "view",
      "database"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbView",
    "popularityRank": 158,
    "synopsis": "Retrieves SQL Server database views with metadata for documentation and analysis.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbView View Source Klaas Vandenberghe (@PowerDbaKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server database views with metadata for documentation and analysis. 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. Syntax Get-DbaDbView [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-ExcludeSystemView] [[-View] ] [[-Schema] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all database views PS C:\\> Get-DbaDbView -SqlInstance sql2016 Example 2: Gets the views for the db1 database PS C:\\> Get-DbaDbView -SqlInstance Server1 -Database db1 Example 3: Gets the views for all databases except db1 PS C:\\> Get-DbaDbView -SqlInstance Server1 -ExcludeDatabase db1 Example 4: Gets the views for all databases that are not system objects (there can be 400+ system views in each DB) PS C:\\> Get-DbaDbView -SqlInstance Server1 -ExcludeSystemView Example 5: Gets the views for the databases on Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbView Example 6: Pipe the databases from Get-DbaDatabase into Get-DbaDbView PS C:\\> Get-DbaDatabase -SqlInstance Server1 -ExcludeSystem | Get-DbaDbView Example 7: Gets the view vw1 for the db1 database PS C:\\> Get-DbaDbView -SqlInstance Server1 -Database db1 -View vw1 Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 output. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.View Returns one View object per database view found that matches the filter criteria. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the view Schema: The schema name where the view is defined CreateDate: The datetime when the view was created DateLastModified: The datetime when the view was last modified Name: The name of the view Additional properties available (from SMO View object): IsSystemObject: Boolean indicating if this is a system view IsEncrypted: Boolean indicating if the view definition is encrypted IsBound: Boolean indicating if the view references only available objects Implementation: String indicating the view implementation (Standard or Unknown) PropertyCount: Integer count of the number of properties the view has TextHeader: String containing the header portion of the view definition TextMode: The text mode of the view All properties from the SMO View object are accessible by using Select-Object * or by using the property names directly. &nbsp;"
  },
  {
    "name": "Get-DbaDbVirtualLogFile",
    "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's 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've got a high number of VLFs, you can use Expand-DbaDbLogFile to reduce the number.",
    "category": "Database Operations",
    "tags": [
      "diagnostic",
      "vlf",
      "database",
      "logfile"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDbVirtualLogFile",
    "popularityRank": 318,
    "synopsis": "Retrieves detailed virtual log file (VLF) metadata from transaction logs for performance analysis and troubleshooting.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDbVirtualLogFile View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed virtual log file (VLF) metadata from transaction logs for performance analysis and troubleshooting. 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's essential for analyzing transaction log structure and performance. Having 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. Common 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. References: http://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/ http://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx If you've got a high number of VLFs, you can use Expand-DbaDbLogFile to reduce the number. Syntax Get-DbaDbVirtualLogFile [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-IncludeSystemDBs] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all user database virtual log file details for the sqlcluster instance PS C:\\> Get-DbaDbVirtualLogFile -SqlInstance sqlcluster Example 2: Returns user databases that have 50 or more VLFs PS C:\\> Get-DbaDbVirtualLogFile -SqlInstance sqlserver | Group-Object -Property Database | Where-Object Count -gt 50 Example 3: Returns all VLF information for the sqlserver and sqlcluster SQL Server instances PS C:\\> 'sqlserver','sqlcluster' | Get-DbaDbVirtualLogFile Returns all VLF information for the sqlserver and sqlcluster SQL Server instances. Processes data via the pipeline. Example 4: Returns the VLF counts for the db1 and db2 databases on sqlcluster PS C:\\> Get-DbaDbVirtualLogFile -SqlInstance sqlcluster -Database db1, db2 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for VLF information. Accepts wildcards for pattern matching. Use this when you need to focus on specific databases instead of checking all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to skip during VLF analysis. Accepts wildcards for pattern matching. Use this to exclude problematic databases or those you don't need to monitor for VLF issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSystemDBs Include system databases (master, model, msdb, tempdb) in the VLF analysis. By default, only user databases are checked since system database VLF counts are typically less critical for performance tuning. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per virtual log file (VLF) found in each database transaction log. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName) Database: The name of the database containing the virtual log file RecoveryUnitId: The recovery unit identifier for the VLF FileId: The transaction log file ID (typically 0 for the primary log file) FileSize: The size of the virtual log file in bytes StartOffset: The starting offset of this VLF within the transaction log file in bytes FSeqNo: The virtual log file sequence number - indicates the order of VLFs in the transaction log Status: The status of the VLF (0=unused, 1=active, 2=recoverable) Parity: The parity value used for recovery tracking and alternate backup validation CreateLsn: The Log Sequence Number (LSN) at which this VLF was created &nbsp;"
  },
  {
    "name": "Get-DbaDefaultPath",
    "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.",
    "category": "Backup & Restore",
    "tags": [
      "storage",
      "data",
      "log",
      "backup"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDefaultPath",
    "popularityRank": 296,
    "synopsis": "Retrieves default file paths for SQL Server data, log, backup, and error log directories",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDefaultPath View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves default file paths for SQL Server data, log, backup, and error log directories 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. Syntax Get-DbaDefaultPath [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the default file paths for sql01\\sharepoint PS C:\\> Get-DbaDefaultPath -SqlInstance sql01\\sharepoint Example 2: Returns the default file paths for &quot;sql2014&quot;,&quot;sql2016&quot; and &quot;sqlcluster\\sharepoint&quot; PS C:\\> $servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\" PS C:\\> $servers | Get-DbaDefaultPath Required Parameters -SqlInstance The target SQL Server instance or instances. Accepts named instances (server\\instance) and pipeline input for batch processing. Use this to query multiple SQL Server instances at once to compare their default path configurations across your environment. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Use this when Windows Authentication isn't available or when you need to connect using SQL Server Authentication or service accounts. Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance with the default file paths configured for that server. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (ServiceName) SqlInstance: The full SQL Server instance name in computer\\instance format (DomainInstanceName) Data: The default directory path for new database data files Log: The default directory path for new transaction log files Backup: The default directory path for database backups ErrorLog: The directory path where SQL Server stores error log files &nbsp;"
  },
  {
    "name": "Get-DbaDependency",
    "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 'Parents' 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",
    "category": "Utilities",
    "tags": [
      "dependency",
      "utility"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDependency",
    "popularityRank": 334,
    "synopsis": "Maps SQL Server object dependencies and generates creation scripts in proper deployment order",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDependency View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Maps SQL Server object dependencies and generates creation scripts in proper deployment order Description This function discovers SQL Server object dependencies using SMO (SQL Server Management Objects) and returns detailed information including creation scripts and deployment order. By 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. The function returns objects in hierarchical tiers, showing you exactly which objects need to be created first when deploying to a new environment. Each result includes the T-SQL creation script, so you can generate deployment scripts in the correct dependency order without manually figuring out prerequisites. Use the 'Parents' 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. This is particularly valuable when migrating individual objects between environments or troubleshooting missing dependencies. For more details on dependency relationships, see: https://technet.microsoft.com/en-us/library/ms345449(v=sql.105).aspx Syntax Get-DbaDependency [[-InputObject] ] [-AllowSystemObjects] [-Parents] [-IncludeSelf] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns everything that depends on the &quot;Customers&quot; table PS C:\\> $table = (Get-DbaDatabase -SqlInstance sql2012 -Database Northwind).tables | Where-Object Name -eq Customers PS C:\\> $table | Get-DbaDependency Optional Parameters -InputObject Specifies the SQL Server object (table, view, stored procedure, function, etc.) to analyze for dependencies. Accepts any SMO object from Get-DbaDatabase, Get-DbaDbTable, Get-DbaDbStoredProcedure, and similar commands. Use this when you need to understand what objects will be affected by changes to a specific database object. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -AllowSystemObjects Includes system objects like sys tables, system functions, and built-in stored procedures in dependency results. Use this when you need complete dependency mapping including SQL Server internal objects. Most DBAs can leave this off since system dependencies rarely impact deployment or migration planning. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Parents Reverses the dependency direction to show what objects the input depends on rather than what depends on it. Essential for understanding prerequisites when migrating objects or troubleshooting \"object not found\" errors. Use this to identify all dependencies that must exist before you can create or restore the target object. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSelf Includes the original input object in the results along with its dependencies. Helpful when generating complete deployment scripts that need to recreate both the object and everything it depends on. Commonly used when exporting database schemas or preparing objects for cross-environment deployment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Database.Dependency Returns 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. Properties: ComputerName: The name of the SQL Server computer ServiceName: The SQL Server service name SqlInstance: The full SQL Server instance name Dependent: The name of the dependent database object Type: The SMO object type (Table, View, StoredProcedure, UserDefinedFunction, etc.) Owner: The schema/owner of the object IsSchemaBound: Boolean indicating if the object is schema-bound (relevant for views and functions) Parent: The name of the parent object (the object being depended upon or depending on this object) ParentType: The SMO type of the parent object Tier: Integer indicating the deployment tier (1 = base dependencies, higher numbers = dependent on lower-numbered tiers) Object: The SMO object instance for the dependent object (allows access to all SMO properties) Urn: The URN (Uniform Resource Name) of the dependent object OriginalResource: The original input object being analyzed for dependencies Script: The T-SQL creation script for the dependent object, ready for deployment When -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 included in the results with Tier 0. &nbsp;"
  },
  {
    "name": "Get-DbaDeprecatedFeature",
    "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've 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",
    "category": "Utilities",
    "tags": [
      "deprecated",
      "general"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDeprecatedFeature",
    "popularityRank": 579,
    "synopsis": "Identifies deprecated SQL Server features currently in use with their usage counts from performance counters.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDeprecatedFeature View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies deprecated SQL Server features currently in use with their usage counts from performance counters. 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've 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. The 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. More information: https://learn.microsoft.com/en-us/sql/relational-databases/performance-monitor/sql-server-deprecated-features-object Syntax Get-DbaDeprecatedFeature [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get usage information relating to deprecated features on the servers sql2008 and sqlserver2012 PS C:\\> Get-DbaDeprecatedFeature -SqlInstance sql2008, sqlserver2012 Example 2: Get usage information relating to deprecated features on server sql2008 PS C:\\> Get-DbaDeprecatedFeature -SqlInstance sql2008 Required Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per deprecated SQL Server feature that has been used on the instance (with usage count > 0). Properties: ComputerName: The name of the computer running the SQL Server instance InstanceName: The name of the SQL Server instance (from SQL Server's perspective) SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName format) DeprecatedFeature: The name of the deprecated SQL Server feature UsageCount: Integer count of how many times this deprecated feature has been used &nbsp;"
  },
  {
    "name": "Get-DbaDiskSpace",
    "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.",
    "category": "Utilities",
    "tags": [
      "storage",
      "disk",
      "space",
      "os"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaDiskSpace",
    "popularityRank": 47,
    "synopsis": "Retrieves disk space and filesystem details from SQL Server host systems for capacity monitoring and performance analysis.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaDiskSpace View Source Chrissy LeMaire (@cl), netnerds.net , Jakob Bindslet Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves disk space and filesystem details from SQL Server host systems for capacity monitoring and performance analysis. 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. Essential 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. By 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. Requires Windows administrator access on target SQL Server systems. Syntax Get-DbaDiskSpace [[-ComputerName] ] [[-Credential] ] [[-Unit] ] [[-SqlCredential] ] [[-ExcludeDrive] ] [-CheckFragmentation] [-Force] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get disk space for the server srv0042 PS C:\\> Get-DbaDiskSpace -ComputerName srv0042 Example 2: Get disk space for the server srv0042 and displays in megabytes (MB) PS C:\\> Get-DbaDiskSpace -ComputerName srv0042 -Unit MB Example 3: Get disk space from two servers and displays in terabytes (TB) PS C:\\> Get-DbaDiskSpace -ComputerName srv0042, srv0007 -Unit TB Example 4: Get all disk and volume space information PS C:\\> Get-DbaDiskSpace -ComputerName srv0042 -Force Example 5: Get all disk and volume space information PS C:\\> Get-DbaDiskSpace -ComputerName srv0042 -ExcludeDrive 'C:\\' Optional Parameters -ComputerName Specifies the SQL Server host systems to query for disk space information. Accepts multiple computer names for bulk monitoring. Use this to check storage capacity across your SQL Server environment before database growth or backup operations impact available space. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Credential object used to connect to the computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Unit This parameter has been deprecated and will be removed in 1.0.0. All size properties (Bytes, KB, MB, GB, TB, PB) are now available simultaneously in the output object but hidden by default for cleaner display. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | GB | | Accepted Values | Bytes,KB,MB,GB,TB,PB | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDrive Specifies drive letters to exclude from the disk space report, using the format 'C:\\' or 'D:\\'. Use this to skip system drives or non-SQL storage when focusing on database file locations, or to exclude network drives that may cause timeouts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. This significantly increases runtime (seconds to minutes per volume) but provides critical data for troubleshooting slow database operations or planning defragmentation maintenance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Includes all drive types and hidden volumes in the results, not just local and removable disks (DriveType 2 and 3). Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Computer.DiskSpace Returns 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 unit formats (Bytes, KB, MB, GB, TB, PB). Default display properties (shown without using Select-Object): ComputerName: The name of the computer Name: The volume name (drive letter or UNC path, e.g., 'C:\\' or '\\\\server\\share') Label: The volume label/name if assigned Capacity: Total disk capacity in the specified unit (default GB) Free: Free space available in the specified unit (default GB) PercentFree: Percentage of disk space that is free BlockSize: File system block size in bytes *Additional properties available (use Select-Object to view): FileSystem: File system type (NTFS, FAT32, ReFS, etc.) Type: Drive type identifier (corresponds to DriveType) DriveType: Enumerated drive type (LocalDisk, RemovableDisk, NetworkDrive, etc.) IsSqlDisk: Boolean indicating if SQL Server files are detected on this disk Server: Server name (same as ComputerName) Size information in all units (dynamically calculated):** SizeInBytes, FreeInBytes: Capacity and free space in bytes SizeInKB, FreeInKB: Capacity and free space in kilobytes SizeInMB, FreeInMB: Capacity and free space in megabytes SizeInGB, FreeInGB: Capacity and free space in gigabytes SizeInTB, FreeInTB: Capacity and free space in terabytes SizeInPB, FreeInPB: Capacity and free space in petabytes By 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 specific volumes. &nbsp;"
  },
  {
    "name": "Get-DbaDump",
    "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.",
    "category": "Utilities",
    "tags": [
      "diagnostic",
      "engine",
      "corruption"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaDump",
    "popularityRank": 275,
    "synopsis": "Retrieves SQL Server memory dump file information from sys.dm_server_memory_dumps DMV.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaDump View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server memory dump file information from sys.dm_server_memory_dumps DMV. 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. Syntax Get-DbaDump [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Shows the detailed information for memory dump(s) located on sql2016 instance PS C:\\> Get-DbaDump -SqlInstance sql2016 Example 2: Shows the detailed information for memory dump(s) located on sql2016 instance PS C:\\> Get-DbaDump -SqlInstance sql2016 -SqlCredential sqladmin Shows the detailed information for memory dump(s) located on sql2016 instance. Logs into the SQL Server using the SQL login 'sqladmin' Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) FileName: The file path and name of the memory dump file (.mdmp) CreationTime: DateTime indicating when the memory dump was created Size: The size of the memory dump file (formatted as dbasize for easy human-readable display, e.g., \"1.5 GB\") &nbsp;"
  },
  {
    "name": "Get-DbaEndpoint",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "endpoint"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaEndpoint",
    "popularityRank": 303,
    "synopsis": "Retrieves SQL Server endpoints with network connectivity details for troubleshooting and documentation.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaEndpoint View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server endpoints with network connectivity details for troubleshooting and documentation. 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. Syntax Get-DbaEndpoint [-SqlInstance] [[-SqlCredential] ] [[-Endpoint] ] [[-Type] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all endpoints on the local default SQL Server instance PS C:\\> Get-DbaEndpoint -SqlInstance localhost Example 2: Returns all endpoints for the local and sql2016 SQL Server instances PS C:\\> Get-DbaEndpoint -SqlInstance localhost, sql2016 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Endpoint Specifies one or more endpoint names to retrieve instead of returning all endpoints. Accepts exact endpoint names and supports multiple values. Use this when you need to examine specific endpoints like 'Mirroring' or 'AlwaysOn_health' rather than scanning all configured endpoints. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Filters endpoints by their functional type. Valid options: DatabaseMirroring, ServiceBroker, Soap, and TSql. Use this to focus on specific endpoint categories, such as 'DatabaseMirroring' for Always On AG troubleshooting or 'ServiceBroker' for message queuing configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Endpoint Returns one Endpoint object per endpoint found on the SQL Server instance, with custom properties added for connection details and network information. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (service name) SqlInstance: The fully qualified SQL Server instance name (Computer\\Instance) ID: The unique identifier of the endpoint Name: The name of the endpoint IPAddress: The IP address the endpoint listens on (when TCP is configured; otherwise null) Port: The TCP port the endpoint listens on (when TCP is configured; otherwise null) EndpointState: The current state of the endpoint (Started or Stopped) EndpointType: The type of endpoint (DatabaseMirroring, ServiceBroker, Soap, or TSql) Owner: The SQL Server login that owns the endpoint IsAdminEndpoint: Boolean indicating if this is an administrative endpoint 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 IsSystemObject: Boolean indicating if this is a system-created endpoint Additional properties available (from SMO Endpoint object): CreateDate: The date and time when the endpoint was created DateLastModified: The date and time when the endpoint was last modified Payload: Protocol-specific configuration details for the endpoint Protocol: Protocol configuration details (includes Tcp, NamedPipes, SharedMemory configuration objects) ProtocolName: The name of the protocol used Note: 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 null or empty. The Fqdn property is automatically resolved with DNS lookups to provide a fully qualified domain name for connectivity testing. &nbsp;"
  },
  {
    "name": "Get-DbaErrorLog",
    "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't have to check each log file manually.",
    "category": "Server Management",
    "tags": [
      "logging",
      "instance",
      "errorlog"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaErrorLog",
    "popularityRank": 115,
    "synopsis": "Retrieves SQL Server error log entries for troubleshooting and monitoring",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaErrorLog View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server error log entries for troubleshooting and monitoring Description Retrieves entries from SQL Server error logs across all available log files (0-99, where 0 is current and 99 is oldest). Essential for troubleshooting SQL Server issues, monitoring login failures, tracking system events, and compliance auditing. Supports filtering by log number, source type, text patterns, and date ranges to quickly locate specific errors or events. Reads from all available error logs by default, so you don't have to check each log file manually. Syntax Get-DbaErrorLog [[-SqlInstance] ] [[-SqlCredential] ] [[-LogNumber] ] [[-Source] ] [[-Text] ] [[-After] ] [[-Before] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns every log entry from sql01\\sharepoint SQL Server instance PS C:\\> Get-DbaErrorLog -SqlInstance sql01\\sharepoint Example 2: Returns all log entries for log number 3 and 6 on sql01\\sharepoint SQL Server instance PS C:\\> Get-DbaErrorLog -SqlInstance sql01\\sharepoint -LogNumber 3, 6 Example 3: Returns every log entry, with a source of Logon, from sql01\\sharepoint SQL Server instance PS C:\\> Get-DbaErrorLog -SqlInstance sql01\\sharepoint -Source Logon Example 4: Returns every log entry for log number 3, with &quot;login failed&quot; in the text, from sql01\\sharepoint SQL Server... PS C:\\> Get-DbaErrorLog -SqlInstance sql01\\sharepoint -LogNumber 3 -Text \"login failed\" Returns every log entry for log number 3, with \"login failed\" in the text, from sql01\\sharepoint SQL Server instance. Example 5: Returns the most recent SQL Server error logs for &quot;sql2014&quot;,&quot;sql2016&quot; and &quot;sqlcluster\\sharepoint&quot; PS C:\\> $servers = \"sql2014\",\"sql2016\", \"sqlcluster\\sharepoint\" PS C:\\> $servers | Get-DbaErrorLog -LogNumber 0 Example 6: Returns every log entry found after the date 14 November 2016 from sql101\\sharepoint SQL Server instance PS C:\\> Get-DbaErrorLog -SqlInstance sql01\\sharepoint -After '2016-11-14 00:00:00' Example 7: Returns every log entry found before the date 16 August 2016 from sql101\\sharepoint SQL Server instance PS C:\\> Get-DbaErrorLog -SqlInstance sql01\\sharepoint -Before '2016-08-16 00:00:00' Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this to target specific log files when troubleshooting issues from a particular time period or to avoid reading all logs for performance. SQL Server keeps 6 log files by default but can be configured up to 99 archived logs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Source Filters log entries by the source component that generated the message, such as \"Logon\", \"Server\", \"Backup\", or \"spid123\". Use this to focus on specific SQL Server subsystems when troubleshooting authentication issues, backup problems, or tracking activity from particular processes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Text Searches for log entries containing specific text patterns using wildcard matching (supports wildcards). Use this to find specific error messages, user names, database names, or any text string within log entries for targeted troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -After Returns only log entries that occurred after the specified date and time. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Before Returns only log entries that occurred before the specified date and time. Use this to investigate historical issues, exclude recent events from analysis, or focus on problems that existed prior to a specific incident or change. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.LogFileEntry Returns 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 (newest logs first) to prioritize recent activity. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) LogDate: The date and time when the log entry was created (DateTime) Source: The process ID or source component that created the entry (e.g., spid123, Backup, Logon) Text: The full text content of the log entry message Additional properties available (from SMO LogFileEntry object): ProcessInfo: The raw process identifier or source component (same as Source but without aliasing) All properties from the base SMO object are accessible even though only default properties are displayed without using Select-Object . &nbsp;"
  },
  {
    "name": "Get-DbaErrorLogConfig",
    "description": "Retrieves current error log configuration from SQL Server instances, showing how many log files are retained, where they're 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.",
    "category": "Server Management",
    "tags": [
      "instance",
      "errorlog",
      "logging"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaErrorLogConfig",
    "popularityRank": 464,
    "synopsis": "Retrieves SQL Server error log configuration settings including file count, size limits, and storage location",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaErrorLogConfig View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server error log configuration settings including file count, size limits, and storage location Description Retrieves current error log configuration from SQL Server instances, showing how many log files are retained, where they're 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. Syntax Get-DbaErrorLogConfig [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns error log configuration for server2017 and server2014 PS C:\\> Get-DbaErrorLogConfig -SqlInstance server2017,server2014 Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance with error log configuration details. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) LogCount: The number of error log files retained by SQL Server (integer) 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 LogPath: The file system directory path where error log files are stored (string) &nbsp;"
  },
  {
    "name": "Get-DbaEstimatedCompletionTime",
    "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'll 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't 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's 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",
    "category": "Utilities",
    "tags": [
      "diagnostic",
      "query"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaEstimatedCompletionTime",
    "popularityRank": 361,
    "synopsis": "Monitors progress and estimated completion times for long-running SQL Server operations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaEstimatedCompletionTime View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Monitors progress and estimated completion times for long-running SQL Server operations 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'll complete or manually check SQL Server Management Studio. Shows 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't appear in the results. Percent complete will show for the following commands: ALTER INDEX REORGANIZE AUTO_SHRINK option with ALTER DATABASE BACKUP DATABASE DBCC CHECKDB DBCC CHECKFILEGROUP DBCC CHECKTABLE DBCC INDEXDEFRAG DBCC SHRINKDATABASE DBCC SHRINKFILE RECOVERY RESTORE DATABASE ROLLBACK TDE ENCRYPTION Particularly useful during scheduled maintenance windows, large database restores, or when troubleshooting performance issues where you need visibility into what's currently running and how much longer it will take. For 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 Syntax Get-DbaEstimatedCompletionTime [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets estimated completion times for queries performed against the entire server PS C:\\> Get-DbaEstimatedCompletionTime -SqlInstance sql2016 Example 2: Gets estimated completion times for queries performed against the entire server PLUS the SQL query text of... PS C:\\> Get-DbaEstimatedCompletionTime -SqlInstance sql2016 | Select-Object Gets estimated completion times for queries performed against the entire server PLUS the SQL query text of each command Example 3: Gets results for commands whose queries only match specific text (match is like LIKE but way more powerful) PS C:\\> Get-DbaEstimatedCompletionTime -SqlInstance sql2016 | Where-Object { $_.Text -match 'somequerytext' } Example 4: Gets estimated completion times for queries performed against the Northwind, pubs, and Adventureworks2014... PS C:\\> Get-DbaEstimatedCompletionTime -SqlInstance sql2016 -Database Northwind,pubs,Adventureworks2014 Gets estimated completion times for queries performed against the Northwind, pubs, and Adventureworks2014 databases Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Filters results to show only long-running operations within the specified database(s). Accepts multiple database names or wildcards. Use this when you need to monitor specific databases during maintenance windows or troubleshoot performance issues in particular databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes long-running operations from the specified database(s) when monitoring across the entire instance. Helpful when you want to monitor all databases except system databases or exclude databases with known maintenance operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Default display properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database where the operation is running Login: The login/user who initiated the operation Command: The command being executed (BACKUP, RESTORE, DBCC CHECKDB, ALTER INDEX, etc.) PercentComplete: The percentage of completion (0-100) StartTime: DateTime when the operation started RunningTime: Elapsed time formatted as HH:MM:SS EstimatedTimeToGo: Estimated remaining time formatted as HH:MM:SS EstimatedCompletionTime: Projected completion DateTime Additional properties available: Text: The T-SQL query text (excluded from default view, use Select-Object to display) Only operations supporting progress tracking show completion estimates. Quick queries and standard SELECT statements won't appear in results. &nbsp;"
  },
  {
    "name": "Get-DbaExecutionPlan",
    "description": "Retrieves execution plans from SQL Server's 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/",
    "category": "Performance",
    "tags": [
      "performance"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaExecutionPlan",
    "popularityRank": 341,
    "synopsis": "Retrieves cached execution plans and metadata from SQL Server's plan cache",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaExecutionPlan View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves cached execution plans and metadata from SQL Server's plan cache Description Retrieves execution plans from SQL Server's 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. The 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. The 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. Thanks to following for the queries: https://www.simple-talk.com/sql/t-sql-programming/dmvs-for-query-plan-metadata/ http://www.scarydba.com/2017/02/13/export-plans-cache-sqlplan-file/ Syntax Get-DbaExecutionPlan [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-SinceCreation] ] [[-SinceLastExecution] ] [-ExcludeEmptyQueryPlan] [-Force] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all execution plans on sqlserver2014a PS C:\\> Get-DbaExecutionPlan -SqlInstance sqlserver2014a Example 2: Gets all execution plans for databases db1 and db2 on sqlserver2014a since July 1, 2016 at 10:47 AM PS C:\\> Get-DbaExecutionPlan -SqlInstance sqlserver2014a -Database db1, db2 -SinceLastExecution '2016-07-01 10:47:00' Example 3: Gets execution plan info for all databases except db1 on sqlserver2014a and sql2016 and makes the output... PS C:\\> Get-DbaExecutionPlan -SqlInstance sqlserver2014a, sql2016 -Exclude db1 | Format-Table Gets execution plan info for all databases except db1 on sqlserver2014a and sql2016 and makes the output pretty Example 4: Gets super detailed information for execution plans on only for AdventureWorks2014 and pubs PS C:\\> Get-DbaExecutionPlan -SqlInstance sql2014 -Database AdventureWorks2014, pubs -Force Example 5: Gets super detailed information for execution plans on sqlserver2014a and sql2016 PS C:\\> $servers = \"sqlserver2014a\",\"sql2016t\" PS C:\\> $servers | Get-DbaExecutionPlan -Force Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to include when retrieving execution plans from the plan cache. Use this to focus performance analysis on specific databases instead of scanning all databases on the instance. Accepts multiple database names and supports wildcards for pattern matching. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to exclude when retrieving execution plans from the plan cache. Useful when you want to analyze most databases but skip system databases like tempdb or specific application databases. Accepts multiple database names for flexible filtering. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SinceCreation Filters execution plans to only those created on or after the specified date and time. Use this to focus on recent query plan changes after deployments, index modifications, or statistics updates. Helps identify new execution plans that may be causing performance issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SinceLastExecution Filters execution plans to only those executed on or after the specified date and time. Essential for identifying recently active queries when troubleshooting current performance problems. Excludes older cached plans that are no longer being used by applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeEmptyQueryPlan Excludes execution plans that have null or empty XML query plan data. Use this to focus only on plans with complete execution plan information for detailed performance analysis. Helps avoid incomplete results when you need the actual query plan XML for troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Returns all available columns from the Dynamic Management Views instead of the standard curated output. Use this when you need access to additional execution statistics, compilation details, or other raw plan cache data. Provides comprehensive information for advanced performance analysis and troubleshooting scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject (default) Returns 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. Default display properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: The database name where the query executes ObjectName: The object name (procedure, function, or NULL for ad-hoc queries) QueryPosition: Row number ordering statements within a batch SqlHandle: Hexadecimal representation of the SQL handle for the query PlanHandle: Hexadecimal representation of the plan handle CreationTime: DateTime when the execution plan was created LastExecutionTime: DateTime when the plan was last executed StatementCondition: XML node containing statement conditions StatementSimple: XML node for simple statements StatementId: Statement identifier within the batch StatementCompId: Statement compilation ID StatementType: Type of statement (SELECT, INSERT, UPDATE, DELETE, etc.) RetrievedFromCache: Boolean indicating if plan was retrieved from cache StatementSubTreeCost: Estimated subtree cost (decimal) StatementEstRows: Estimated number of rows returned (int/decimal) SecurityPolicyApplied: Boolean indicating if Row-Level Security policy was applied StatementOptmLevel: Optimization level (int) QueryHash: Hashed identifier for the query text QueryPlanHash: Hashed identifier for the query plan StatementOptmEarlyAbortReason: Reason for early optimization abort if applicable CardinalityEstimationModelVersion: Cardinality estimation version used (int) ParameterizedText: Parameterized version of the query text StatementSetOptions: SET options active during statement compilation QueryPlan: XML node containing the execution plan tree structure BatchConditionXml: XML node for batch-level conditions BatchSimpleXml: XML node for batch-level simple statements Additional properties available (excluded from default view): BatchQueryPlanRaw: Complete batch-level query plan as XML object SingleStatementPlanRaw: Single statement plan as XML object PlanWarnings: Plan warnings and advice if applicable System.Data.DataTable (when -Force is specified) Returns 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 available execution statistics, compilation details, and metadata for advanced analysis. &nbsp;"
  },
  {
    "name": "Get-DbaExtendedProperty",
    "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.",
    "category": "Utilities",
    "tags": [
      "general",
      "extendedproperty"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaExtendedProperty",
    "popularityRank": 352,
    "synopsis": "Retrieves custom metadata and documentation stored as extended properties on SQL Server objects",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaExtendedProperty View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves custom metadata and documentation stored as extended properties on SQL Server objects 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. This 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. Works 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. Perfect for discovering undocumented business logic, finding objects with compliance tags, or building comprehensive database documentation reports from existing metadata. Syntax Get-DbaExtendedProperty [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Name] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all extended properties on all databases PS C:\\> Get-DbaExtendedProperty -SqlInstance sql2016 Example 2: Gets the extended properties for the db1 database PS C:\\> Get-DbaExtendedProperty -SqlInstance Server1 -Database db1 Example 3: Gets the info1 and info2 extended properties within the db1 database PS C:\\> Get-DbaExtendedProperty -SqlInstance Server1 -Database db1 -Name info1, info2 Example 4: Get the extended properties for all stored procedures in the tempdb database PS C:\\> Get-DbaDbStoredProcedure -SqlInstance localhost -Database tempdb | Get-DbaExtendedProperty Example 5: Get the extended properties for the mytable table in the mydb database PS C:\\> Get-DbaDbTable -SqlInstance localhost -Database mydb -Table mytable | Get-DbaExtendedProperty Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for extended properties. Only applies when connecting directly to SqlInstance. Use this when you need to examine extended properties from specific databases rather than all accessible databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Filters results to extended properties with specific names. Accepts multiple property names. Use this when you know the exact property names you're looking for, such as finding all objects tagged with 'Description' or 'Version' properties. | Property | Value | | --- | --- | | Alias | Property | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts SQL Server objects piped from other dbatools commands to examine their extended properties. Use this to discover metadata on specific objects like tables, stored procedures, or views returned from commands like Get-DbaDbTable or Get-DbaDbStoredProcedure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.ExtendedProperty Returns 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 level. When piping objects from other dbatools commands, extended properties from those specific objects are returned. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ParentName: Name of the SQL Server object that owns this extended property Type: The type name of the parent object (e.g., Database, Table, StoredProcedure, Column) Name: The name of the extended property Value: The value or content of the extended property (can be any string data) Additional properties available (from SMO ExtendedProperty object): Parent: Reference to the parent SQL Server object Urn: The Uniform Resource Name of the extended property Properties: Collection of property objects State: The current state of the SMO object (Existing, Creating, Pending, etc.) The Server property added by this command contains the connection object for programmatic access to the parent SQL Server instance. &nbsp;"
  },
  {
    "name": "Get-DbaExtendedProtection",
    "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 > 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.",
    "category": "Server Management",
    "tags": [
      "instance",
      "security"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaExtendedProtection",
    "popularityRank": 598,
    "synopsis": "Retrieves Extended Protection authentication settings from SQL Server network configuration.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaExtendedProtection View Source Claudio Silva (@claudioessilva), claudioessilva.eu Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Extended Protection authentication settings from SQL Server network configuration. 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. This 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 > Protocols properties, but can be checked programmatically across multiple instances for compliance auditing. Returns 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. Syntax Get-DbaExtendedProtection [[-SqlInstance] ] [[-Credential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Gets Extended Protection on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs... PS C:\\> Get-DbaExtendedProtection Gets Extended Protection on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin. Example 2: Set Extended Protection of SQL Engine for the SQL2008R2SP2 on sql01 to &quot;Off&quot; PS C:\\> Get-DbaExtendedProtection -SqlInstance sql01\\SQL2008R2SP2 Set Extended Protection of SQL Engine for the SQL2008R2SP2 on sql01 to \"Off\". Uses Windows Credentials to both connect and modify the registry. Gets Extended Protection for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and view the registry. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $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. Required when your current Windows account lacks administrative privileges on the target server or when connecting across domains. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per instance containing the current Extended Protection setting and its interpretation. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) 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\" (e.g., \"1 - Allowed\") &nbsp;"
  },
  {
    "name": "Get-DbaExternalProcess",
    "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/",
    "category": "Utilities",
    "tags": [
      "diagnostic",
      "process"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaExternalProcess",
    "popularityRank": 533,
    "synopsis": "Retrieves operating system processes spawned by SQL Server instances",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaExternalProcess View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves operating system processes spawned by SQL Server instances 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. This 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. The 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. https://web.archive.org/web/20201027122300/http://vickyharp.com/2013/12/killing-sessions-with-external-wait-types/ Syntax Get-DbaExternalProcess [-ComputerName] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets OS processes created by SQL Server on SERVER01 and SERVER02 PS C:\\> Get-DbaExternalProcess -ComputerName SERVER01, SERVER02 Required Parameters -ComputerName Specifies the SQL Server host computer(s) to check for external processes spawned by SQL Server. Use this when troubleshooting hung sessions or investigating resource usage from processes like xp_cmdshell, BCP, or SSIS operations. Accepts multiple computer names and SQL Server instance names with automatic computer resolution. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Allows you to login to $ComputerName using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties: ComputerName: The name of the computer where the SQL Server process resides ProcessId: The operating system process ID of the child process (unsigned integer) Name: The executable name of the child process (e.g., cmd.exe, bcp.exe, DTExec.exe) HandleCount: The number of open handles held by the child process (unsigned integer) WorkingSetSize: Memory currently in use by the child process in bytes (unsigned long) VirtualSize: Total virtual address space reserved by the child process in bytes (unsigned long) CimObject: The underlying WMI process object providing full access to all Win32_Process properties Credential: The credential object used for the WMI connection (this property is typically not useful for analysis) &nbsp;"
  },
  {
    "name": "Get-DbaFeature",
    "description": "Executes SQL Server's 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's (@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.",
    "category": "Utilities",
    "tags": [
      "feature",
      "component",
      "general"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaFeature",
    "popularityRank": 220,
    "synopsis": "Discovers installed SQL Server features and components across multiple servers",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaFeature View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Discovers installed SQL Server features and components across multiple servers Description Executes SQL Server's 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. The 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. Inspired by Dave Mason's (@BeginTry) post at https://itsalljustelectrons.blogspot.be/2018/04/SQL-Server-Discovery-Report.html Assumptions: 1. The sub-folder \"Microsoft SQL Server\" exists in [System.Environment]::GetFolderPath(\"ProgramFiles\"), even if SQL was installed to a non-default path. This has been verified on SQL 2008R2 and SQL 2012. Further verification may be needed. 2. The discovery report displays installed components for the version of SQL Server associated with setup.exe, along with installed components of all lesser versions of SQL Server that are installed. Syntax Get-DbaFeature [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all SQL Server features for all instances on sql2017, sql2016 and sql2005 PS C:\\> Get-DbaFeature -ComputerName sql2017, sql2016, sql2005 Example 2: Gets all SQL Server features for all instances on localhost PS C:\\> Get-DbaFeature -Verbose Gets all SQL Server features for all instances on localhost. Outputs to screen if no instances are found. Example 3: Gets all SQL Server features for all instances on sql2017 using the ad\\sqladmin credential (which has access... PS C:\\> Get-DbaFeature -ComputerName sql2017 -Credential ad\\sqldba Gets all SQL Server features for all instances on sql2017 using the ad\\sqladmin credential (which has access to the Windows Server). Optional Parameters -ComputerName Specifies the Windows computer names where you want to discover SQL Server features and components. Accepts multiple computers for bulk discovery operations. Use this when you need to inventory SQL Server installations across your environment for compliance auditing or license tracking. Requires PowerShell remoting to be enabled on remote computers. Note that this targets the Windows host, not SQL instance names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to servers using alternative credentials. To use: $cred = Get-Credential, then pass $cred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 server(s). Properties: ComputerName: The name of the Windows server where SQL Server is installed Product: The SQL Server product name (e.g., \"SQL Server 2019 Enterprise Edition\") Instance: The SQL Server instance name, or \"MSSQLSERVER\" for the default instance InstanceID: The SQL Server instance ID identifier from the registry Feature: The specific SQL Server component that is installed (e.g., Database Engine, Analysis Services, Reporting Services, Integration Services, Replication, Full-Text Search) Language: The language/locale of the SQL Server installation (e.g., \"English\") Edition: The SQL Server edition (Enterprise, Standard, Express, Developer, Evaluation, Web) Version: The version number of SQL Server in format (e.g., \"15.0.2000.5\") Clustered: Boolean indicating if this SQL Server instance is part of a failover cluster (True/False) Configured: Boolean indicating if the SQL Server component is fully configured and operational (True/False) Each row represents one installed feature. A single SQL Server instance with multiple installed features will generate multiple objects. &nbsp;"
  },
  {
    "name": "Get-DbaFile",
    "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's 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",
    "category": "Utilities",
    "tags": [
      "storage",
      "file",
      "path"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaFile",
    "popularityRank": 184,
    "synopsis": "Enumerates files and directories on remote SQL Server instances using xp_dirtree",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaFile View Source Brandon Abshire, netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Enumerates files and directories on remote SQL Server instances using xp_dirtree 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's data directory but accepts additional paths for comprehensive file system exploration. Common use cases include locating orphaned database files, finding backup files for restores, auditing disk usage, and preparing for file migrations. You 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. Thanks to serg-52 for the query: https://www.sqlservercentral.com/Forums/Topic1642213-391-1.aspx Syntax Get-DbaFile [-SqlInstance] [[-SqlCredential] ] [[-Path] ] [[-FileType] ] [[-Depth] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Logs into the SQL Server &quot;sqlserver2014a&quot; using Windows credentials and searches E:\\Dir for all files PS C:\\> Get-DbaFile -SqlInstance sqlserver2014a -Path E:\\Dir1 Example 2: Logs into the SQL Server &quot;sqlserver2014a&quot; using alternative credentials and returns all files in &#39;E:\\sql... PS C:\\> Get-DbaFile -SqlInstance sqlserver2014a -SqlCredential $cred -Path 'E:\\sql files' Logs into the SQL Server \"sqlserver2014a\" using alternative credentials and returns all files in 'E:\\sql files' Example 3: Returns the files in the default data, log and backup directories on sql2014, 3 directories deep... PS C:\\> $all = Get-DbaDefaultPath -SqlInstance sql2014 PS C:\\> Get-DbaFile -SqlInstance sql2014 -Path $all.Data, $all.Log, $all.Backup -Depth 3 Returns the files in the default data, log and backup directories on sql2014, 3 directories deep (recursively). Example 4: Returns the files in &quot;E:\\Dir1&quot; and &quot;E:Dir2&quot; on sql2014 PS C:\\> Get-DbaFile -SqlInstance sql2014 -Path 'E:\\Dir1', 'E:\\Dir2' Example 5: Finds files in E:\\Dir1 ending with &quot;.fsf&quot; and &quot;.mld&quot; for both the servers sql2014 and sql2016 PS C:\\> Get-DbaFile -SqlInstance sql2014, sql2016 -Path 'E:\\Dir1' -FileType fsf, mld Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Allows you to login to servers using alternative credentials | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies additional directory paths to search beyond the instance's default data directory. Accepts multiple paths as an array. Use this when you need to scan specific locations for orphaned files, backup locations, or custom database file directories. Defaults to the instance's data directory if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileType Filters results to only show files with specific extensions. Pass extensions without the dot (e.g., 'mdf', 'ldf', 'bak'). Use this to find specific database files like data files (mdf, ndf), log files (ldf), or backup files (bak, trn). Accepts multiple extensions to search for different file types simultaneously. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Depth Controls how many subdirectory levels to search recursively. Default is 1 (current directory only). Increase this value when searching deep folder structures for scattered database files or backup archives. Higher values take more time but ensure comprehensive file discovery across complex directory trees. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per file found in the specified directories across all target instances. Default display properties (via Select-DefaultView): Filename: The full path of the file on the target server (with path separators adapted for the host OS) *Additional properties available (via Select-Object ):** ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) RemoteFilename: The UNC path to the file for remote access (\\\\ComputerName\\share\\path) &nbsp;"
  },
  {
    "name": "Get-DbaFilestream",
    "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.",
    "category": "Utilities",
    "tags": [
      "filestream"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaFilestream",
    "popularityRank": 616,
    "synopsis": "Retrieves FileStream configuration status at both the SQL Server service and instance levels.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaFilestream View Source Stuart Moore (@napalmgram) , Chrissy LeMaire (@cl) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves FileStream configuration status at both the SQL Server service and instance levels. 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. Syntax Get-DbaFilestream [[-SqlInstance] ] [[-SqlCredential] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Will return the status of Filestream configuration for the service and instance server1\\instance2 PS C:\\> Get-DbaFilestream -SqlInstance server1\\instance2 Example 2: Prompts for the password to the SQL Login &quot;sqladmin&quot; then returns the status of Filestream configuration for... PS C:\\> Get-DbaFilestream -SqlInstance server1\\instance2 -SqlCredential sqladmin Prompts for the password to the SQL Login \"sqladmin\" then returns the status of Filestream configuration for the service and instance server1\\instance2 Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Login to the target Windows server using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per instance queried, containing both service-level and instance-level FileStream configuration status. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) InstanceAccess: Human-readable description of instance-level FileStream access (Disabled, T-SQL access enabled, or Full access enabled) 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 enabled for T-SQL, IO streaming, and remote clients) ServiceShareName: The Windows file share name used for FileStream when service-level access is enabled *Additional properties available (via Select-Object ):** InstanceAccessLevel: Numeric code for instance-level FileStream access (0-2) ServiceAccessLevel: Numeric code for service-level FileStream access (0-3) Credential: The Windows credentials used for service-level queries (passed from -Credential parameter) SqlCredential: The SQL Server credentials used for instance-level queries (passed from -SqlCredential parameter) &nbsp;"
  },
  {
    "name": "Get-DbaFirewallRule",
    "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.",
    "category": "Utilities",
    "tags": [
      "network",
      "connection",
      "firewall"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaFirewallRule",
    "popularityRank": 306,
    "synopsis": "Retrieves Windows firewall rules for SQL Server components from target computers for network troubleshooting and security auditing.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaFirewallRule View Source Andreas Jordan (@JordanOrdix), ordix.de Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows firewall rules for SQL Server components from target computers for network troubleshooting and security auditing. 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. Most 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. This 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. The functionality is currently limited. Help to extend the functionality is welcome. As long as you can read this note here, there may be breaking changes in future versions. So please review your scripts using this command after updating dbatools. Syntax Get-DbaFirewallRule [-SqlInstance] [[-Credential] ] [[-Type] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the firewall rule for the default instance on SRV1 PS C:\\> Get-DbaFirewallRule -SqlInstance SRV1 Returns the firewall rule for the default instance on SRV1. In case the instance is not listening on port 1433, it also returns the firewall rule for the SQL Server Browser. Example 2: Returns only the firewall rule for the instance SQL2016 on SRV1 PS C:\\> Get-DbaFirewallRule -SqlInstance SRV1\\SQL2016 -Type Engine Example 3: Both commands return the firewall rule for the SQL Serer Browser on SRV1 PS C:\\> Get-DbaFirewallRule -SqlInstance SRV1\\SQL2016 -Type Browser PS C:\\> Get-DbaFirewallRule -SqlInstance SRV1 -Type Browser Both commands return the firewall rule for the SQL Serer Browser on SRV1. As the Browser is not bound to a specific instance, only the computer part of SqlInstance is used. Example 4: Returns all firewall rules on the computer SRV1 related to SQL Server PS C:\\> Get-DbaFirewallRule -SqlInstance SRV1\\SQL2016 -Type AllInstance Returns all firewall rules on the computer SRV1 related to SQL Server. The value \"AllInstance\" only uses the computer name part of SqlInstance. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Credential object used to connect to the Computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies which SQL Server firewall rule types to retrieve from the target computer. Use this when you need to focus on specific SQL Server components during network troubleshooting or security audits. Valid values are: Engine - Returns firewall rules for the SQL Server Database Engine service Browser - Returns firewall rules for the SQL Server Browser service (UDP 1434) DAC - Returns firewall rules for the Dedicated Admin Connection DatabaseMirroring - Returns firewall rules for database mirroring or Availability Groups AllInstance - Returns all SQL Server-related firewall rules on the target computer When omitted, returns Engine and DAC rules for the specified instance, plus Browser rules if the instance uses a non-standard port. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one firewall rule object per matching SQL Server firewall rule on the target computer. Each object contains details about the rule's protocol, port, and program path. Default properties returned: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name (null for Browser rules) SqlInstance: The full SQL Server instance name (computer\\instance format; null for Browser) DisplayName: The display name of the firewall rule Type: Category of rule (Engine, Browser, DAC, or DatabaseMirroring) Protocol: Protocol type used by the rule (TCP, UDP, etc.) LocalPort: The port number(s) the rule applies to Program: The executable path allowed through the firewall Additional properties available: Name: The internal name of the firewall rule Rule: The raw Get-NetFirewallRule object with all native properties Credential: The credential object used for execution When an error occurs during remote execution, an error object is returned instead with: ComputerName: The target computer name Warning: Any warning messages from Get-NetFirewallRule Error: Error message details if the operation failed Exception: The exception object containing full error information Details: Full diagnostic information from the remote execution &nbsp;"
  },
  {
    "name": "Get-DbaForceNetworkEncryption",
    "description": "Retrieves the Force Network Encryption setting and associated certificate from SQL Server's 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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaForceNetworkEncryption",
    "popularityRank": 443,
    "synopsis": "Retrieves Force Network Encryption configuration from SQL Server's network settings",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaForceNetworkEncryption View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Force Network Encryption configuration from SQL Server's network settings Description Retrieves the Force Network Encryption setting and associated certificate from SQL Server's network configuration stored in the Windows registry. This setting determines whether SQL Server requires all client connections to use encryption, preventing unencrypted communication. Useful 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. Syntax Get-DbaForceNetworkEncryption [[-SqlInstance] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets Force Encryption properties on the default (MSSQLSERVER) instance on localhost - requires (and checks... PS C:\\> Get-DbaForceNetworkEncryption Gets Force Encryption properties on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin. Example 2: Gets Force Network Encryption for the SQL2008R2SP2 on sql01 PS C:\\> Get-DbaForceNetworkEncryption -SqlInstance sql01\\SQL2008R2SP2 Gets Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and view the registry. Optional Parameters -SqlInstance The target SQL Server instance or instances. Defaults to localhost. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the computer (not sql instance) using alternative Windows credentials | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance with the Force Network Encryption configuration details. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) ForceEncryption: Boolean indicating whether Force Network Encryption is enabled on the instance CertificateThumbprint: The SHA-1 thumbprint of the certificate used for encryption, or $null if no certificate is configured &nbsp;"
  },
  {
    "name": "Get-DbaHelpIndex",
    "description": "This function queries SQL Server DMVs to return detailed index and statistics information for performance analysis, index maintenance planning, and identifying optimization opportunities. You can target all indexes in a database or focus on a specific table to analyze index usage patterns, sizes, and fragmentation levels.\n\nEssential for DBAs performing index tuning, this command helps identify unused indexes for removal, oversized indexes consuming storage, and indexes requiring maintenance based on fragmentation or usage statistics. The data combines structural information (key columns, include columns, filters) with runtime metrics (reads, updates, last used) to provide a complete index health picture.\n\nUses SQL Server DMVs and system tables, requiring SQL Server 2008 or later.\n\nThe data includes:\n- ObjectName: the table containing the index\n- IndexType: clustered/non-clustered/columnstore and whether the index is unique/primary key\n- KeyColumns: the key columns of the index\n- IncludeColumns: any include columns in the index\n- FilterDefinition: any filter that may have been used in the index\n- DataCompression: row/page/none depending upon whether or not compression has been used\n- IndexReads: the number of reads of the index since last restart or index rebuild\n- IndexUpdates: the number of writes to the index since last restart or index rebuild\n- SizeKB: the size the index in KB\n- IndexRows: the number of the rows in the index (note filtered indexes will have fewer rows than exist in the table)\n- IndexLookups: the number of lookups that have been performed (only applicable for the heap or clustered index)\n- MostRecentlyUsed: when the index was most recently queried (default to 1900 for when never read)\n- StatsSampleRows: the number of rows queried when the statistics were built/rebuilt\n- StatsRowMods: the number of changes to the statistics since the last rebuild\n- HistogramSteps: the number of steps in the statistics histogram\n- StatsLastUpdated: when the statistics were last rebuilt",
    "category": "Database Operations",
    "tags": [
      "database",
      "index"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaHelpIndex",
    "popularityRank": 110,
    "synopsis": "Retrieves comprehensive index and statistics information from SQL Server databases for performance analysis and optimization.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaHelpIndex View Source Nic Cain, sirsql.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves comprehensive index and statistics information from SQL Server databases for performance analysis and optimization. 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. Essential 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. Uses SQL Server DMVs and system tables, requiring SQL Server 2008 or later. The data includes: ObjectName: the table containing the index IndexType: clustered/non-clustered/columnstore and whether the index is unique/primary key KeyColumns: the key columns of the index IncludeColumns: any include columns in the index FilterDefinition: any filter that may have been used in the index DataCompression: row/page/none depending upon whether or not compression has been used IndexReads: the number of reads of the index since last restart or index rebuild IndexUpdates: the number of writes to the index since last restart or index rebuild SizeKB: the size the index in KB IndexRows: the number of the rows in the index (note filtered indexes will have fewer rows than exist in the table) IndexLookups: the number of lookups that have been performed (only applicable for the heap or clustered index) MostRecentlyUsed: when the index was most recently queried (default to 1900 for when never read) StatsSampleRows: the number of rows queried when the statistics were built/rebuilt StatsRowMods: the number of changes to the statistics since the last rebuild HistogramSteps: the number of steps in the statistics histogram StatsLastUpdated: when the statistics were last rebuilt Syntax Get-DbaHelpIndex [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-InputObject] ] [[-ObjectName] ] [-IncludeStats] [-IncludeDataTypes] [-Raw] [-IncludeFragmentation] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns information on all indexes on the MyDB database on the localhost PS C:\\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB Example 2: Returns information on all indexes on the MyDB &amp; MyDB2 databases PS C:\\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB,MyDB2 Example 3: Returns index information on the object dbo.Table1 in the database MyDB PS C:\\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 Example 4: Returns information on the indexes and statistics for the table dbo.Table1 in the MyDB database PS C:\\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -IncludeStats Example 5: Returns the index information for the table dbo.Table1 in the MyDB database, and includes the data types for... PS C:\\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -IncludeDataTypes Returns the index information for the table dbo.Table1 in the MyDB database, and includes the data types for the key and include columns. Example 6: Returns the index information for the table dbo.Table1 in the MyDB database, and returns the numerical data... PS C:\\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -ObjectName dbo.Table1 -Raw Returns the index information for the table dbo.Table1 in the MyDB database, and returns the numerical data without localized separators. Example 7: Returns the index information for all indexes in the MyDB database as well as their statistics, and formats... PS C:\\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -IncludeStats -Raw Returns the index information for all indexes in the MyDB database as well as their statistics, and formats the numerical data without localized separators. Example 8: Returns the index information for all indexes in the MyDB database as well as their fragmentation PS C:\\> Get-DbaHelpIndex -SqlInstance localhost -Database MyDB -IncludeFragmentation Example 9: Returns the index information for all indexes in the MyDB database PS C:\\> Get-DbaDatabase -SqlInstance sql2017 -Database MyDB | Get-DbaHelpIndex Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for index and statistics information. Accepts multiple database names and wildcard patterns. Use this when you need to focus your analysis on specific databases rather than scanning the entire instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Databases to skip during the index analysis process. Useful for excluding system databases or databases currently under maintenance. Commonly used to exclude tempdb or databases that are offline or in restoring state. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase for pipeline processing. Enables filtering databases first, then analyzing only the indexes on those specific databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -ObjectName Targets index analysis to a specific table using either single name (uses default schema) or two-part naming like 'schema.table'. Essential when troubleshooting performance issues on a specific table or when you need detailed statistics information on SQL Server 2005 instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeStats Returns statistics objects in addition to indexes, providing complete picture of query optimization structures. Use this when analyzing query plan issues or determining which statistics might be missing or stale for specific tables. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeDataTypes Adds data type information for all key and include columns in the index definitions. Helpful when analyzing index key size, planning composite indexes, or understanding why certain indexes might be inefficient. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Raw Returns numeric values without formatting (no thousands separators) and Size as a dbasize object. Use this when feeding results into other functions or when you need precise numeric values for calculations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeFragmentation Adds fragmentation percentage data by querying sys.dm_db_index_physical_stats with DETAILED mode. Critical for index maintenance planning but significantly increases execution time on large databases with many indexes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 maintenance characteristics. Default properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the index Object: The table containing the index (schema.table format) Index: The name of the index; empty string for statistics-only rows Statistics: The name of the statistics object; null for index rows IndexType: Type of index structure (Clustered Index, Nonclustered Index, Heap) with optional qualifiers (PRIMARY KEY, UNIQUE, UNIQUE CONSTRAINT) KeyColumns: Comma-separated list of key columns with optional DESC markers and data types (if -IncludeDataTypes) IncludeColumns: Comma-separated list of included columns with optional data types (if -IncludeDataTypes); empty string if none FilterDefinition: Filter predicate for filtered indexes; empty string if no filter FillFactor: Fill factor value (0-100) for the index; empty string for statistics rows DataCompression: Compression type (Row, Page, or ColumnStore); empty string for No Compression IndexReads: Numeric count of index seeks, scans, and lookups (formatted with thousands separators unless -Raw) IndexUpdates: Numeric count of index write operations (formatted with thousands separators unless -Raw) Size: Index size in kilobytes; formatted as N0 unless -Raw (then dbasize object) (formatted with thousands separators unless -Raw); empty string for statistics rows IndexRows: Numeric row count in the index or statistics; formatted with thousands separators unless -Raw IndexLookups: Numeric count of lookup operations (only for heap or clustered index); empty string for statistics rows MostRecentlyUsed: DateTime of most recent index usage; null if never used (1900 year) or no usage data StatsSampleRows: Number of rows sampled when statistics were built/updated; empty for index rows StatsRowMods: Number of modifications to underlying data since last statistics update; empty for index rows HistogramSteps: Number of steps in the statistics histogram; empty for index rows StatsLastUpdated: DateTime when statistics were last updated; empty for index rows IndexFragInPercent: Fragmentation percentage (0-100 formatted as F2 decimal) of the index; only present when -IncludeFragmentation specified; empty string otherwise When -IncludeStats is specified, statistics-only objects are also returned with index-specific properties set to empty strings and statistics properties populated. When -Raw is specified, numeric values return as dbasize objects rather than formatted strings, enabling calculations and comparisons without string parsing. All properties are returned as strings in default mode for display formatting. Use -Raw for numeric calculations. &nbsp;"
  },
  {
    "name": "Get-DbaHideInstance",
    "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.",
    "category": "Server Management",
    "tags": [
      "instance",
      "security"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaHideInstance",
    "popularityRank": 582,
    "synopsis": "Retrieves the Hide Instance setting from SQL Server registry configuration",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaHideInstance View Source Tracy Boggiano @TracyBoggiano, databaseuperhero.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves the Hide Instance setting from SQL Server registry configuration 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. Syntax Get-DbaHideInstance [[-SqlInstance] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets Hide Instance properties on the default (MSSQLSERVER) instance on localhost - requires (and checks for)... PS C:\\> Get-DbaHideInstance Gets Hide Instance properties on the default (MSSQLSERVER) instance on localhost - requires (and checks for) RunAs admin. Example 2: Gets Force Network Encryption for the SQL2008R2SP2 on sql01 PS C:\\> Get-DbaHideInstance -SqlInstance sql01\\SQL2008R2SP2 Gets Force Network Encryption for the SQL2008R2SP2 on sql01. Uses Windows Credentials to both login and view the registry. Optional Parameters -SqlInstance The target SQL Server instance or instances. Defaults to localhost. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the computer (not sql instance) using alternative Windows credentials | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per instance containing the current Hide Instance setting. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) HideInstance: Boolean indicating if the instance is hidden from network discovery ($true if hidden, $false if visible) &nbsp;"
  },
  {
    "name": "Get-DbaInstalledPatch",
    "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.",
    "category": "Utilities",
    "tags": [
      "deployment",
      "updates",
      "patches"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaInstalledPatch",
    "popularityRank": 88,
    "synopsis": "Retrieves installed SQL Server patches from Windows Registry for patch compliance and audit reporting.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaInstalledPatch View Source Hiram Fleitas, @hiramfleitas, fleitasarts.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves installed SQL Server patches from Windows Registry for patch compliance and audit reporting. 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. Essential 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. To test if your build is up to date, use Test-DbaBuild. Syntax Get-DbaInstalledPatch [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets a list of SQL Server patches installed on HiramSQL1 and HiramSQL2 PS C:\\> Get-DbaInstalledPatch -ComputerName HiramSQL1, HiramSQL2 Example 2: Gets the SQL Server patches from a list of computers in C:\\Monitoring\\Servers.txt PS C:\\> Get-Content C:\\Monitoring\\Servers.txt | Get-DbaInstalledPatch Example 3: Gets the SQL Server patches from SRV1 and orders by date PS C:\\> Get-DbaInstalledPatch -ComputerName SRV1 | Sort-Object InstallDate.Date Gets the SQL Server patches from SRV1 and orders by date. Note that we use a special customizable date datatype for InstallDate so you'll need InstallDate.Date Optional Parameters -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. Use this to audit patch levels across multiple servers for compliance reporting or pre-upgrade planning. Defaults to the local computer when not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Credential object used to connect to the Computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 \"SQL\" anywhere in the name. Properties: ComputerName: The name of the computer where the patch was found Name: The display name of the patch as shown in Windows Registry (e.g., \"Hotfix for SQL Server 2019 (KB5012345)\") Version: The version number of the patch as stored in Registry InstallDate: The installation date converted to DbaDate type; use .Date property for date-only access or .DateTime for full datetime &nbsp;"
  },
  {
    "name": "Get-DbaInstanceAudit",
    "description": "Retrieves all configured SQL Server audit objects at the instance level, which define where security audit events are stored and how they're 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.",
    "category": "Security",
    "tags": [
      "audit",
      "security",
      "sqlaudit"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaInstanceAudit",
    "popularityRank": 169,
    "synopsis": "Retrieves SQL Server audit objects from instance-level security auditing configurations.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaInstanceAudit View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server audit objects from instance-level security auditing configurations. Description Retrieves all configured SQL Server audit objects at the instance level, which define where security audit events are stored and how they're 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. Syntax Get-DbaInstanceAudit [-SqlInstance] [[-SqlCredential] ] [[-Audit] ] [[-ExcludeAudit] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all Security Audits on the local default SQL Server instance PS C:\\> Get-DbaInstanceAudit -SqlInstance localhost Example 2: Returns all Security Audits for the local and sql2016 SQL Server instances PS C:\\> Get-DbaInstanceAudit -SqlInstance localhost, sql2016 Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Audit Specifies which audit objects to retrieve by name. Accepts multiple audit names to return only those specific audits. Use this when you need to check configuration or status for particular audits instead of retrieving all instance-level audits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeAudit Specifies which audit objects to exclude from results by name. Accepts multiple audit names to filter out unwanted audits. Use this when you want to retrieve most audits but skip specific ones, such as excluding test or temporary audits from compliance reports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Audit Returns one Audit object for each SQL Server audit configured at the instance level. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the SQL Server audit IsEnabled: Boolean indicating if the audit is currently enabled OnFailure: Action to take when an audit event cannot be written (Continue, Shutdown, FailOperation) MaximumFiles: Maximum number of audit files to retain MaximumFileSize: Maximum size for each audit file MaximumFileSizeUnit: Unit of measurement for MaximumFileSize (Megabyte, Gigabyte, Terabyte) MaximumRolloverFiles: Number of files to rollover before recycling the oldest file QueueDelay: Delay in milliseconds before flushing audit records to the audit target ReserveDiskSpace: Boolean indicating if disk space equal to MaximumFileSize is pre-allocated FullName: Full local file path where audit events are stored Additional properties available: RemoteFullName: Remote UNC path to the audit file location (\\\\computername\\c$\\path\\filename) FilePath: Directory path where audit files are stored FileName: Name of the audit file Enabled: Same as IsEnabled property All properties from the base SMO Audit object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaInstanceAuditSpecification",
    "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.",
    "category": "Security",
    "tags": [
      "audit",
      "security",
      "sqlaudit"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaInstanceAuditSpecification",
    "popularityRank": 427,
    "synopsis": "Retrieves server-level audit specifications from SQL Server instances for compliance and security monitoring",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaInstanceAuditSpecification View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves server-level audit specifications from SQL Server instances for compliance and security monitoring 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. Syntax Get-DbaInstanceAuditSpecification [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all Security Audit Specifications on the local default SQL Server instance PS C:\\> Get-DbaInstanceAuditSpecification -SqlInstance localhost Example 2: Returns all Security Audit Specifications for the local and sql2016 SQL Server instances PS C:\\> Get-DbaInstanceAuditSpecification -SqlInstance localhost, sql2016 Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.ServerAuditSpecification Returns one ServerAuditSpecification object for each server-level audit specification configured on the SQL Server instance. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ID: Unique identifier for the server audit specification within the instance Name: The name of the server audit specification AuditName: The name of the SQL Server Audit that this specification is associated with Enabled: Boolean indicating if the audit specification is currently enabled CreateDate: DateTime when the audit specification was created DateLastModified: DateTime when the audit specification was last modified Guid: Globally unique identifier for the audit specification All properties from the base SMO ServerAuditSpecification object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaInstanceInstallDate",
    "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.",
    "category": "Server Management",
    "tags": [
      "install",
      "instance",
      "utility"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaInstanceInstallDate",
    "popularityRank": 357,
    "synopsis": "Retrieves SQL Server installation dates by querying system tables for compliance auditing and infrastructure tracking.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaInstanceInstallDate View Source Mitchell Hamann (@SirCaptainMitch), mitchellhamann.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server installation dates by querying system tables for compliance auditing and infrastructure tracking. 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. Syntax Get-DbaInstanceInstallDate [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [-IncludeWindows] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns an object with SQL Instance Install date as a string PS C:\\> Get-DbaInstanceInstallDate -SqlInstance SqlBox1\\Instance2 Example 2: Returns an object with SQL Instance Install date as a string for both SQLInstances that are passed to the... PS C:\\> Get-DbaInstanceInstallDate -SqlInstance winserver\\sqlexpress, sql2016 Returns an object with SQL Instance Install date as a string for both SQLInstances that are passed to the cmdlet. Example 3: Returns an object with SQL Instance Install date as a string for both SQLInstances that are passed to the... PS C:\\> 'sqlserver2014a', 'sql2016' | Get-DbaInstanceInstallDate Returns an object with SQL Instance Install date as a string for both SQLInstances that are passed to the cmdlet via the pipeline. Example 4: Returns an object with the Windows Install date and the SQL install date as a string PS C:\\> Get-DbaInstanceInstallDate -SqlInstance sqlserver2014a, sql2016 -IncludeWindows Example 5: Returns an object with SQL Instance install date as a string for every server listed in the Central... PS C:\\> Get-DbaRegServer -SqlInstance sql2014 | Get-DbaInstanceInstallDate Returns an object with SQL Instance install date as a string for every server listed in the Central Management Server on sql2014 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Windows credentials used for WMI connection when retrieving Windows OS installation date with -IncludeWindows. Only required when the current user lacks WMI access to the target server or when connecting across domains. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeWindows Retrieves the Windows OS installation date in addition to SQL Server installation date using WMI. Useful for infrastructure audits requiring both application and operating system installation timestamps. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance with installation date information. Default properties (without -IncludeWindows): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) SqlInstallDate: DateTime when SQL Server was originally installed (DbaDateTime type) When -IncludeWindows is specified, an additional property is included: WindowsInstallDate: DateTime when the Windows operating system was installed (DbaDateTime type) The 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 (SQL Server 2005+) or dbo.sysservers (SQL Server 2000) to determine installation dates. &nbsp;"
  },
  {
    "name": "Get-DbaInstanceList",
    "description": "Returns all SQL Server instance names from the user-maintained list that is pre-loaded\ninto the dbatools tab completion cache for the -SqlInstance parameter. This list allows\nusers to have their frequently used instances available for autocomplete in their\nPowerShell terminal without needing to connect to them first.\n\nUse Add-DbaInstanceList to add instances to the list and Remove-DbaInstanceList to\nremove them.\n\nInstances can also be pre-loaded at module import time by setting the\n$env:DBATOOLS_KNOWN_INSTANCES environment variable to a comma-separated list of instance\nnames in your PowerShell profile.",
    "category": "Server Management",
    "tags": [
      "tabcompletion",
      "autocomplete"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaInstanceList",
    "popularityRank": 0,
    "synopsis": "Returns the user-maintained list of SQL Server instances used for tab completion.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaInstanceList View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Outputs Synopsis Returns the user-maintained list of SQL Server instances used for tab completion. Description Returns all SQL Server instance names from the user-maintained list that is pre-loaded into the dbatools tab completion cache for the -SqlInstance parameter. This list allows users to have their frequently used instances available for autocomplete in their PowerShell terminal without needing to connect to them first. Use Add-DbaInstanceList to add instances to the list and Remove-DbaInstanceList to remove them. Instances can also be pre-loaded at module import time by setting the $env:DBATOOLS_KNOWN_INSTANCES environment variable to a comma-separated list of instance names in your PowerShell profile. Syntax Get-DbaInstanceList [ ] &nbsp; Examples &nbsp; Example 1: Returns all instance names from the user-maintained autocomplete list PS C:\\> Get-DbaInstanceList Example 2: Removes all instances from the user-maintained autocomplete list PS C:\\> Get-DbaInstanceList | Remove-DbaInstanceList Outputs System.String Returns instance names as strings. Each instance name in the user-maintained autocomplete list is returned as a separate string object. &nbsp;"
  },
  {
    "name": "Get-DbaInstanceProperty",
    "description": "Retrieves all instance-level configuration properties from SQL Server's 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.",
    "category": "Server Management",
    "tags": [
      "instance",
      "configure",
      "configuration",
      "general"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaInstanceProperty",
    "popularityRank": 61,
    "synopsis": "Retrieves comprehensive SQL Server instance configuration properties for auditing and comparison",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaInstanceProperty View Source Klaas Vandenberghe (@powerdbaklaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves comprehensive SQL Server instance configuration properties for auditing and comparison Description Retrieves all instance-level configuration properties from SQL Server's 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. Syntax Get-DbaInstanceProperty [-SqlInstance] [[-SqlCredential] ] [[-InstanceProperty] ] [[-ExcludeInstanceProperty] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns SQL Server instance properties on the local default SQL Server instance PS C:\\> Get-DbaInstanceProperty -SqlInstance localhost Example 2: Returns SQL Server instance properties on default instance on sql2 and sqlexpress instance on sql4 PS C:\\> Get-DbaInstanceProperty -SqlInstance sql2, sql4\\sqlexpress Example 3: Returns SQL Server instance properties on sql2 and sql4 PS C:\\> 'sql2','sql4' | Get-DbaInstanceProperty Example 4: Returns SQL Server instance property DefaultFile on instance sql2 and sql4 PS C:\\> Get-DbaInstanceProperty -SqlInstance sql2,sql4 -InstanceProperty DefaultFile Example 5: Returns all SQL Server instance properties except DefaultFile on instance sql2 and sql4 PS C:\\> Get-DbaInstanceProperty -SqlInstance sql2,sql4 -ExcludeInstanceProperty DefaultFile Example 6: Connects using sqladmin credential and returns SQL Server instance properties from sql2 PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Get-DbaInstanceProperty -SqlInstance sql2 -SqlCredential $cred Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InstanceProperty Specifies which SQL Server instance properties to include from Information, UserOptions, and Settings collections. Accepts wildcards and arrays. Use this to focus on specific configuration properties like DefaultFile, MaxWorkerThreads, or LoginMode when auditing particular settings across instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeInstanceProperty Specifies which SQL Server instance properties to exclude from the results. Accepts wildcards and arrays. Use this to filter out noisy or irrelevant properties when you need a cleaner view of configuration data for reporting or comparison. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per instance property from the Information, UserOptions, and Settings collections. The function returns properties from three separate SMO collections, outputting each property with contextual information about which collection it came from. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Name: The property name (e.g., DefaultFile, MaxWorkerThreads, LoginMode, TcpPort) Value: The current value of the configuration property (string or mixed type depending on property) PropertyType: The type of property collection - either \"Information\", \"UserOption\", or \"Setting\" The -InstanceProperty and -ExcludeInstanceProperty parameters filter which specific properties are returned but do not change the output structure. &nbsp;"
  },
  {
    "name": "Get-DbaInstanceProtocol",
    "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).",
    "category": "Server Management",
    "tags": [
      "management",
      "protocol",
      "os"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaInstanceProtocol",
    "popularityRank": 391,
    "synopsis": "Retrieves SQL Server network protocol configuration and status from target computers.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaInstanceProtocol View Source Klaas Vandenberghe (@PowerDbaKlaas) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server network protocol configuration and status from target computers. 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. The 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. Requires Local Admin rights on destination computer(s). Syntax Get-DbaInstanceProtocol [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the SQL Server related server protocols on computer sqlserver2014a PS C:\\> Get-DbaInstanceProtocol -ComputerName sqlserver2014a Example 2: Gets the SQL Server related server protocols on computers sql1, sql2 and sql3 PS C:\\> 'sql1','sql2','sql3' | Get-DbaInstanceProtocol Example 3: Gets the SQL Server related server protocols on computers sql1 and sql2 PS C:\\> Get-DbaInstanceProtocol -ComputerName sql1,sql2 Example 4: Disables the VIA ServerNetworkProtocol on computer sql1 PS C:\\> (Get-DbaInstanceProtocol -ComputerName sql1 | Where-Object { $_.DisplayName -eq 'Named Pipes' }).Disable() Disables the VIA ServerNetworkProtocol on computer sql1. If successful, return code 0 is shown. Optional Parameters -ComputerName Specifies the target computer(s) where SQL Server instances are running. Accepts computer names, fully qualified domain names, or IP addresses. Use this when you need to check network protocol configurations on remote SQL Server machines for connectivity troubleshooting or security audits. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Credential object used to connect to the computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs WMI ServerNetworkProtocol object Returns 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 programmatically. Default display properties (via Select-DefaultView): ComputerName: The name of the computer running SQL Server InstanceName: The SQL Server instance name DisplayName: The user-friendly name of the protocol (TCP/IP, Named Pipes, Shared Memory, VIA) Name: The technical protocol name as recognized by SQL Server WMI MultiIP: Boolean indicating if the protocol supports multiple IP configurations IsEnabled: Boolean indicating whether the protocol is currently enabled or disabled Methods available on returned objects: Enable(): Enables the network protocol; returns 0 on success Disable(): Disables the network protocol; returns 0 on success These methods can be called directly on the returned objects to manage protocol states without using SQL Server Configuration Manager. &nbsp;"
  },
  {
    "name": "Get-DbaInstanceTrigger",
    "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.",
    "category": "Server Management",
    "tags": [
      "database",
      "trigger",
      "general"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaInstanceTrigger",
    "popularityRank": 514,
    "synopsis": "Retrieves server-level DDL triggers from SQL Server instances for auditing and documentation",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaInstanceTrigger View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves server-level DDL triggers from SQL Server instances for auditing and documentation 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. Syntax Get-DbaInstanceTrigger [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all server triggers on sql2017 PS C:\\> Get-DbaInstanceTrigger -SqlInstance sql2017 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Trigger Returns one Trigger object per server-level DDL trigger on the specified instance(s). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ID: Unique identifier for the trigger Name: The name of the trigger AnsiNullsStatus: ANSI NULLS setting (ON or OFF) AssemblyName: CLR assembly name (for CLR-based triggers) BodyStartIndex: Starting character position of the trigger body in the script ClassName: CLR class name (for CLR-based triggers) CreateDate: DateTime when the trigger was created DateLastModified: DateTime of the most recent modification DdlTriggerEvents: DDL events that cause the trigger to fire (CREATE, ALTER, DROP, etc.) ExecutionContext: Security context of trigger execution (Caller, Owner, or specific principal name) ExecutionContextLogin: The principal that executes the trigger ImplementationType: Implementation type (T-SQL or CLR) IsDesignMode: Boolean indicating if the trigger is in design mode IsEnabled: Boolean indicating if the trigger is active IsEncrypted: Boolean indicating if the trigger body is encrypted IsSystemObject: Boolean indicating if this is a system object MethodName: CLR method name (for CLR-based triggers) QuotedIdentifierStatus: QUOTED_IDENTIFIER setting State: Current state of the SMO object (Existing, Creating, Pending, etc.) TextHeader: The text header of the trigger definition TextMode: The text mode setting for the trigger All properties from the base SMO Trigger object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaInstanceUserOption",
    "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.",
    "category": "Server Management",
    "tags": [
      "instance",
      "configure",
      "useroption",
      "general"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaInstanceUserOption",
    "popularityRank": 508,
    "synopsis": "Retrieves instance-level user option defaults that affect new database connections",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaInstanceUserOption View Source Klaas Vandenberghe (@powerdbaklaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves instance-level user option defaults that affect new database connections 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. Syntax Get-DbaInstanceUserOption [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns SQL Instance user options on the local default SQL Server instance PS C:\\> Get-DbaInstanceUserOption -SqlInstance localhost Example 2: Returns SQL Instance user options on default instance on sql2 and sqlexpress instance on sql4 PS C:\\> Get-DbaInstanceUserOption -SqlInstance sql2, sql4\\sqlexpress Example 3: Returns SQL Instance user options on sql2 and sql4 PS C:\\> 'sql2','sql4' | Get-DbaInstanceUserOption Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Property Returns one Property object per user option configured at the instance level, representing the default user options that apply to new database connections. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) 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, IMPLICIT_TRANSACTIONS) Value: The current value of the user option (typically ON or OFF for boolean options, or a numeric value) All properties from the base SMO Property object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaIoLatency",
    "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's 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/",
    "category": "Utilities",
    "tags": [
      "diagnostic",
      "iolatency"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaIoLatency",
    "popularityRank": 204,
    "synopsis": "Retrieves I/O latency metrics for all database files to identify storage performance bottlenecks",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaIoLatency View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves I/O latency metrics for all database files to identify storage performance bottlenecks 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's SQL Server performance tuning methodology. Reference: https://www.sqlskills.com/blogs/paul/how-to-examine-io-subsystem-latencies-from-within-sql-server/ https://www.sqlskills.com/blogs/paul/capturing-io-latencies-period-time/ Syntax Get-DbaIoLatency [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get IO subsystem latency statistics for servers sql2008 and sqlserver2012 PS C:\\> Get-DbaIoLatency -SqlInstance sql2008, sqlserver2012 Example 2: Collects all IO subsystem latency statistics on server sql2008 into a Data Table PS C:\\> $output = Get-DbaIoLatency -SqlInstance sql2008 | Select-Object | ConvertTo-DbaDataTable Example 3: Get IO subsystem latency statistics for servers sql2008 and sqlserver2012 via pipline PS C:\\> 'sql2008','sqlserver2012' | Get-DbaIoLatency Example 4: Connects using sqladmin credential and returns IO subsystem latency statistics from sql2008 PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Get-DbaIoLatency -SqlInstance sql2008 -SqlCredential $cred Required Parameters -SqlInstance The SQL Server instance. Server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database file on the SQL Server instance, providing detailed I/O performance metrics collected from sys.dm_io_virtual_file_stats. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseId: Internal ID of the database containing the file DatabaseName: Name of the database containing the file FileId: Internal ID of the file within the database PhysicalName: Operating system file path of the file NumberOfReads: Total count of read operations since SQL Server instance startup IoStallRead: Total wait time in milliseconds spent waiting for read operations to complete NumberOfwrites: Total count of write operations since SQL Server instance startup IoStallWrite: Total wait time in milliseconds spent waiting for write operations to complete IoStall: Total cumulative I/O wait time in milliseconds (reads + writes) NumberOfBytesRead: Total number of bytes read from this file since instance startup NumberOfBytesWritten: Total number of bytes written to this file since instance startup SampleMilliseconds: Time in milliseconds since the SQL Server instance started (used for duration calculations) SizeOnDiskBytes: Current size of the file on disk in bytes Hidden properties (excluded from default display but available with Select-Object ):** FileHandle: Internal file handle reference ReadLatency: Average read latency calculated as IoStallRead / NumberOfReads in milliseconds WriteLatency: Average write latency calculated as IoStallWrite / NumberOfwrites in milliseconds Latency: Average I/O latency for both reads and writes calculated as IoStall / (NumberOfReads + NumberOfwrites) in milliseconds AvgBPerRead: Average bytes per read operation calculated as NumberOfBytesRead / NumberOfReads AvgBPerWrite: Average bytes per write operation calculated as NumberOfBytesWritten / NumberOfwrites AvgBPerTransfer: Average bytes per I/O operation (both reads and writes combined) All latency values are in milliseconds and are calculated to handle division by zero when no I/O has occurred (returns 0 in such cases). &nbsp;"
  },
  {
    "name": "Get-DbaKbUpdate",
    "description": "Searches Microsoft's 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't provide an API for this data.",
    "category": "Utilities",
    "tags": [
      "deployment",
      "install",
      "patch",
      "update"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaKbUpdate",
    "popularityRank": 108,
    "synopsis": "Retrieves detailed metadata and download links for Microsoft KB updates from the update catalog",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaKbUpdate View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed metadata and download links for Microsoft KB updates from the update catalog Description Searches Microsoft's 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't provide an API for this data. Syntax Get-DbaKbUpdate [-Name] [-Simple] [[-Language] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets detailed information about KB4057119 PS C:\\> Get-DbaKbUpdate -Name KB4057119 Gets detailed information about KB4057119. This works for SQL Server or any other KB. Example 2: Gets detailed information about KB4057119 and KB4057114 PS C:\\> Get-DbaKbUpdate -Name KB4057119, 4057114 Gets detailed information about KB4057119 and KB4057114. This works for SQL Server or any other KB. Example 3: A lil faster PS C:\\> Get-DbaKbUpdate -Name KB4057119, 4057114 -Simple A lil faster. Returns, at the very least: Title, Architecture, Language, Hotfix, UpdateId and Link Example 4: Gets detailed information about KB4057119 in Japanese PS C:\\> Get-DbaKbUpdate -Name KB4057119 -Language ja Gets detailed information about KB4057119 in Japanese. This works for SQL Server or any other KB. (Link property includes the links for Japanese version of SQL Server if the KB was Service Pack) Example 5: Downloads Japanese version of KB4057119 PS C:\\> Get-DbaKbUpdate -Name KB4057119 -Language ja | Save-DbaKbUpdate Required Parameters -Name Specifies the KB article number to search for, with or without the 'KB' prefix. Accepts multiple values for batch processing. Use this to retrieve update information for specific knowledge base articles like security patches, cumulative updates, or service packs. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -Simple Returns only essential update information to improve performance by skipping detailed web scraping. Provides Title, Architecture, Language, Hotfix status, UpdateId, and download Link. Use this when you need basic KB information quickly or when processing many updates where full details aren't required. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 all languages in one file. Use 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 Japanese. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 from Get-DbaBuild. Default display properties (full detailed output, when -Simple is NOT used): Title: The name/title of the KB update (e.g., \"Cumulative Update 23 for SQL Server 2019\") NameLevel: SQL Server release name (SQL Server 2019, 2017, etc.) from Get-DbaBuild SPLevel: Service Pack level (SP0, SP1, etc.) from Get-DbaBuild KBLevel: KB article number from Get-DbaBuild CULevel: Cumulative Update number from Get-DbaBuild BuildLevel: Full build number from Get-DbaBuild SupportedUntil: Support end date from Get-DbaBuild Architecture: CPU architecture - \"x64\", \"x86\", or \"ARM64\" based on extracted architecture information Language: Language identifier for the KB update (e.g., \"en-US\" for English) Hotfix: Boolean or status indicating if this is a hotfix (True/False) Description: Full description of the KB update contents and fixes LastModified: DateTime when the KB update was last modified Size: File size of the download package Classification: Microsoft classification (Critical, Important, Security Update, etc.) SupportedProducts: Array of supported SQL Server versions/editions MSRCNumber: Microsoft Security Response Center bulletin number if applicable MSRCSeverity: MSRC severity rating (Critical, Important, Moderate, Low) RebootBehavior: Whether installation requires reboot (Yes, No, Can be deferred) RequestsUserInput: Whether installation requires user input (Yes, No) ExclusiveInstall: Whether this update is exclusive/incompatible with other updates (Yes, No) NetworkRequired: Whether network connectivity is required during installation (Yes, No) UninstallNotes: Notes about uninstalling this update UninstallSteps: Steps required to uninstall this update UpdateId: Internal Microsoft update catalog GUID Supersedes: Array of KB articles superseded by this update SupersededBy: Array of KB articles that supersede this update Link: Direct HTTP/HTTPS download URL from download.windowsupdate.com When -Simple switch is specified (reduced property set for performance): Title: The name/title of the KB update Architecture: CPU architecture (x64, x86, etc.) Language: Language identifier Hotfix: Boolean indicating if this is a hotfix UpdateId: Internal Microsoft update catalog GUID Link: Direct download URL When build information is unavailable from Get-DbaBuild: The following properties are excluded: NameLevel, SPLevel, KBLevel, CULevel, BuildLevel, SupportedUntil Note: The function returns one object per download link found. A single KB article may have multiple links if different architectures or languages are available. &nbsp;"
  },
  {
    "name": "Get-DbaLastBackup",
    "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.",
    "category": "Backup & Restore",
    "tags": [
      "disasterrecovery",
      "backup"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaLastBackup",
    "popularityRank": 80,
    "synopsis": "Retrieves last backup dates and times for database backup compliance monitoring",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaLastBackup View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves last backup dates and times for database backup compliance monitoring 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. Syntax Get-DbaLastBackup [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-ExcludeReplica] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a custom object with Server name, Database name, and the date the last time backups were performed PS C:\\> Get-DbaLastBackup -SqlInstance ServerA\\sql987 Example 2: Returns a custom object with Server name, Database name, and the date the last time backups were performed... PS C:\\> Get-DbaLastBackup -SqlInstance ServerA\\sql987 | Select-Object Returns 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 status is. Example 3: Returns a gridview displaying ComputerName, InstanceName, SqlInstance, Database, RecoveryModel... PS C:\\> Get-DbaLastBackup -SqlInstance ServerA\\sql987 | Select-Object | Out-Gridview Returns a gridview displaying ComputerName, InstanceName, SqlInstance, Database, RecoveryModel, LastFullBackup, LastDiffBackup, LastLogBackup, SinceFull, SinceDiff, SinceLog, LastFullBackupIsCopyOnly, LastDiffBackupIsCopyOnly, LastLogBackupIsCopyOnly, DatabaseCreated, DaysSinceDbCreated, Status Example 4: Returns all databases on the given instances without a full backup in the last three days PS C:\\> $MyInstances | Get-DbaLastBackup | Where-Object -FilterScript { $_.LastFullBackup.Date -lt (Get-Date).AddDays(-3) } | Format-Table -Property SqlInstance, Database, LastFullBackup Returns all databases on the given instances without a full backup in the last three days. Note that the property LastFullBackup is a custom object, with the subproperty Date of type datetime and therefore suitable for comparison with dates. Example 5: Filters for the databases that had a copy_only full backup done as the last backup PS C:\\> Get-DbaLastBackup -SqlInstance ServerA\\sql987 | Where-Object { $_.LastFullBackupIsCopyOnly -eq $true } Example 6: Returns last backup information for all databases on both instances, excluding availability group databases... PS C:\\> Get-DbaLastBackup -SqlInstance sql2019, sql2019b -ExcludeReplica Returns last backup information for all databases on both instances, excluding availability group databases where the current instance is not the preferred backup replica. This prevents false alerts when secondary replicas appear to have no recent backups because backups are only performed on the preferred replica. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for backup history. Accepts wildcards for pattern matching. Use this when you need to focus on specific databases rather than scanning all databases on the instance. Helpful for monitoring critical production databases or troubleshooting backup issues on particular databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the backup history check. Commonly used to skip system databases or test databases. Use this when you want to check most databases but exclude certain ones like tempdb, development databases, or databases with known backup exemptions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeReplica When this switch is enabled, databases in an AlwaysOn Availability Group where the current SQL Server instance is not the preferred backup replica are excluded from the results. This is useful when running Get-DbaLastBackup against multiple servers in an availability group to avoid false positives where secondary replicas appear to have missing backups because backups are taken on the preferred replica only. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database processed, containing backup status information and compliance metrics. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database LastFullBackup: DateTime of the most recent full backup (DbaDateTime object with Date subproperty) LastDiffBackup: DateTime of the most recent differential backup (DbaDateTime object with Date subproperty) LastLogBackup: DateTime of the most recent transaction log backup (DbaDateTime object with Date subproperty) *Additional properties available (use Select-Object to display):** RecoveryModel: Database recovery model (Simple, Full, or BulkLogged) SinceFull: DbaTimeSpan representing time elapsed since last full backup; null if never backed up SinceDiff: DbaTimeSpan representing time elapsed since last differential backup; null if never backed up SinceLog: DbaTimeSpan representing time elapsed since last transaction log backup; null if never backed up LastFullBackupIsCopyOnly: Boolean indicating if the last full backup was copy-only LastDiffBackupIsCopyOnly: Boolean indicating if the last differential backup was copy-only (always false per SQL Server rules) LastLogBackupIsCopyOnly: Boolean indicating if the last transaction log backup was copy-only DatabaseCreated: DateTime when the database was created DaysSinceDbCreated: Integer number of days since database creation 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\" The LastFullBackup, LastDiffBackup, and LastLogBackup properties are DbaDateTime objects that can be compared with .Date subproperty. &nbsp;"
  },
  {
    "name": "Get-DbaLastGoodCheckDb",
    "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.",
    "category": "Database Operations",
    "tags": [
      "checkdb",
      "database",
      "utility"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaLastGoodCheckDb",
    "popularityRank": 246,
    "synopsis": "Retrieves the last successful DBCC CHECKDB timestamp and integrity status for databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaLastGoodCheckDb View Source Jakob Bindslet (jakob@bindslet.dk) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves the last successful DBCC CHECKDB timestamp and integrity status for databases 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. The 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. This 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. Please note that this script uses the DBCC DBINFO() WITH TABLERESULTS. DBCC DBINFO has several known weak points, such as: DBCC DBINFO is an undocumented feature/command. The LastKnowGood timestamp is updated when a DBCC CHECKFILEGROUP is performed. The LastKnowGood timestamp is updated when a DBCC CHECKDB WITH PHYSICAL_ONLY is performed. The LastKnowGood timestamp does not get updated when a database in READ_ONLY. An empty ($null) LastGoodCheckDb result indicates that a good DBCC CHECKDB has never been performed. SQL Server 2008R2 has a \"bug\" that causes each databases to possess two dbi_dbccLastKnownGood fields, instead of the normal one. This 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. Syntax Get-DbaLastGoodCheckDb [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a custom object displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated... PS C:\\> Get-DbaLastGoodCheckDb -SqlInstance ServerA\\sql987 Returns a custom object displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled Example 2: Returns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated... PS C:\\> Get-DbaLastGoodCheckDb -SqlInstance ServerA\\sql987 -SqlCredential sqladmin | Format-Table -AutoSize Returns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled. Authenticates using SQL Server authentication. Example 3: Returns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated... PS C:\\> Get-DbaLastGoodCheckDb -SqlInstance sql2016 -ExcludeDatabase \"TempDB\" | Format-Table -AutoSize Returns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled. All databases except for \"TempDB\" will be displayed in the output. Example 4: Returns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated... PS C:\\> Get-DbaDatabase -SqlInstance sql2016 -Database DB1, DB2 | Get-DbaLastGoodCheckDb | Format-Table -AutoSize Returns a formatted table displaying Server, Database, DatabaseCreated, LastGoodCheckDb, DaysSinceDbCreated, DaysSinceLastGoodCheckDb, Status and DataPurityEnabled. Only databases DB1 abd DB2 will be displayed in the output. Optional Parameters -SqlInstance The target SQL Server instance or instances. Defaults to localhost. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for their last good CHECKDB status. Accepts wildcards for pattern matching. When 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the CHECKDB status check. Commonly used to skip system databases like TempDB or databases with known maintenance schedules. Accepts wildcards and multiple database names to filter out databases that don't need regular CHECKDB monitoring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase, allowing for complex filtering scenarios before checking CHECKDB status. Use this when you need to apply advanced database filtering logic or when chaining multiple dbatools commands together. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database processed, containing database integrity check status and compliance metrics. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database DatabaseCreated: DateTime when the database was created; $null if the date cannot be determined LastGoodCheckDb: DateTime of the last successful DBCC CHECKDB operation; $null if CHECKDB has never been performed DaysSinceDbCreated: Numeric value (days and fractional days) representing time elapsed since database creation DaysSinceLastGoodCheckDb: Integer number of days since the last successful CHECKDB; only present if CHECKDB was previously run 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) 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 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 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 Notes: For SQL Server 2005-2008: Uses DBCC DBINFO() WITH TABLERESULTS to retrieve LastGoodCheckDb, CreateVersion, and DbccFlags For SQL Server 2008 R2 and newer: Uses SMO LastGoodCheckDbTime property (CreateVersion and DbccFlags are not available) CreateVersion and DbccFlags are only populated when running as sysadmin or on SQL Server versions prior to 2010 If CHECKDB has never been performed, LastGoodCheckDb will be $null and Status will indicate \"New database\" or \"should be performed\" &nbsp;"
  },
  {
    "name": "Get-DbaLatchStatistic",
    "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's 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/",
    "category": "Performance",
    "tags": [
      "latchstatistics",
      "waits"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaLatchStatistic",
    "popularityRank": 496,
    "synopsis": "Retrieves latch contention statistics from SQL Server to identify performance bottlenecks",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaLatchStatistic View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves latch contention statistics from SQL Server to identify performance bottlenecks 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's 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. Returns: LatchClass WaitSeconds WaitCount Percentage AverageWaitSeconds URL Reference: https://www.sqlskills.com/blogs/paul/advanced-performance-troubleshooting-waits-latches-spinlocks/ https://www.sqlskills.com/blogs/paul/most-common-latch-classes-and-what-they-mean/ Syntax Get-DbaLatchStatistic [-SqlInstance] [[-SqlCredential] ] [[-Threshold] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Check latch statistics for servers sql2008 and sqlserver2012 PS C:\\> Get-DbaLatchStatistic -SqlInstance sql2008, sqlserver2012 Example 2: Check latch statistics on server sql2008 for thresholds above 98% PS C:\\> Get-DbaLatchStatistic -SqlInstance sql2008 -Threshold 98 Example 3: Collects all latch statistics on server sql2008 into a Data Table PS C:\\> $output = Get-DbaLatchStatistic -SqlInstance sql2008 -Threshold 100 | Select-Object * | ConvertTo-DbaDataTable Example 4: Get latch statistics for servers sql2008 and sqlserver2012 via pipline PS C:\\> 'sql2008','sqlserver2012' | Get-DbaLatchStatistic Example 5: Connects using sqladmin credential and returns latch statistics from sql2008 PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Get-DbaLatchStatistic -SqlInstance sql2008 -SqlCredential $cred Example 6: Displays the output then loads the associated sqlskills website for each result PS C:\\> $output = Get-DbaLatchStatistic -SqlInstance sql2008 PS C:\\> $output PS C:\\> foreach ($row in ($output | Sort-Object -Unique Url)) { Start-Process ($row).Url } Displays the output then loads the associated sqlskills website for each result. Opens one tab per unique URL. Required Parameters -SqlInstance The SQL Server instance. Server version must be SQL Server version 2005 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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's methodology. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 95 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 classes; using 100% threshold returns all non-BUFFER latch classes. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) WaitType: The latch class name from sys.dm_os_latch_stats (e.g., ACCESS_METHODS_LATCH_EX, BUFFER_LATCH_EX) WaitSeconds: Total wait time for this latch class in seconds (decimal with 2 decimal places) WaitCount: Number of waiting requests for this latch class (bigint) Percentage: Percentage of total latch wait time contributed by this latch class (0-100, decimal with 2 decimal places) AverageWaitSeconds: Average wait time per request for this latch class in seconds (decimal with 4 decimal places, calculated as WaitSeconds/WaitCount) URL: Direct hyperlink to SQLSkills documentation for this latch class (format: https://www.sqlskills.com/help/latches/{LatchClass}) &nbsp;"
  },
  {
    "name": "Get-DbaLinkedServer",
    "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.",
    "category": "Utilities",
    "tags": [
      "linkedserver",
      "linked"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaLinkedServer",
    "popularityRank": 98,
    "synopsis": "Retrieves linked server configurations and connection details from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaLinkedServer View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves linked server configurations and connection details from SQL Server instances. 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. Syntax Get-DbaLinkedServer [-SqlInstance] [[-SqlCredential] ] [[-LinkedServer] ] [[-ExcludeLinkedServer] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all linked servers for the SQL Server instance DEV01 PS C:\\> Get-DbaLinkedServer -SqlInstance DEV01 Example 2: Returns all linked servers for a group of servers from SQL Server Central Management Server (CMS) PS C:\\> Get-DbaRegServer -SqlInstance DEV01 -Group SQLDEV | Get-DbaLinkedServer | Out-GridView Returns all linked servers for a group of servers from SQL Server Central Management Server (CMS). Send output to GridView. Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LinkedServer Specifies one or more linked server names to retrieve information for. Accepts an array of server names for filtering results. Use this when you need details on specific linked servers instead of all configured linked servers on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeLinkedServer Specifies one or more linked server names to exclude from the results. Accepts an array of server names to filter out. Use this when you want to skip specific linked servers, such as excluding test or deprecated connections from your inventory. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.LinkedServer Returns one LinkedServer object per configured linked server found on the target instance(s). When filtered, returns only the linked servers matching the specified criteria. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the linked server RemoteServer: The data source or remote server name (from DataSource property) ProductName: The product type of the linked server Impersonate: Boolean or collection indicating if impersonation is enabled RemoteUser: The remote user login mapped for this linked server connection Publisher: The distribution publisher for the linked server (if applicable) Distributor: The distributor server (if applicable) DateLastModified: DateTime indicating when the linked server configuration was last modified *Additional properties available from SMO LinkedServer object (accessible via Select-Object ):** LinkedServerType: Type of linked server (SqlServer, OleDbProvider, etc.) RpsSiteUrl: RPS site URL if configured LoginSecure: Boolean indicating if Windows authentication is enforced ConnectionTimeout: Timeout in seconds for linked server connections QueryTimeout: Query timeout in seconds on the linked server Collation: Collation setting for the linked server LazySchemaValidation: Boolean indicating lazy schema validation setting UseRemoteCollation: Boolean indicating if remote collation is used IsPublisher: Boolean indicating if this linked server is a publisher IsDistributor: Boolean indicating if this linked server is a distributor IsSubscriber: Boolean indicating if this linked server is a subscriber &nbsp;"
  },
  {
    "name": "Get-DbaLinkedServerLogin",
    "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.",
    "category": "Security",
    "tags": [
      "linkedserver",
      "login"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaLinkedServerLogin",
    "popularityRank": 209,
    "synopsis": "Retrieves linked server login mappings and authentication configurations from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaLinkedServerLogin View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves linked server login mappings and authentication configurations from SQL Server instances. 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. Syntax Get-DbaLinkedServerLogin [[-SqlInstance] ] [[-SqlCredential] ] [[-LinkedServer] ] [[-LocalLogin] ] [[-ExcludeLocalLogin] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Gets the linked server login &quot;login1&quot; from the linked server &quot;linkedServer1&quot; on sql01 PS C:\\> Get-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -LocalLogin login1 Example 2: Gets the linked server login(s) from the linked server &quot;linkedServer1&quot; on sql01 and excludes the login2... PS C:\\> Get-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -ExcludeLocalLogin login2 Gets the linked server login(s) from the linked server \"linkedServer1\" on sql01 and excludes the login2 linked server login. Example 3: Gets the linked server login &quot;login1&quot; from the linked server &quot;linkedServer1&quot; on sql01 using a pipeline with... PS C:\\> (Get-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1) | Get-DbaLinkedServerLogin -LocalLogin login1 Gets the linked server login \"login1\" from the linked server \"linkedServer1\" on sql01 using a pipeline with the linked server passed in. Example 4: Gets the linked server login &quot;login1&quot; from the linked server &quot;linkedServer1&quot; on sql01 using a pipeline with... PS C:\\> (Connect-DbaInstance -SqlInstance sql01) | Get-DbaLinkedServerLogin -LinkedServer linkedServer1 -LocalLogin login1 Gets the linked server login \"login1\" from the linked server \"linkedServer1\" on sql01 using a pipeline with the instance passed in. Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LinkedServer Specifies the name(s) of the linked server(s) to retrieve login mappings from. Required when using SqlInstance parameter. Use this to focus on specific linked servers when you have multiple configured on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LocalLogin Filters results to only include specific local SQL Server login names that have mappings configured for the linked server. Useful when auditing a specific user's access or troubleshooting authentication for particular accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeLocalLogin Excludes specific local SQL Server login names from the results, showing all other configured login mappings. Use this to hide system accounts or service accounts when focusing on user login mappings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts piped input from Connect-DbaInstance or Get-DbaLinkedServer commands to work with existing connection objects. When piping from Get-DbaLinkedServer, the LinkedServer parameter becomes optional since the linked server context is already established. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.LinkedServerLogin Returns one LinkedServerLogin object per local login mapping configured on the linked server. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the local SQL Server login RemoteUser: The remote user account on the linked server Impersonate: Boolean indicating if the remote user credentials are impersonated Additional properties available (from SMO LinkedServerLogin object): DateLastModified: DateTime when the login mapping was last modified Parent: Reference to the parent LinkedServer object State: Current state of the SMO object (Existing, Creating, Pending, etc.) Urn: The Uniform Resource Name for the object All properties from the base SMO object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaLocaleSetting",
    "description": "Retrieves Windows locale settings from the Control Panel\\International registry key on one or more computers. These settings directly impact SQL Server's 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's locale settings from HKEY_CURRENT_USER\\Control Panel\\International.\n\nRequires Local Admin rights on destination computer(s).",
    "category": "Utilities",
    "tags": [
      "management",
      "locale",
      "os"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaLocaleSetting",
    "popularityRank": 500,
    "synopsis": "Retrieves Windows locale settings from the registry on SQL Server computers for regional configuration analysis.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaLocaleSetting View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows locale settings from the registry on SQL Server computers for regional configuration analysis. Description Retrieves Windows locale settings from the Control Panel\\International registry key on one or more computers. These settings directly impact SQL Server's date/time formatting, currency display, number formatting, and collation behavior. Useful 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's locale settings from HKEY_CURRENT_USER\\Control Panel\\International. Requires Local Admin rights on destination computer(s). Syntax Get-DbaLocaleSetting [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the Locale settings on computer sqlserver2014a PS C:\\> Get-DbaLocaleSetting -ComputerName sqlserver2014a Example 2: Gets the Locale settings on computers sql1, sql2 and sql3 PS C:\\> 'sql1','sql2','sql3' | Get-DbaLocaleSetting Example 3: Gets the Locale settings on computers sql1 and sql2 using SQL Authentication to authenticate to the servers PS C:\\> Get-DbaLocaleSetting -ComputerName sql1,sql2 -Credential $credential Optional Parameters -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. Use 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 collation behavior. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Credential object used to connect to the computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per computer with Windows locale settings from the HKEY_CURRENT_USER\\Control Panel\\International registry key. Standard properties (always included): ComputerName: The name of the computer where locale settings were retrieved Additional properties (dynamically retrieved from registry): The command dynamically reads all values from the HKEY_CURRENT_USER\\Control Panel\\International registry key and adds them as properties. Common properties include: Locale and Language Settings: Locale: The locale code (e.g., \"00000410\" for Italian) LocaleName: The locale name in standard format (e.g., \"it-IT\") sLanguage: The language abbreviation (e.g., \"ITA\") sCurrency: The currency symbol (e.g., \"â‚¬\") Date and Time Formatting: sLongDate: Format string for long date display sShortDate: Format string for short date display sTimeFormat: Format string for time display sShortTime: Format string for short time display Numeric Formatting: sDecimal: Decimal separator character (e.g., \".\") sList: List separator character (e.g., \",\" or \";\") iDigits: Number of digits after decimal separator Additional Integer Settings (prefixed with 'i'): iCountry: Country/region identifier iCurrDigits: Number of digits for currency iCurrency: Currency format (0=prefix, 1=suffix) iDate: Date format (0=M/D/Y, 1=D/M/Y, 2=Y/M/D) iFirstDayOfWeek: First day of week (0=Sunday, 1=Monday, etc.) iFirstWeekOfYear: First week of year definition iLZero: Leading zero display (0=none, 1=display) iTime: Time format (0=12-hour, 1=24-hour) iTLZero: Time leading zero for hours (0=none, 1=display) Additional String Settings (prefixed with 's'): sAM: AM symbol for 12-hour format sPM: PM symbol for 12-hour format sThousand: Thousands separator character Note: 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 specific computer. &nbsp;"
  },
  {
    "name": "Get-DbaLogin",
    "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.",
    "category": "Security",
    "tags": [
      "login"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaLogin",
    "popularityRank": 17,
    "synopsis": "Retrieves SQL Server login accounts with filtering options for security audits and access management",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaLogin View Source Mitchell Hamann (@SirCaptainMitch) , Rob Sewell (@SQLDBaWithBeard) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server login accounts with filtering options for security audits and access management 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. Syntax Get-DbaLogin [-SqlInstance] [[-SqlCredential] ] [[-Login] ] [[-IncludeFilter] ] [[-ExcludeLogin] ] [[-ExcludeFilter] ] [-ExcludeSystemLogin] [[-Type] ] [-HasAccess] [-Locked] [-Disabled] [-MustChangePassword] [-Detailed] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all the logins from server sql2016 using NT authentication and returns the SMO login objects PS C:\\> Get-DbaLogin -SqlInstance sql2016 Example 2: Gets all the logins for a given SQL Server using a passed credential object and returns the SMO login objects PS C:\\> Get-DbaLogin -SqlInstance sql2016 -SqlCredential $sqlcred Example 3: Get specific logins from server sql2016 returned as SMO login objects PS C:\\> Get-DbaLogin -SqlInstance sql2016 -SqlCredential $sqlcred -Login dbatoolsuser,TheCaptain Example 4: Get all user objects from server sql2016 beginning with &#39;&#39; or &#39;NT &#39;, returned as SMO login objects PS C:\\> Get-DbaLogin -SqlInstance sql2016 -IncludeFilter '','NT ' Example 5: Get all user objects from server sql2016 except the login dbatoolsuser, returned as SMO login objects PS C:\\> Get-DbaLogin -SqlInstance sql2016 -ExcludeLogin dbatoolsuser Example 6: Get all user objects from server sql2016 that are Windows Logins PS C:\\> Get-DbaLogin -SqlInstance sql2016 -Type Windows Example 7: Get all user objects from server sql2016 that are Windows Logins and have Rob in the name PS C:\\> Get-DbaLogin -SqlInstance sql2016 -Type Windows -IncludeFilter Rob Example 8: Get all user objects from server sql2016 that are SQL Logins PS C:\\> Get-DbaLogin -SqlInstance sql2016 -Type SQL Example 9: Get all user objects from server sql2016 that are SQL Logins and have Rob in the name PS C:\\> Get-DbaLogin -SqlInstance sql2016 -Type SQL -IncludeFilter Rob Example 10: Get all user objects from server sql2016 that are not system objects PS C:\\> Get-DbaLogin -SqlInstance sql2016 -ExcludeSystemLogin Example 11: Get all user objects from server sql2016 except any beginning with &#39;&#39; or &#39;NT &#39;, returned as SMO login... PS C:\\> Get-DbaLogin -SqlInstance sql2016 -ExcludeFilter '','NT ' Get all user objects from server sql2016 except any beginning with '' or 'NT ', returned as SMO login objects. Example 12: Using Get-DbaLogin on the pipeline, you can also specify which names you would like with -Login PS C:\\> 'sql2016', 'sql2014' | Get-DbaLogin -SqlCredential $sqlcred Example 13: Using Get-DbaLogin on the pipeline to get all locked logins on servers sql2016 and sql2014 PS C:\\> 'sql2016', 'sql2014' | Get-DbaLogin -SqlCredential $sqlcred -Locked Example 14: Using Get-DbaLogin on the pipeline to get all Disabled logins that have access on servers sql2016 or sql2014 PS C:\\> 'sql2016', 'sql2014' | Get-DbaLogin -SqlCredential $sqlcred -HasAccess -Disabled Example 15: Get all user objects from server sql2016 that are SQL Logins PS C:\\> Get-DbaLogin -SqlInstance sql2016 -Type SQL -Detailed Get all user objects from server sql2016 that are SQL Logins. Get additional info for login available from LoginProperty function Example 16: Using Get-DbaLogin on the pipeline to get all logins that must change password on servers sql2016 and sql2014 PS C:\\> 'sql2016', 'sql2014' | Get-DbaLogin -SqlCredential $sqlcred -MustChangePassword Required Parameters -SqlInstance The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Specifies specific login names to retrieve instead of returning all logins from the instance. Use this when you need information about particular accounts for troubleshooting access issues or security audits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeFilter Includes only logins matching the specified wildcard patterns (supports and ? wildcards). Use this to find groups of related logins, such as all domain accounts from a specific organizational unit or service accounts with naming conventions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeLogin Excludes specific login names from the results. Useful when you want all logins except certain service accounts or system logins that you don't need to review. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeFilter Excludes logins matching the specified wildcard patterns (supports and ? wildcards). Commonly used to filter out system accounts or built-in logins when focusing on user accounts during security reviews. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemLogin Excludes built-in system logins like sa, BUILTIN\\Administrators, and NT AUTHORITY accounts from results. Use this when performing user access audits where you only want to see custom logins created for applications and users. | Property | Value | | --- | --- | | Alias | ExcludeSystemLogins | | Required | False | | Pipeline | false | | Default Value | False | -Type Filters results to show only Windows Authentication logins or SQL Server Authentication logins. Use 'Windows' to review domain accounts and local Windows users, or 'SQL' to audit SQL Server native accounts that store passwords in the database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Windows,SQL | -HasAccess Returns only logins that currently have permission to connect to the SQL Server instance. Use this to verify which accounts can actually access the server, as some logins may exist but be denied connection rights. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Locked Returns only login accounts that are currently locked due to failed authentication attempts. Use this to identify accounts that may need to be unlocked or investigate potential security incidents. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Disabled Returns only login accounts that have been disabled but not dropped from the server. Use this to identify inactive accounts that should be reviewed for cleanup or re-enabling for returning employees. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MustChangePassword Returns only SQL Server logins that are flagged to change their password on next login. Use this to identify accounts with temporary passwords or those requiring password updates due to security policies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Detailed Includes additional security-related properties like bad password count, password age, and lockout times. Use this for comprehensive security audits when you need detailed information about password policies and authentication failures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Login Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The login account name LoginType: The type of login (SqlLogin, WindowsUser, or WindowsGroup) CreateDate: DateTime when the login was created LastLogin: DateTime of the most recent connection (null if never connected or SQL Server 2000) HasAccess: Boolean indicating if the login has permission to connect IsLocked: Boolean indicating if the login is currently locked due to failed authentication attempts IsDisabled: Boolean indicating if the login is disabled MustChangePassword: Boolean indicating if the login must change password on next connection When -Detailed switch is specified, additional properties are included: BadPasswordCount: Number of failed login attempts since last successful login BadPasswordTime: DateTime of the most recent failed login attempt DaysUntilExpiration: Number of days until the login password expires (SQL Server only) HistoryLength: Number of previous passwords tracked in history (SQL Server only) IsMustChange: Boolean from LOGINPROPERTY indicating password change requirement LockoutTime: DateTime when the login was locked due to authentication failures PasswordHash: Hexadecimal hash of the password (SQL Server only, sensitive data) PasswordLastSetTime: DateTime when the password was last set (SQL Server only) Additional properties always available: SidString: Hexadecimal string representation of the login's Security Identifier (SID) All properties from the base SMO Login object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaMaintenanceSolutionLog",
    "description": "Retrieves detailed execution information from IndexOptimize text log files when LogToTable='N' is configured in Ola Hallengren's MaintenanceSolution. This function parses the text files written to the SQL Server instance's 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='Y' to enable database-based logging, which provides more reliable access to maintenance history.",
    "category": "Utilities",
    "tags": [
      "community",
      "olahallengren"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaMaintenanceSolutionLog",
    "popularityRank": 232,
    "synopsis": "Parses IndexOptimize text log files from Ola Hallengren's MaintenanceSolution when database logging is disabled.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaMaintenanceSolutionLog View Source Klaas Vandenberghe (@powerdbaklaas) , Simone Bizzotto (@niphlod) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Parses IndexOptimize text log files from Ola Hallengren's MaintenanceSolution when database logging is disabled. Description Retrieves detailed execution information from IndexOptimize text log files when LogToTable='N' is configured in Ola Hallengren's MaintenanceSolution. This function parses the text files written to the SQL Server instance's log directory, extracting index operation details including start times, duration, fragmentation levels, and any errors encountered. This 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. Be 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. For modern deployments, we recommend using Install-DbaMaintenanceSolution and configuring procedures with LogToTable='Y' to enable database-based logging, which provides more reliable access to maintenance history. Syntax Get-DbaMaintenanceSolutionLog [-SqlInstance] [[-SqlCredential] ] [[-LogType] ] [[-Since] ] [[-Path] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the outcome of the IndexOptimize job on sql instance sqlserver2014a PS C:\\> Get-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a Example 2: Gets the outcome of the IndexOptimize job on sqlserver2014a, using SQL Authentication PS C:\\> Get-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -SqlCredential $credential Example 3: Gets the outcome of the IndexOptimize job on sqlserver2014a and sqlserver2020test PS C:\\> 'sqlserver2014a', 'sqlserver2020test' | Get-DbaMaintenanceSolutionLog Example 4: Gets the outcome of the IndexOptimize job on sqlserver2014a, reading the log files in their custom location PS C:\\> Get-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -Path 'D:\\logs\\maintenancesolution\\' Example 5: Gets the outcome of the IndexOptimize job on sqlserver2014a, starting from july 18, 2017 PS C:\\> Get-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -Since '2017-07-18' Example 6: Gets the outcome of the IndexOptimize job on sqlserver2014a, the other options are not yet available! sorry PS C:\\> Get-DbaMaintenanceSolutionLog -SqlInstance sqlserver2014a -LogType IndexOptimize Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LogType Specifies which Ola Hallengren maintenance solution log type to parse from text files. Accepts 'IndexOptimize', 'DatabaseBackup', or 'DatabaseIntegrityCheck'. Currently only IndexOptimize parsing is supported - use this when you need to analyze index rebuild and reorganize operations from file-based logs. DatabaseBackup and DatabaseIntegrityCheck parsing are planned for future releases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | IndexOptimize | | Accepted Values | IndexOptimize,DatabaseBackup,DatabaseIntegrityCheck | -Since Filters log files to include only those created on or after the specified date and time. Use this when you need to focus on recent maintenance operations or investigate issues that started after a specific point in time. The function examines both the filename timestamp and file creation time to determine which logs to process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies a custom directory path where maintenance solution log files are stored. Defaults to the SQL Server instance's error log directory. Use this when your maintenance solution jobs write logs to a non-standard location, such as a dedicated maintenance logs folder or shared network path. The path must be accessible from the machine where you're running the command. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties include: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name Database: The database name where the index or statistics operation was performed StartTime: DateTime when the operation started (converted from \"Date and time\" field as dbadatetime) Duration: The total duration of the operation (converted from \"Duration\" field as timespan) Index: The index name for ALTER INDEX operations (null for UPDATE STATISTICS operations) Statistics: The statistics name for UPDATE STATISTICS operations (null for ALTER INDEX operations) Schema: The schema name containing the table Table: The table name Action: The action performed (REBUILD or REORGANIZE for indexes, null for statistics) Options: The index operation options (FILLFACTOR, PAD_INDEX, etc.) Timeout: The lock timeout value in milliseconds (if specified) Partition: The partition number for partitioned indexes (null for non-partitioned) ObjectType: The type of object being optimized IndexType: The type of index (Heap, ClusteredIndex, NonClusteredIndex) ImageText: Image text information from the log NewLOB: New LOB information FileStream: FileStream information ColumnStore: ColumnStore information AllowPageLocks: Page lock settings PageCount: Number of pages in the index Fragmentation: Index fragmentation percentage before optimization Error: Any errors encountered during the operation (multiline string with newlines joining multiple error lines) All properties from the parsed log file are accessible via Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaManagementObject",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "smo"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaManagementObject",
    "popularityRank": 292,
    "synopsis": "Discovers installed SQL Server Management Object (SMO) assemblies and their load status",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaManagementObject View Source Ben Miller (@DBAduck), dbaduck.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Discovers installed SQL Server Management Object (SMO) assemblies and their load status 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. Syntax Get-DbaManagementObject [[-ComputerName] ] [[-Credential] ] [[-VersionNumber] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all versions of SMO on the computer PS C:\\> Get-DbaManagementObject Example 2: Returns just the version specified PS C:\\> Get-DbaManagementObject -VersionNumber 13 Returns just the version specified. If the version does not exist then it will return nothing. Optional Parameters -ComputerName Specifies the Windows server(s) where you want to scan for SMO assemblies and SQL Client libraries. Use this when troubleshooting SMO version conflicts across multiple servers or when checking which SQL Server tools are installed on remote machines. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential This command uses Windows credentials. This parameter allows you to connect remotely as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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). Use this when you need to verify if a specific SQL Server version's SMO libraries are installed, particularly when troubleshooting version compatibility issues between different SQL Server tools. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 assembly or module discovered. Properties: ComputerName: Name of the computer where the assembly or module is located Version: Version number of the assembly or module Loaded: Boolean indicating if the assembly/module is currently loaded in the PowerShell session Path: File path to the assembly or module; null for Global Assembly Cache (GAC) assemblies LoadTemplate: Ready-to-use PowerShell command to load the assembly/module via Add-Type Multiple output types may be included: Local SMO assemblies from PowerShell installation directories (with file paths) Global Assembly Cache (GAC) assemblies (without file paths, using AssemblyName) Loaded assemblies currently in the AppDomain (with location information) SNI modules with corresponding SqlClient assembly references Use the LoadTemplate property to quickly load discovered assemblies in PowerShell scripts. &nbsp;"
  },
  {
    "name": "Get-DbaMaxMemory",
    "description": "This command retrieves the SQL Server 'Max Server Memory' 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't 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.",
    "category": "Performance",
    "tags": [
      "maxmemory",
      "memory"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaMaxMemory",
    "popularityRank": 114,
    "synopsis": "Retrieves SQL Server max memory configuration and compares it to total physical server memory",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaMaxMemory View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server max memory configuration and compares it to total physical server memory Description This command retrieves the SQL Server 'Max Server Memory' 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. Use this function to audit memory settings across your environment, troubleshoot performance issues related to memory pressure, or verify that SQL Server isn't 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. Results are returned in megabytes (MB) for both the configured max memory and total physical memory values. Syntax Get-DbaMaxMemory [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get memory settings for instances &quot;sqlcluster&quot; and &quot;sqlserver2012&quot; PS C:\\> Get-DbaMaxMemory -SqlInstance sqlcluster, sqlserver2012 Get memory settings for instances \"sqlcluster\" and \"sqlserver2012\". Returns results in megabytes (MB). Example 2: Find all servers in Server Central Management Server that have &#39;Max Server Memory&#39; set to higher than the... PS C:\\> Get-DbaRegServer -SqlInstance sqlcluster | Get-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total } Find all servers in Server Central Management Server that have 'Max Server Memory' set to higher than the total memory of the server (think 2147483647) Example 3: Scans localhost for instances using the browser service, traverses all instances and displays memory settings... PS C:\\> Find-DbaInstance -ComputerName localhost | Get-DbaMaxMemory | Format-Table -AutoSize Scans localhost for instances using the browser service, traverses all instances and displays memory settings in a formatted table. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance specified, containing memory configuration and physical memory information for comparison. Default display properties (via Select-DefaultView): ComputerName: Name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: Full SQL Server instance name (computer\\instance format) Total: Total physical memory on the server in megabytes (MB) MaxValue: Configured max server memory setting in megabytes (MB) Additional available property: Server: The SMO Server object representing the connected SQL Server instance; accessible for piping or further operations Use Select-Object * to access the Server property, or pipe the output to other commands for advanced scenarios. &nbsp;"
  },
  {
    "name": "Get-DbaMemoryCondition",
    "description": "Analyzes SQL Server's 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.",
    "category": "Performance",
    "tags": [
      "memory",
      "general"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaMemoryCondition",
    "popularityRank": 407,
    "synopsis": "Retrieves memory pressure notifications and utilization metrics from SQL Server resource monitor ring buffers.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaMemoryCondition View Source IJeb Reitsma Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves memory pressure notifications and utilization metrics from SQL Server resource monitor ring buffers. Description Analyzes SQL Server's 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. The 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. This command is based on a query provided by Microsoft support and queries the sys.dm_os_ring_buffers DMV to extract resource monitor notifications. Syntax Get-DbaMemoryCondition [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the memory conditions for the selected instance PS C:\\> Get-DbaMemoryCondition -SqlInstance sqlserver2014a Example 2: Returns the memory conditions for a group of servers from SQL Server Central Management Server (CMS) PS C:\\> Get-DbaRegServer -SqlInstance sqlserver2014a -Group GroupName | Get-DbaMemoryCondition | Out-GridView Returns the memory conditions for a group of servers from SQL Server Central Management Server (CMS). Send output to GridView. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 utilization metrics at that point in time. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Runtime: DateTime when the query was executed in the instance NotificationTime: Calculated DateTime of when the memory pressure event occurred NotificationType: Type of memory notification (e.g., Low Physical Memory, Low Page File, Low Virtual Address Space) MemoryUtilizationPercent: Current memory utilization as a percentage (0-100) TotalPhysicalMemory: Total physical RAM in bytes; dbasize object convertible to KB, MB, GB, TB AvailablePhysicalMemory: Free physical RAM in bytes; dbasize object convertible to KB, MB, GB, TB TotalPageFile: Total page file size in bytes; dbasize object convertible to KB, MB, GB, TB AvailablePageFile: Free page file size in bytes; dbasize object convertible to KB, MB, GB, TB TotalVirtualAddressSpace: Total virtual address space in bytes; dbasize object convertible to KB, MB, GB, TB AvailableVirtualAddressSpace: Free virtual address space in bytes; dbasize object convertible to KB, MB, GB, TB NodeId: NUMA node identifier (for systems with multiple memory nodes) SQLReservedMemory: SQL Server reserved memory in bytes; dbasize object convertible to KB, MB, GB, TB SQLCommittedMemory: SQL Server committed memory in bytes; dbasize object convertible to KB, MB, GB, TB RecordId: Unique identifier for this record in the ring buffer Type: Record type from the resource monitor ring buffer Indicators: Memory pressure indicators value (bit flags representing specific pressure conditions) RecordTime: Ring buffer record timestamp in milliseconds (raw tick count) CurrentTime: Current system time in milliseconds (sys.ms_ticks, for reference and time-based calculations) Size 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, .Terabytes. &nbsp;"
  },
  {
    "name": "Get-DbaMemoryUsage",
    "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.",
    "category": "Performance",
    "tags": [
      "management",
      "os",
      "memory"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaMemoryUsage",
    "popularityRank": 221,
    "synopsis": "Collects memory usage statistics from all SQL Server services using Windows performance counters",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaMemoryUsage View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Collects memory usage statistics from all SQL Server services using Windows performance counters 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. Gathers 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. SSRS does not have memory counters, only memory shrinks and memory pressure state. This function requires local admin role on the targeted computers. Syntax Get-DbaMemoryUsage [[-ComputerName] ] [[-Credential] ] [[-MemoryCounterRegex] ] [[-PlanCounterRegex] ] [[-BufferCounterRegex] ] [[-SSASCounterRegex] ] [[-SSISCounterRegex] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a custom object displaying Server, counter instance, counter, number of pages, memory PS C:\\> Get-DbaMemoryUsage -ComputerName sql2017 Example 2: Logs into the sql2017\\sqlexpress as sqladmin using SQL Authentication then returns results only where memory... PS C:\\> Get-DbaMemoryUsage -ComputerName sql2017\\sqlexpress -SqlCredential sqladmin | Where-Object { $_.Memory.Megabyte -gt 100 } Logs into the sql2017\\sqlexpress as sqladmin using SQL Authentication then returns results only where memory exceeds 100 MB Example 3: Gets results from an array of $servers then diplays them in a gridview PS C:\\> $servers | Get-DbaMemoryUsage | Out-Gridview Optional Parameters -ComputerName Specifies the Windows server to collect memory usage statistics from. Returns data for all SQL Server instances on the server. Use this when you need to monitor memory usage across multiple instances on a single server or compare memory allocation between different servers. | Property | Value | | --- | --- | | Alias | Host,cn,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 workspace usage. Customize this when you need specific memory counters or when working with non-English SQL Server installations where counter names are localized. Default pattern captures the most critical memory allocation counters that DBAs monitor for memory pressure troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (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 statements. Use this to focus on specific plan cache types when investigating plan cache bloat or when working with non-English SQL Server installations. Default pattern captures all major plan cache memory consumers that affect query performance and memory allocation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (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 extensions. Modify this when troubleshooting specific buffer pool issues or working with non-English SQL Server installations where counter names are translated. Default pattern includes essential buffer pool metrics that indicate memory pressure and buffer pool health. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (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. Customize this when monitoring specific SSAS memory usage patterns or working with non-English installations where SSAS counter names are localized. Use when troubleshooting SSAS memory issues or when SSAS and Database Engine compete for server memory resources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (\\\\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. Adjust this when investigating SSIS memory consumption during ETL operations or working with non-English installations where SSIS counter names are translated. Useful for identifying memory bottlenecks in SSIS packages or when multiple SQL Server services compete for available memory. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (memory) | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 match 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 system. Properties: ComputerName: The name of the computer where counters were collected SqlInstance: The SQL Server instance name (mssqlserver for default instance, or the instance name for named instances) CounterInstance: The performance counter instance identifier extracted from the counter path Counter: The name of the Windows performance counter (e.g., Total Server Memory, Free pages, cache pages) 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. Memory: Memory usage as dbasize object in bytes. Conversion varies by counter type: Memory Manager counters: KB converted to bytes (automatic dbasize formatting) Plan Cache counters: Pages 8192 converted to bytes (automatic dbasize formatting) Buffer Manager counters: Pages * 8192 converted to bytes (automatic dbasize formatting) SSAS counters: KB converted to bytes (automatic dbasize formatting) SSIS counters: MB converted to bytes (automatic dbasize formatting) Memory 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, .Terabytes. &nbsp;"
  },
  {
    "name": "Get-DbaModule",
    "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.",
    "category": "Utilities",
    "tags": [
      "general",
      "object",
      "storedprocedure",
      "view",
      "table",
      "trigger"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaModule",
    "popularityRank": 422,
    "synopsis": "Retrieves database modules (stored procedures, functions, views, triggers) modified after a specified date",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaModule View Source Brandon Abshire, netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database modules (stored procedures, functions, views, triggers) modified after a specified date 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. Essential for identifying which stored procedures, functions, views, or triggers were altered during maintenance windows or after application deployments. Returns metadata including modification dates, schema names, and object types, with the actual module definition hidden by default but available when needed. Supports filtering by specific module types and can exclude system objects to focus on user-created code changes. Syntax Get-DbaModule [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-ModifiedSince] ] [[-Type] ] [-ExcludeSystemDatabases] [-ExcludeSystemObjects] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Return all modules for servers sql2008 and sqlserver2012 sorted by Database, Modify_Date ASC PS C:\\> Get-DbaModule -SqlInstance sql2008, sqlserver2012 Example 2: Shows hidden definition column (informative wall of text) PS C:\\> Get-DbaModule -SqlInstance sql2008, sqlserver2012 | Select-Object Example 3: Return all modules on server sql2008 for only the TestDB database with a modified date after 1 January 2017... PS C:\\> Get-DbaModule -SqlInstance sql2008 -Database TestDB -ModifiedSince \"2017-01-01 10:00:00\" Return all modules on server sql2008 for only the TestDB database with a modified date after 1 January 2017 10:00:00 AM. Example 4: Return all modules on server sql2008 for all databases that are triggers, views or scalar functions PS C:\\> Get-DbaModule -SqlInstance sql2008 -Type View, Trigger, ScalarFunction Example 5: Return all modules on server sql2008 for only the TestDB database that are stored procedures, views or scalar... PS C:\\> 'sql2008' | Get-DbaModule -Database TestDB -Type View, StoredProcedure, ScalarFunction Return all modules on server sql2008 for only the TestDB database that are stored procedures, views or scalar functions. Input via Pipeline Example 6: Return all modules on server sql2008 for all user databases that are triggers, views or scalar functions PS C:\\> Get-DbaDatabase -SqlInstance sql2008 -ExcludeSystem | Get-DbaModule -Type View, Trigger, ScalarFunction Example 7: Return all user created stored procedures in the system databases for servers sql2008 and sqlserver2012 PS C:\\> Get-DbaDatabase -SqlInstance sql2008, sqlserver2012 -ExcludeUser | Get-DbaModule -Type StoredProcedure -ExcludeSystemObjects Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for modified modules. Accepts database names or wildcards for pattern matching. Use this when you need to focus on specific databases rather than scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Commonly used to exclude databases under maintenance or those known to have frequent module changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ModifiedSince Returns only modules modified after this date and time. Defaults to 1900-01-01 to include all modules. Essential for tracking recent code changes after deployments, maintenance windows, or troubleshooting sessions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1900-01-01 | -Type Filters results to specific module types only. Valid choices include: View, TableValuedFunction, DefaultConstraint, StoredProcedure, Rule, InlineTableValuedFunction, Trigger, ScalarFunction. Use this when investigating specific types of database objects, such as finding all modified stored procedures after an application release. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | View,TableValuedFunction,DefaultConstraint,StoredProcedure,Rule,InlineTableValuedFunction,Trigger,ScalarFunction | -ExcludeSystemDatabases Excludes system databases (master, model, msdb, tempdb) from the search. Focus on user databases only. Recommended for routine auditing since system database changes are typically handled by SQL Server updates rather than application deployments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeSystemObjects Excludes Microsoft-shipped system objects from results. Shows only user-created modules. Use this to filter out built-in SQL Server objects and focus on custom business logic that your team maintains. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database objects from Get-DbaDatabase for pipeline operations. Allows chaining commands together. Useful for complex filtering scenarios where you first select databases with specific criteria, then search for modules within those databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database module (stored procedure, function, view, trigger, etc.) found in the specified databases that matches the filter criteria. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the module Name: The name of the module object ObjectID: The SQL Server object ID (int) SchemaName: The name of the schema containing the module 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) CreateDate: DateTime when the module was first created ModifyDate: DateTime when the module was last modified IsMsShipped: Boolean indicating if the module is a Microsoft-shipped system object ExecIsStartUp: Boolean indicating if the stored procedure is configured to run at SQL Server startup (for stored procedures only) Definition: The source code definition of the module (hidden by default, use Select-Object to view) &nbsp;"
  },
  {
    "name": "Get-DbaMsdtc",
    "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",
    "category": "Utilities",
    "tags": [
      "msdtc",
      "dtc",
      "general"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaMsdtc",
    "popularityRank": 488,
    "synopsis": "Retrieves Microsoft Distributed Transaction Coordinator (MSDTC) service status and configuration details",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaMsdtc View Source Klaas Vandenberghe (@powerdbaklaas) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Microsoft Distributed Transaction Coordinator (MSDTC) service status and configuration details 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. This 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. Requires: Windows administrator access on target servers Syntax Get-DbaMsdtc [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get DTC status for the server srv0042 PS C:\\> Get-DbaMsdtc -ComputerName srv0042 Example 2: Get DTC status for all the computers in a .txt file PS C:\\> $Computers = (Get-Content D:\\configfiles\\SQL\\MySQLInstances.txt | % {$_.split('\\')[0]}) PS C:\\> $Computers | Get-DbaMsdtc Example 3: Get DTC status for all the computers where the MSDTC Service is not running PS C:\\> Get-DbaMsdtc -Computername $Computers | Where-Object { $_.dtcservicestate -ne 'running' } Example 4: Get DTC status for the computer srv0042 and show in a grid view PS C:\\> Get-DbaMsdtc -ComputerName srv0042 | Out-Gridview Optional Parameters -ComputerName Specifies the server or computer names where MSDTC information should be retrieved. Accepts multiple values and supports pipeline input. Use this when checking MSDTC configuration across multiple SQL Server hosts, especially when troubleshooting distributed transactions or linked server issues. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Alternative credential | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties: ComputerName: The name of the target computer DTCServiceName: The display name of the MSDTC service (Microsoft Distributed Transaction Coordinator) DTCServiceState: The current state of the MSDTC service (Running, Stopped, Paused, etc.) DTCServiceStatus: The operational status of the MSDTC service (OK, Degraded, etc.) DTCServiceStartMode: The start mode configuration of the service (Auto, Manual, Disabled) DTCServiceAccount: The Windows account under which the MSDTC service runs DTCCID_MSDTC: Component identifier (CID) for the MSDTC component (null if not available) DTCCID_MSDTCUIS: Component identifier for the MSDTC User Interface Service component (null if not available) DTCCID_MSDTCTIPGW: Component identifier for the MSDTC TIP Gateway component (null if not available) DTCCID_MSDTCXATM: Component identifier for the MSDTC XA Transaction Manager component (null if not available) networkDTCAccess: Boolean indicating if network DTC access is enabled networkDTCAccessAdmin: Boolean indicating if network DTC admin access is enabled networkDTCAccessClients: Boolean indicating if DTC network access is enabled for clients networkDTCAccessInbound: Boolean indicating if inbound network DTC transactions are enabled networkDTCAccessOutBound: Boolean indicating if outbound network DTC transactions are enabled networkDTCAccessTip: Boolean indicating if TIP (Transaction Internet Protocol) access is enabled networkDTCAccessTransactions: Boolean indicating if network DTC transactions are enabled XATransactions: Boolean indicating if XA (eXtended Architecture) transactions are enabled &nbsp;"
  },
  {
    "name": "Get-DbaNetworkActivity",
    "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).",
    "category": "Utilities",
    "tags": [
      "server",
      "management",
      "network"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaNetworkActivity",
    "popularityRank": 412,
    "synopsis": "Retrieves real-time network traffic statistics for all network interfaces on SQL Server host computers.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaNetworkActivity View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves real-time network traffic statistics for all network interfaces on SQL Server host computers. 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. The 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. Requires Local Admin rights on destination computer(s). Syntax Get-DbaNetworkActivity [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the Current traffic on every Network Interface on computer sqlserver2014a PS C:\\> Get-DbaNetworkActivity -ComputerName sqlserver2014a Example 2: Gets the Current traffic on every Network Interface on computers sql1, sql2 and sql3 PS C:\\> 'sql1','sql2','sql3' | Get-DbaNetworkActivity Example 3: Gets the Current traffic on every Network Interface on computers sql1 and sql2 PS C:\\> Get-DbaNetworkActivity -ComputerName sql1,sql2 Optional Parameters -ComputerName Specifies the computer names or SQL Server instances to monitor network activity. Function extracts the computer name from full instance names and resolves them to fully qualified domain names. Defaults to the local computer when not specified. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Credential object used to connect to the computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Win32_PerfFormattedData_Tcpip_NetworkInterface Returns one object per network interface found on the target computer(s). Default display properties (via Select-DefaultView): ComputerName: The name of the computer containing the network interface NIC: The name of the network interface (alias for Name property) BytesReceivedPersec: Bytes received per second on this interface (numeric value) BytesSentPersec: Bytes sent per second on this interface (numeric value) BytesTotalPersec: Total bytes per second (received + sent) on this interface (numeric value) Bandwidth: Human-readable interface bandwidth capacity (10Gb, 1Gb, 100Mb, 10Mb, 1Mb, 100Kb, or Low) Additional properties available (from Win32_PerfFormattedData_Tcpip_NetworkInterface): CurrentBandwidth: Numeric bandwidth in bits per second (used to calculate display Bandwidth) OutputQueueLength: Queue length for outbound data PacketsReceivedPersec: Number of packets received per second PacketsSentPersec: Number of packets sent per second PacketsOutboundErrors: Number of transmission errors PacketsReceivedErrors: Number of receive errors PacketsReceivedDiscarded: Number of received packets discarded PacketsOutboundDiscarded: Number of transmitted packets discarded All properties from the base WMI object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaNetworkCertificate",
    "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't appear in the results. Useful for auditing SSL configurations, troubleshooting encrypted connection issues, and verifying certificate assignments across multiple instances.",
    "category": "Security",
    "tags": [
      "certificate",
      "encryption",
      "security"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaNetworkCertificate",
    "popularityRank": 133,
    "synopsis": "Retrieves the certificate currently configured for SQL Server network encryption.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaNetworkCertificate View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves the certificate currently configured 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't appear in the results. Useful for auditing SSL configurations, troubleshooting encrypted connection issues, and verifying certificate assignments across multiple instances. Syntax Get-DbaNetworkCertificate [[-SqlInstance] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets computer certificate for the standard instance on sql2016 that is being used for SQL Server network... PS C:\\> Get-DbaNetworkCertificate -SqlInstance sql2016 Gets computer certificate for the standard instance on sql2016 that is being used for SQL Server network encryption Example 2: Gets computer certificate for the named instance sql2017 on server1 that is being used for SQL Server network... PS C:\\> Get-DbaNetworkCertificate -SqlInstance server1\\sql2017 Gets computer certificate for the named instance sql2017 on server1 that is being used for SQL Server network encryption Optional Parameters -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. | Property | Value | | --- | --- | | Alias | ComputerName | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Alternate credential object to use for accessing the target computer(s). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) VSName: Virtual Server Name if applicable (for clustered instances) ServiceAccount: The Windows service account running SQL Server ForceEncryption: Boolean indicating if encryption is forced for all connections FriendlyName: Human-readable certificate name from the certificate store DnsNameList: Array of DNS names in the certificate's Subject Alternative Names Thumbprint: SHA-1 hash thumbprint of the certificate Generated: DateTime when the certificate becomes valid (NotBefore) Expires: DateTime when the certificate expires (NotAfter) IssuedTo: Certificate subject (who it was issued to) IssuedBy: Certificate issuer name Certificate: The full X509Certificate2 object with complete certificate information &nbsp;"
  },
  {
    "name": "Get-DbaNetworkConfiguration",
    "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",
    "category": "Utilities",
    "tags": [
      "connection",
      "sqlwmi"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaNetworkConfiguration",
    "popularityRank": 241,
    "synopsis": "Retrieves SQL Server network protocols, TCP/IP settings, and SSL certificate configuration from SQL Server Configuration Manager",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaNetworkConfiguration View Source Andreas Jordan (@JordanOrdix), ordix.de Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server network protocols, TCP/IP settings, and SSL certificate configuration from SQL Server Configuration Manager 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. The 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. Since 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. For a detailed explanation of the different properties see the documentation at: https://docs.microsoft.com/en-us/sql/tools/configuration-manager/sql-server-network-configuration Syntax Get-DbaNetworkConfiguration [-SqlInstance] [[-Credential] ] [[-OutputType] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the network configuration for the default instance on sqlserver2014a PS C:\\> Get-DbaNetworkConfiguration -SqlInstance sqlserver2014a Example 2: Returns information about the server protocols for the sqlexpress on winserver and the default instance on... PS C:\\> Get-DbaNetworkConfiguration -SqlInstance winserver\\sqlexpress, sql2016 -OutputType ServerProtocols Returns information about the server protocols for the sqlexpress on winserver and the default instance on sql2016. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Credential object used to connect to the Computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OutputType Controls which network configuration details are returned from SQL Server Configuration Manager. Use this to focus on specific troubleshooting areas or reduce output when checking multiple instances. Valid options: Full, ServerProtocols, TcpIpProperties, TcpIpAddresses, Certificate (defaults to Full). Full provides complete network configuration including all protocols, TCP/IP settings, IP bindings, and SSL certificate details. ServerProtocols shows only whether Shared Memory, Named Pipes, and TCP/IP protocols are enabled. TcpIpProperties returns TCP/IP protocol settings like KeepAlive timeout and whether the instance listens on all IP addresses. TcpIpAddresses displays port configurations and IP address bindings for connection troubleshooting. Certificate outputs SSL certificate information and encryption enforcement settings for security audits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Full | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Default (-OutputType Full) returns a PSCustomObject with the following properties: ComputerName: Computer name of the SQL Server instance InstanceName: SQL Server instance name SqlInstance: Full SQL Server instance name (computer\\instance format) SharedMemoryEnabled: Boolean indicating if Shared Memory protocol is enabled NamedPipesEnabled: Boolean indicating if Named Pipes protocol is enabled TcpIpEnabled: Boolean indicating if TCP/IP protocol is enabled TcpIpProperties: Nested object containing Enabled, KeepAlive, and ListenAll properties for TCP/IP configuration TcpIpAddresses: Array of objects representing IP address configurations with properties like Name, Active, Enabled, IpAddress, TcpDynamicPorts, and TcpPort Certificate: Nested object containing SSL certificate information (FriendlyName, DnsNameList, Thumbprint, Generated, Expires, IssuedTo, IssuedBy, Certificate object) SuitableCertificate: Array of certificates from the local machine store that are suitable for SQL Server encryption based on key usage, signature algorithm, validity, and DNS names Advanced: Nested object containing advanced settings (ForceEncryption, HideInstance, AcceptedSPNs, ExtendedProtection) When -OutputType ServerProtocols is specified: ComputerName: Computer name of the SQL Server instance InstanceName: SQL Server instance name SqlInstance: Full SQL Server instance name (computer\\instance format) SharedMemoryEnabled: Boolean indicating if Shared Memory protocol is enabled NamedPipesEnabled: Boolean indicating if Named Pipes protocol is enabled TcpIpEnabled: Boolean indicating if TCP/IP protocol is enabled When -OutputType TcpIpProperties is specified: ComputerName: Computer name of the SQL Server instance InstanceName: SQL Server instance name SqlInstance: Full SQL Server instance name (computer\\instance format) Enabled: Value indicating if TCP/IP protocol is enabled KeepAlive: TCP KeepAlive timeout setting value ListenAll: Value indicating if instance listens on all IP addresses When -OutputType TcpIpAddresses is specified: If ListenAll is True, returns one object for IPAll: ComputerName: Computer name of the SQL Server instance InstanceName: SQL Server instance name SqlInstance: Full SQL Server instance name (computer\\instance format) Name: IP configuration name (IPAll) TcpDynamicPorts: Dynamic port configuration (empty or port number) TcpPort: Static port number configuration If ListenAll is False, returns one object per configured IP address: ComputerName: Computer name of the SQL Server instance InstanceName: SQL Server instance name SqlInstance: Full SQL Server instance name (computer\\instance format) Name: IP configuration name (e.g., IP1, IP2, IPV6) Active: Value indicating if this IP configuration is active Enabled: Value indicating if this IP configuration is enabled IpAddress: The IP address (IPv4 or IPv6) TcpDynamicPorts: Dynamic port configuration (empty or port number) TcpPort: Static port number configuration When -OutputType Certificate is specified: ComputerName: Computer name of the SQL Server instance InstanceName: SQL Server instance name SqlInstance: Full SQL Server instance name (computer\\instance format) VSName: Virtual Server Name (if applicable; omitted if not present) ServiceAccount: Service account running SQL Server ForceEncryption: Boolean indicating if encryption is forced for all connections FriendlyName: Human-readable certificate name DnsNameList: Array of DNS names in the certificate's Subject Alternative Names Thumbprint: SHA-1 hash thumbprint of the certificate Generated: DateTime when the certificate becomes valid (NotBefore) Expires: DateTime when the certificate expires (NotAfter) IssuedTo: Certificate subject (who it was issued to) IssuedBy: Certificate issuer name Certificate: The full X509Certificate2 object with complete certificate information &nbsp;"
  },
  {
    "name": "Get-DbaNetworkEncryption",
    "description": "Connects directly to a SQL Server instance's TCP port and retrieves the TLS/SSL certificate\nthat the server presents during the TLS handshake. This does not require Windows host access\nor WinRM - it works purely over the network like a client connecting to SQL Server.\n\nThis complements Get-DbaNetworkCertificate, which reads the configured certificate from the\nWindows registry (requires WinRM). This command instead shows what certificate is actually\nbeing presented to clients over the network, without requiring any host-level access.\n\nFor named instances, the SQL Browser service is queried on UDP port 1434 to determine the\nTCP port number. For default instances, port 1433 is used unless overridden.",
    "category": "Security",
    "tags": [
      "certificate",
      "encryption",
      "security",
      "network"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaNetworkEncryption",
    "popularityRank": 0,
    "synopsis": "Retrieves the TLS/SSL certificate presented by a SQL Server instance over the network.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaNetworkEncryption View Source the dbatools team + Claude Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves the TLS/SSL certificate presented by a SQL Server instance over the network. Description Connects directly to a SQL Server instance's TCP port and retrieves the TLS/SSL certificate that the server presents during the TLS handshake. This does not require Windows host access or WinRM - it works purely over the network like a client connecting to SQL Server. This complements Get-DbaNetworkCertificate, which reads the configured certificate from the Windows registry (requires WinRM). This command instead shows what certificate is actually being presented to clients over the network, without requiring any host-level access. For named instances, the SQL Browser service is queried on UDP port 1434 to determine the TCP port number. For default instances, port 1433 is used unless overridden. Syntax Get-DbaNetworkEncryption [-SqlInstance] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Retrieves the TLS certificate presented by the default SQL Server instance on sql2016 PS C:\\> Get-DbaNetworkEncryption -SqlInstance sql2016 Example 2: Retrieves the TLS certificate presented by the named instance sqlexpress on sql2016 PS C:\\> Get-DbaNetworkEncryption -SqlInstance sql2016\\sqlexpress Retrieves the TLS certificate presented by the named instance sqlexpress on sql2016. Queries the SQL Browser service to determine the port. Example 3: Retrieves certificates from multiple SQL Server instances and shows key certificate details PS C:\\> Get-DbaNetworkEncryption -SqlInstance sql2016, sql2017, sql2019 | Select-Object SqlInstance, Subject, Expires, Thumbprint Example 4: Finds SQL Server instances whose TLS certificates expire within the next 30 days PS C:\\> $servers | Get-DbaNetworkEncryption | Where-Object { $_.Expires -lt (Get-Date).AddDays(30) } Required Parameters -SqlInstance The target SQL Server instance or instances. Accepts pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance that successfully presents a TLS certificate. Properties: ComputerName: The hostname of the SQL Server InstanceName: The SQL Server instance name (MSSQLSERVER for default) SqlInstance: The full SQL Server instance identifier Subject: The certificate subject (Common Name) Issuer: The certificate issuer Thumbprint: SHA-1 hash thumbprint of the certificate NotBefore: DateTime when the certificate becomes valid Expires: DateTime when the certificate expires DnsNameList: Array of DNS names from the Subject Alternative Names extension SerialNumber: Certificate serial number Certificate: The full X509Certificate2 object &nbsp;"
  },
  {
    "name": "Get-DbaOleDbProvider",
    "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's 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't accessible.",
    "category": "Utilities",
    "tags": [
      "general",
      "oledb"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaOleDbProvider",
    "popularityRank": 573,
    "synopsis": "Retrieves OLE DB provider configurations registered with SQL Server for linked servers and distributed queries",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaOleDbProvider View Source Chrissy LeMaire (@cl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves OLE DB provider configurations registered with SQL Server for linked servers and distributed queries 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's 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't accessible. Syntax Get-DbaOleDbProvider [-SqlInstance] [[-SqlCredential] ] [[-Provider] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a list of all OleDb providers on SqlBox1\\Instance2 PS C:\\> Get-DbaOleDbProvider -SqlInstance SqlBox1\\Instance2 Example 2: Returns the SSISOLEDB provider on SqlBox1\\Instance2 PS C:\\> Get-DbaOleDbProvider -SqlInstance SqlBox1\\Instance2 -Provider SSISOLEDB Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Provider Filters results to specific OLE DB provider names. Accepts an array of provider names for targeting multiple providers. Use this when you need to check configuration for specific providers like SQLNCLI11 or MSDASQL instead of listing all available providers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.OleDbProviderSettings Returns one OleDbProviderSettings object per OLE DB provider configured on the SQL Server instance. Default display properties (via Select-DefaultView): ComputerName: Computer name of the SQL Server instance InstanceName: SQL Server instance name SqlInstance: Full SQL Server instance name (computer\\instance format) Name: OLE DB provider name (e.g., SQLNCLI11, MSDASQL, SSISOLEDB) Description: Human-readable description of the provider AllowInProcess: Boolean indicating if the provider is allowed to run in-process with SQL Server DisallowAdHocAccess: Boolean indicating if ad hoc access (OPENROWSET, OPENDATASOURCE) is disallowed DynamicParameters: Boolean indicating if the provider supports dynamic parameters IndexAsAccessPath: Boolean indicating if the provider supports indexes as access paths LevelZeroOnly: Boolean indicating if only level zero (table-level) operations are allowed NestedQueries: Boolean indicating if the provider supports nested queries NonTransactedUpdates: Boolean indicating if the provider supports non-transacted updates Additional properties available (from SMO OleDbProviderSettings object): Parent: Reference to the parent Server object Urn: The Uniform Resource Name of the provider object Properties: Collection of property objects State: Current state of the SMO object (Existing, Creating, Deleting, etc.) Uid: Unique identifier for the provider setting All properties from the base SMO OleDbProviderSettings object are accessible using Select-Object * even though only the default properties are displayed without it. &nbsp;"
  },
  {
    "name": "Get-DbaOpenTransaction",
    "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/",
    "category": "Utilities",
    "tags": [
      "diagnostic",
      "process",
      "session",
      "activitymonitor"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaOpenTransaction",
    "popularityRank": 421,
    "synopsis": "Retrieves detailed information about open database transactions across SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaOpenTransaction View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed information about open database transactions across SQL Server instances. 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. This 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. This command is based on the open transaction monitoring script published by Paul Randal. Reference: https://www.sqlskills.com/blogs/paul/script-open-transactions-with-text-and-plans/ Syntax Get-DbaOpenTransaction [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns open transactions for sqlserver2014a PS C:\\> Get-DbaOpenTransaction -SqlInstance sqlserver2014a Example 2: Logs into sqlserver2014a using the login &quot;sqladmin&quot; PS C:\\> Get-DbaOpenTransaction -SqlInstance sqlserver2014a -SqlCredential sqladmin Required Parameters -SqlInstance The SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Management.Automation.PSCustomObject Returns one object per open transaction found on the specified instance(s). If no open transactions exist, nothing is returned. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name (defaults to 'MSSQLSERVER' for default instances) SqlInstance: The full SQL Server instance name as registered on the server Spid: The session ID (process ID) of the session holding the open transaction Login: The login name associated with the session Database: The name of the database in which the transaction is open BeginTime: DateTime when the transaction began LogBytesUsed: Number of bytes of transaction log space currently used by this transaction LogBytesReserved: Number of bytes of transaction log space reserved by this transaction LastQuery: The text of the most recently executed SQL command in the session LastPlan: The execution plan XML for the most recently executed query (can be NULL if not available) &nbsp;"
  },
  {
    "name": "Get-DbaOperatingSystem",
    "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.",
    "category": "Utilities",
    "tags": [
      "management",
      "os",
      "operatingsystem"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaOperatingSystem",
    "popularityRank": 210,
    "synopsis": "Retrieves comprehensive Windows operating system details from SQL Server host machines.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaOperatingSystem View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves comprehensive Windows operating system details from SQL Server host machines. 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. Syntax Get-DbaOperatingSystem [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns information about the local computer&#39;s operating system PS C:\\> Get-DbaOperatingSystem Example 2: Returns information about the sql2016&#39;s operating system PS C:\\> Get-DbaOperatingSystem -ComputerName sql2016 Example 3: Returns information about the sql2016 and sql2017 operating systems using alternative Windows credentials PS C:\\> $wincred = Get-Credential ad\\sqladmin PS C:\\> 'sql2016', 'sql2017' | Get-DbaOperatingSystem -Credential $wincred Example 4: Returns information about all the servers operating system that are stored in the file PS C:\\> Get-Content .\\servers.txt | Get-DbaOperatingSystem Returns 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. Optional Parameters -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. Use 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. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Alternate credential object to use for accessing the target computer(s). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per computer containing comprehensive Windows operating system details. Default display properties (via Select-DefaultView): ComputerName: The name of the computer Manufacturer: The manufacturer of the computer hardware (e.g., Dell, HP, VMware) Organization: The organization assigned to the computer Architecture: The processor architecture (x64 or x86) Version: The Windows version identifier OSVersion: The friendly operating system version name (e.g., Windows Server 2019 Standard) LastBootTime: DateTime of the most recent system boot LocalDateTime: Current DateTime on the system PowerShellVersion: The installed PowerShell version (e.g., 5.1) TimeZone: The current time zone of the system TotalVisibleMemory: Total physical RAM available (dbasize object with unit conversion) ActivePowerPlan: The active Windows power plan (e.g., High Performance) LanguageNative: The native name of the configured OS language *Additional properties available (use Select-Object ):** Build: The Windows build number SPVersion: Service Pack version number InstallDate: DateTime when the operating system was installed BootDevice: The device from which the system boots SystemDevice: The device containing the operating system files SystemDrive: The drive letter of the system drive WindowsDirectory: The full path to the Windows directory PagingFileSize: Current paging file size in KB FreePhysicalMemory: Currently available physical RAM (dbasize object) TotalVirtualMemory: Total virtual memory available (dbasize object) FreeVirtualMemory: Currently available virtual memory (dbasize object) Status: Current system status Language: The Display name of the configured OS language LanguageId: The LCID (Locale ID) of the OS language LanguageKeyboardLayoutId: The keyboard layout ID LanguageTwoLetter: Two-letter ISO language code LanguageThreeLetter: Three-letter ISO language code LanguageAlias: Language alias name CodeSet: The code set character encoding CountryCode: The country code Locale: The locale identifier IsWsfc: Boolean indicating if Windows Server Failover Clustering service is installed &nbsp;"
  },
  {
    "name": "Get-DbaPageFileSetting",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "management",
      "os",
      "pagefile"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPageFileSetting",
    "popularityRank": 492,
    "synopsis": "Retrieves Windows page file configuration from SQL Server host computers for performance analysis.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPageFileSetting View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows page file configuration from SQL Server host computers for performance analysis. 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. The 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. Note that this may require local administrator privileges for the relevant computers. Syntax Get-DbaPageFileSetting [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a custom object displaying ComputerName, AutoPageFile, FileName, Status, LastModified, LastAccessed... PS C:\\> Get-DbaPageFileSetting -ComputerName ServerA,ServerB Returns a custom object displaying ComputerName, AutoPageFile, FileName, Status, LastModified, LastAccessed, AllocatedBaseSize, InitialSize, MaximumSize, PeakUsage, CurrentUsage for ServerA and ServerB Example 2: Returns a custom object displaying ComputerName, AutoPageFile, FileName, Status, LastModified, LastAccessed... PS C:\\> 'ServerA' | Get-DbaPageFileSetting Returns a custom object displaying ComputerName, AutoPageFile, FileName, Status, LastModified, LastAccessed, AllocatedBaseSize, InitialSize, MaximumSize, PeakUsage, CurrentUsage for ServerA Optional Parameters -ComputerName Specifies the target SQL Server host computers to retrieve page file settings from. Accepts computer names, IP addresses, or SQL Server instance names. Use this to analyze page file configurations across your SQL Server infrastructure for capacity planning and performance troubleshooting. Defaults to the local computer if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | $env:COMPUTERNAME | -Credential Credential object used to connect to the Computer as a different user | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Computer.PageFileSetting Returns 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. Properties: ComputerName: The name of the target computer AutoPageFile: Boolean indicating if page file is automatically managed by Windows FileName: Logical name of the page file (null for auto-managed) Status: Status of the page file from WMI (typically \"OK\", null for auto-managed) SystemManaged: Boolean indicating if both InitialSize and MaximumSize are zero (null for auto-managed) LastModified: DateTime of last page file modification (null for auto-managed) LastAccessed: DateTime of last page file access (null for auto-managed) AllocatedBaseSize: Current allocated size in megabytes between Initial and Maximum sizes (null for auto-managed) InitialSize: Initial page file size in megabytes (null for auto-managed) MaximumSize: Maximum page file size in megabytes (null for auto-managed) PeakUsage: Peak page file usage in megabytes since system startup (null for auto-managed) CurrentUsage: Current page file usage in megabytes (null for auto-managed) &nbsp;"
  },
  {
    "name": "Get-DbaPbmCategory",
    "description": "Retrieves all policy categories configured in SQL Server's 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.",
    "category": "Utilities",
    "tags": [
      "policy",
      "policybasedmanagement",
      "pbm"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPbmCategory",
    "popularityRank": 648,
    "synopsis": "Retrieves Policy-Based Management categories from SQL Server instances for governance and compliance management.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPbmCategory View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Policy-Based Management categories from SQL Server instances for governance and compliance management. Description Retrieves all policy categories configured in SQL Server's 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. Syntax Get-DbaPbmCategory [[-SqlInstance] ] [[-SqlCredential] ] [[-Category] ] [[-InputObject] ] [-ExcludeSystemObject] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all policy categories from the sql2016 PBM server PS C:\\> Get-DbaPbmCategory -SqlInstance sql2016 Example 2: Uses a credential $cred to connect and return all policy categories from the sql2016 PBM server PS C:\\> Get-DbaPbmCategory -SqlInstance sql2016 -SqlCredential $cred Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Category Filters results to only show specific policy categories by name. Accepts multiple category names for targeted retrieval. Use this when you need to check specific categories rather than retrieving all configured PBM categories. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Policy-Based Management store objects from Get-DbaPbmStore for processing categories from specific stores. Use this when you need to work with categories from a pre-filtered set of PBM stores or when chaining multiple PBM commands together. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -ExcludeSystemObject Excludes built-in system policy categories from the results, showing only user-created categories. Use this when you want to focus on custom categories that you or your team have created, filtering out SQL Server's default categories. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Sdk.Sfc.ISfcInstance Returns one policy category object per category found on the target PBM store(s). Each category object includes connection context properties and policy category metadata. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: The unique identifier for the policy category Name: The name of the policy category MandateDatabaseSubscriptions: Boolean indicating if databases must be subscribed to this category for automatic policy evaluation &nbsp;"
  },
  {
    "name": "Get-DbaPbmCategorySubscription",
    "description": "Retrieves all database subscriptions to policy categories from SQL Server's 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.",
    "category": "Utilities",
    "tags": [
      "policy",
      "policybasedmanagement",
      "pbm"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPbmCategorySubscription",
    "popularityRank": 670,
    "synopsis": "Retrieves database subscriptions to Policy-Based Management categories that control automatic policy evaluation.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPbmCategorySubscription View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves database subscriptions to Policy-Based Management categories that control automatic policy evaluation. Description Retrieves all database subscriptions to policy categories from SQL Server's 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. Syntax Get-DbaPbmCategorySubscription [[-SqlInstance] ] [[-SqlCredential] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all policy category subscriptions from the sql2016 PBM server PS C:\\> Get-DbaPbmCategorySubscription -SqlInstance sql2016 Example 2: Uses a credential $cred to connect and return all policy category subscriptions from the sql2016 PBM server PS C:\\> Get-DbaPbmCategorySubscription -SqlInstance sql2016 -SqlCredential $cred Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Policy-Based Management store objects from Get-DbaPbmStore for pipeline processing. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Dmf.PolicyCategorySubscription Returns 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 categories. Default display properties (via Select-DefaultView, excluding Properties, Urn, and Parent): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) PolicyCategory: The name of the policy category this subscription applies to Target: The target object (database or other SQL Server object) subscribed to this category TargetType: The type of the target object being subscribed ID: Unique identifier for the subscription State: Current state of the subscription object (Existing, Creating, Pending, etc.) IdentityKey: Identity key of the subscription object Metadata: Metadata information for the subscription KeyChain: Identity path of the subscription object *Additional properties available via Select-Object :** Properties: Properties collection for the subscription Urn: Uniform Resource Name (URN) for the subscription object Parent: Reference to the parent PolicyStore object &nbsp;"
  },
  {
    "name": "Get-DbaPbmCondition",
    "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.",
    "category": "Utilities",
    "tags": [
      "policy",
      "policybasedmanagement",
      "pbm"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPbmCondition",
    "popularityRank": 682,
    "synopsis": "Retrieves Policy-Based Management conditions from SQL Server instances for compliance monitoring and policy evaluation.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPbmCondition View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Policy-Based Management conditions from SQL Server instances for compliance monitoring and policy evaluation. 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. Syntax Get-DbaPbmCondition [[-SqlInstance] ] [[-SqlCredential] ] [[-Condition] ] [[-InputObject] ] [-IncludeSystemObject] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all conditions from the sql2016 PBM server PS C:\\> Get-DbaPbmCondition -SqlInstance sql2016 Example 2: Uses a credential $cred to connect and return all conditions from the sql2016 PBM server PS C:\\> Get-DbaPbmCondition -SqlInstance sql2016 -SqlCredential $cred Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Condition Filters results to only return conditions that match the specified names. Accepts multiple condition names and supports wildcards. Use this when you need to examine specific PBM conditions rather than retrieving all conditions from the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when processing conditions from multiple instances or when working with previously retrieved PBM store objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -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. Use this when you need to see all available conditions including Microsoft's built-in templates for policy creation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Dmf.Condition Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: Unique identifier for the condition Name: The name of the condition CreateDate: DateTime when the condition was created CreatedBy: User who created the condition DateModified: DateTime when the condition was last modified Description: Description of the condition ExpressionNode: The expression tree that defines the condition logic Facet: The facet that the condition applies to (management area such as Database, Server, Table, etc.) HasScript: Boolean indicating if the condition contains a dynamic script expression IsSystemObject: Boolean indicating if this is a system-provided condition or user-created ModifiedBy: User who last modified the condition *Additional properties available via Select-Object :** IsEnumerable: Boolean indicating if the condition can be used as a target set level filter Parent: Reference to the parent PolicyStore object State: Current state of the condition object (Existing, Creating, Pending, etc.) Urn: Uniform Resource Name (URN) for the condition object IdentityKey: Identity key of the condition object Metadata: Metadata information KeyChain: Identity path of the condition object Properties: Properties collection for the condition &nbsp;"
  },
  {
    "name": "Get-DbaPbmObjectSet",
    "description": "Retrieves object sets from SQL Server's 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.",
    "category": "Utilities",
    "tags": [
      "policy",
      "policybasedmanagement",
      "pbm"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPbmObjectSet",
    "popularityRank": 652,
    "synopsis": "Retrieves Policy-Based Management object sets from SQL Server instances",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPbmObjectSet View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Policy-Based Management object sets from SQL Server instances Description Retrieves object sets from SQL Server's 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. Syntax Get-DbaPbmObjectSet [[-SqlInstance] ] [[-SqlCredential] ] [[-ObjectSet] ] [[-InputObject] ] [-IncludeSystemObject] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all object sets from the sql2016 PBM instance PS C:\\> Get-DbaPbmObjectSet -SqlInstance sql2016 Example 2: Uses a credential $cred to connect and return all object sets from the sql2016 PBM instance PS C:\\> Get-DbaPbmObjectSet -SqlInstance sql2016 -SqlCredential $cred Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ObjectSet Specifies the name(s) of specific Policy-Based Management object sets to retrieve. Accepts multiple values and supports wildcards. Use this when you need to examine particular object sets rather than retrieving all available sets from the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Policy-Based Management store objects from Get-DbaPbmStore via pipeline input for processing multiple stores. Use this when you need to process object sets from multiple SQL Server instances or when chaining PBM commands together. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -IncludeSystemObject Includes SQL Server system object sets in the results, which are excluded by default to focus on user-defined sets. Use this when you need to audit or examine Microsoft's built-in Policy-Based Management object sets for compliance or educational purposes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Dmf.ObjectSet Returns one ObjectSet object per object set found on the specified SQL Server instance(s). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ID: Unique identifier for the object set Name: Name of the object set Facet: The facet that this object set targets (e.g., Server, Database, Table) TargetSets: Collection of target sets that define the objects included in this set IsSystemObject: Boolean indicating if this is a Microsoft system object set Additional properties available (from SMO ObjectSet object): Parent: Reference to the parent PolicyStore object IdentityKey: The identity key for the object Urn: The Uniform Resource Name State: The current state of the SMO object (Existing, Creating, Pending, Dropping, etc.) Metadata: The object metadata All properties from the base SMO ObjectSet object are accessible using Select-Object * even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Get-DbaPbmPolicy",
    "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's Policy-Based Management node.",
    "category": "Utilities",
    "tags": [
      "policy",
      "policybasedmanagement",
      "pbm"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPbmPolicy",
    "popularityRank": 574,
    "synopsis": "Retrieves Policy-Based Management policies from SQL Server instances for compliance auditing and configuration review.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPbmPolicy View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Policy-Based Management policies from SQL Server instances for compliance auditing and configuration review. 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's Policy-Based Management node. Syntax Get-DbaPbmPolicy [[-SqlInstance] ] [[-SqlCredential] ] [[-Policy] ] [[-Category] ] [[-InputObject] ] [-IncludeSystemObject] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all policies from sql2016 server PS C:\\> Get-DbaPbmPolicy -SqlInstance sql2016 Example 2: Uses a credential $cred to connect and return all policies from sql2016 instance PS C:\\> Get-DbaPbmPolicy -SqlInstance sql2016 -SqlCredential $cred Example 3: Returns all policies from sql2016 server that part of the PolicyCategory MorningCheck PS C:\\> Get-DbaPbmPolicy -SqlInstance sql2016 -Category MorningCheck Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Policy Specifies one or more policy names to retrieve, filtering the results to only those policies. Supports exact name matching for targeted policy retrieval. Use this when you need to examine specific policies rather than all policies on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Category Filters results to show only policies belonging to specific policy categories. Categories help organize policies by function or compliance framework. Use this to focus on policies related to specific areas like security, performance, or maintenance checks. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts PBM store objects from Get-DbaPbmStore via pipeline, allowing efficient processing of multiple instances. Enables chaining PBM commands together. Use this when building complex PBM workflows or when you already have PBM store objects from previous commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -IncludeSystemObject Includes Microsoft's built-in system policies in the results, which are excluded by default. System policies cover standard SQL Server best practices. Use this when you need to review or document all policies including Microsoft's predefined compliance policies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Dmf.Policy Returns one Policy object per policy found on the specified SQL Server instance(s). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ID: Unique identifier for the policy Name: Name of the policy Enabled: Boolean indicating if the policy is enabled Description: Text description of the policy's purpose PolicyCategory: The category or group the policy belongs to AutomatedPolicyEvaluationMode: The mode used for automated evaluation (On Demand, On Schedule, On Change, None) Condition: The condition that the policy enforces CreateDate: DateTime when the policy was created CreatedBy: User who created the policy DateModified: DateTime when the policy was last modified ModifiedBy: User who last modified the policy IsSystemObject: Boolean indicating if this is a Microsoft system policy ObjectSet: The object set targeted by this policy RootCondition: The root condition evaluated by the policy ScheduleUid: The schedule identifier if policy uses scheduled evaluation *Properties excluded from default display (accessible with Select-Object ):* HelpText: Help documentation text for the policy HelpLink: URL link to additional help documentation Urn: The Uniform Resource Name Properties: The SMO object properties collection Metadata: The object metadata Parent: Reference to parent PolicyStore object IdentityKey: The identity key for the object HasScript: Boolean indicating if policy conditions reference T-SQL or WQL scripts PolicyEvaluationStarted: Indicates if evaluation has started ConnectionProcessingStarted: Indicates if connection processing started TargetProcessed: Indicates if targets have been processed ConnectionProcessingFinished: Indicates if connection processing is complete PolicyEvaluationFinished: Indicates if policy evaluation is complete PropertyMetadataChanged: Indicates if metadata has changed PropertyChanged: Indicates if properties have changed All properties from the base SMO Policy object are accessible using Select-Object even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Get-DbaPbmStore",
    "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.",
    "category": "Utilities",
    "tags": [
      "policy",
      "policybasedmanagement",
      "pbm"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPbmStore",
    "popularityRank": 631,
    "synopsis": "Retrieves the Policy-Based Management store object from SQL Server instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPbmStore View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves the Policy-Based Management store object from SQL Server instances. 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. Syntax Get-DbaPbmStore [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Return the policy store from the sql2016 instance PS C:\\> Get-DbaPbmStore -SqlInstance sql2016 Example 2: Uses a credential $cred to connect and return the policy store from the sql2016 instance PS C:\\> Get-DbaPbmStore -SqlInstance sql2016 -SqlCredential $cred Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.DMF.PolicyStore Returns one PolicyStore object per instance, which serves as the root container for managing Policy-Based Management (PBM) policies, conditions, and facets. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) All 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 needed: SqlStoreConnection: The underlying SQL Store connection object ConnectionContext: The SQL connection context Properties: The SMO object properties collection Urn: The Uniform Resource Name of the store Parent: The parent object reference DomainInstanceName: The domain instance name Metadata: Metadata information IdentityKey: The identity key for the object Name: The name property of the store object &nbsp;"
  },
  {
    "name": "Get-DbaPermission",
    "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't 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",
    "category": "Security",
    "tags": [
      "permissions",
      "instance",
      "database",
      "security"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaPermission",
    "popularityRank": 50,
    "synopsis": "Retrieves explicit and implicit permissions across SQL Server instances and databases for security auditing",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaPermission View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves explicit and implicit permissions across SQL Server instances and databases for security auditing Description Retrieves comprehensive permission information from SQL Server instances and databases, including both explicit permissions and implicit permissions from fixed roles. This function queries sys.server_permissions and sys.database_permissions to capture all granted, denied, and revoked permissions across server and database levels. Perfect for security audits, compliance reporting, troubleshooting access issues, and planning permission migrations between environments. The output includes permission state (GRANT/DENY/REVOKE), permission type (SELECT, CONNECT, EXECUTE, etc.), grantee information, and the specific securable being protected. Also captures implicit CONTROL permissions for dbo users, db_owner role members, and schema owners that aren't explicitly stored in system tables. Each result includes ready-to-use GRANT and REVOKE statements for easy permission replication or cleanup. Permissions link principals (logins, users, roles) to securables (servers, databases, schemas, objects). Principals exist at Windows, instance, and database levels, while securables exist at instance and database levels. See https://msdn.microsoft.com/en-us/library/ms191291.aspx for more information about SQL Server permissions Syntax Get-DbaPermission [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-IncludeServerLevel] [-ExcludeSystemObjects] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a custom object with Server name, Database name, permission state, permission type, grantee and... PS C:\\> Get-DbaPermission -SqlInstance ServerA\\sql987 Returns a custom object with Server name, Database name, permission state, permission type, grantee and securable. Example 2: Returns a formatted table displaying Server, Database, permission state, permission type, grantee... PS C:\\> Get-DbaPermission -SqlInstance ServerA\\sql987 | Format-Table -AutoSize Returns a formatted table displaying Server, Database, permission state, permission type, grantee, granteetype, securable and securabletype. Example 3: Returns a custom object with Server name, Database name, permission state, permission type, grantee and... PS C:\\> Get-DbaPermission -SqlInstance ServerA\\sql987 -ExcludeSystemObjects -IncludeServerLevel Returns a custom object with Server name, Database name, permission state, permission type, grantee and securable in all databases and on the server level, but not on system securables. Example 4: Returns a custom object with permissions for the master database PS C:\\> Get-DbaPermission -SqlInstance sql2016 -Database master Required Parameters -SqlInstance The target SQL Server instance or instances. Defaults to localhost. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for permissions. Accepts wildcards and multiple database names. When omitted, all accessible databases on the instance are processed, which is useful for comprehensive security audits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from permission analysis. Accepts wildcards and multiple database names. Commonly used to skip system databases like TempDB or exclude sensitive databases from security reports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeServerLevel Includes server-level permissions in the output, such as CONTROL SERVER, VIEW SERVER STATE, and fixed server roles like sysadmin. Essential for complete security audits as it captures instance-wide permissions that affect all databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeSystemObjects Excludes permissions on system objects like system tables, views, and stored procedures from the output. Use this when focusing on user-created objects to reduce noise in permission reports and compliance audits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Data.DataRow Returns one object per permission found across the specified instances and databases. Each permission object represents either an explicit permission from sys.server_permissions or sys.database_permissions, or an implicit permission from fixed roles, schema owners, or the database owner (dbo). Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (MSSQLSERVER for default instance) SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The database name; empty string for server-level permissions PermState: The permission state - 'GRANT', 'DENY', or 'REVOKE' (empty string for implicit permissions from roles) PermissionName: The name of the permission (e.g., SELECT, CONTROL, CONNECT, ADMINISTER BULK OPERATIONS) SecurableType: The type of securable being protected (e.g., DATABASE, OBJECT, SCHEMA, SERVER, ENDPOINT, AVAILABILITY GROUP, LOGIN) Securable: The name or identifier of the securable being protected (e.g., database name, object name, schema name, server name, login name) 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) GranteeType: The type of principal - 'LOGIN', 'USER', 'APPLICATION ROLE', 'ROLE', 'DATABASE OWNER (dbo user)', 'DATABASE OWNER (db_owner role)', 'SCHEMA OWNER', or fixed role type RevokeStatement: T-SQL REVOKE statement that can be used to revoke this permission; empty string for implicit permissions 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 Output Conditions: Server-level permissions: Only included when -IncludeServerLevel switch is specified; Database column is empty Database-level permissions: Always included; one object per explicit permission from sys.database_permissions Fixed role permissions: One object per built-in fixed role (db_owner, db_datareader, db_ddladmin, etc.); PermState is empty Implicit CONTROL permissions: Included for dbo users, db_owner role members, and schema owners; PermState is empty ExcludeSystemObjects: When specified, filters results to exclude permissions with major_id = 0 (system objects) in T-SQL WHERE clause &nbsp;"
  },
  {
    "name": "Get-DbaPfAvailableCounter",
    "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's much faster than traditional Get-Counter methods, making it practical for discovering hundreds of available counters across multiple servers. When credentials are provided, they're 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",
    "category": "Utilities",
    "tags": [
      "performance",
      "datacollector",
      "perfcounter"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPfAvailableCounter",
    "popularityRank": 522,
    "synopsis": "Retrieves all Windows performance counters available on local or remote machines for monitoring setup.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPfAvailableCounter View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves all Windows performance counters available on local or remote machines for monitoring setup. 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's much faster than traditional Get-Counter methods, making it practical for discovering hundreds of available counters across multiple servers. When credentials are provided, they're included in the output for easy piping to other dbatools commands like Add-DbaPfDataCollectorCounter. Thanks to Daniel Streefkerk for this super fast way of counters https://daniel.streefkerkonline.com/2016/02/18/use-powershell-to-list-all-windows-performance-counters-and-their-numeric-ids Syntax Get-DbaPfAvailableCounter [[-ComputerName] ] [[-Credential] ] [[-Pattern] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all available counters on the local machine PS C:\\> Get-DbaPfAvailableCounter Example 2: Gets all counters matching sql on the local machine PS C:\\> Get-DbaPfAvailableCounter -Pattern sql Example 3: Gets all counters matching sql on the remote server sql2017 PS C:\\> Get-DbaPfAvailableCounter -ComputerName sql2017 -Pattern sql Example 4: Gets all counters matching sql on the local machine PS C:\\> Get-DbaPfAvailableCounter -Pattern sql Example 5: Adds all counters matching &quot;sql&quot; to the DataCollector01 within the &#39;Test Collector Set&#39; CollectorSet PS C:\\> Get-DbaPfAvailableCounter -Pattern sql | Add-DbaPfDataCollectorCounter -CollectorSet 'Test Collector Set' -Collector DataCollector01 Optional Parameters -ComputerName Specifies the target computers to query for available performance counters. Defaults to localhost. Use this when you need to discover counters on remote SQL Server instances or other servers in your environment before setting up monitoring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:ComputerName | -Credential Allows you to login to servers using alternative credentials. To use: $scred = Get-Credential, then pass $scred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Pattern Filters counter names using wildcard pattern matching (supports and ? wildcards). Use this to find specific SQL Server counters like \"sql\" or \"buffer\" when you need to identify relevant performance metrics for monitoring setup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per available Windows performance counter found on the specified computers. Default display properties: ComputerName: The name of the computer where the counter is available Name: The performance counter name Additional properties available (via Select-Object ):** Credential: The PSCredential object used for connecting to the computer; useful for piping to other dbatools commands like Add-DbaPfDataCollectorCounter &nbsp;"
  },
  {
    "name": "Get-DbaPfDataCollector",
    "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.",
    "category": "Utilities",
    "tags": [
      "performance",
      "datacollector",
      "perfcounter"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPfDataCollector",
    "popularityRank": 525,
    "synopsis": "Retrieves Windows Performance Monitor data collectors and their configuration details from local or remote computers.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPfDataCollector View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows Performance Monitor data collectors and their configuration details from local or remote computers. 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. Use 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. Syntax Get-DbaPfDataCollector [[-ComputerName] ] [[-Credential] ] [[-CollectorSet] ] [[-Collector] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all Collectors on localhost PS C:\\> Get-DbaPfDataCollector Example 2: Gets all Collectors on sql2017 PS C:\\> Get-DbaPfDataCollector -ComputerName sql2017 Example 3: Gets all Collectors for the &#39;System Correlation&#39; CollectorSet on sql2017 and sql2016 using alternative... PS C:\\> Get-DbaPfDataCollector -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet 'System Correlation' Gets all Collectors for the 'System Correlation' CollectorSet on sql2017 and sql2016 using alternative credentials. Example 4: Gets all Collectors for the &#39;System Correlation&#39; CollectorSet PS C:\\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Get-DbaPfDataCollector Optional Parameters -ComputerName Specifies the target computer(s) to retrieve performance data collectors from. Defaults to localhost. Use this to monitor performance collectors across multiple SQL Server environments or remote systems where SQL Server performance monitoring is configured. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to servers using alternative credentials. To use: $scred = Get-Credential, then pass $scred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CollectorSet Filters results to data collectors within specific collector sets by name. Accepts wildcards for pattern matching. Use this when you want to examine collectors in a particular performance monitoring setup, such as 'System Correlation' or custom SQL Server baseline collector sets. | Property | Value | | --- | --- | | Alias | DataCollectorSet | | Required | False | | Pipeline | false | | Default Value | | -Collector Filters results to specific data collectors by name within the collector sets. Accepts wildcards for pattern matching. Use this when you need to examine a particular collector's configuration, such as one focused on SQL Server counters or system resource monitoring. | Property | Value | | --- | --- | | Alias | DataCollector | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts collector set objects from Get-DbaPfDataCollectorSet via the pipeline to retrieve their individual data collectors. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per data collector found within the specified collector sets. Each object represents a single Performance Monitor data collector configuration. Default display properties (via Select-DefaultView): ComputerName: The name of the computer where the collector set is configured DataCollectorSet: The name of the parent data collector set containing this collector Name: The logical name of the data collector within the collector set DataCollectorType: The type of data collector (e.g., PerformanceCounterDataCollector) DataSourceName: The name of the performance counter data source being collected FileName: The base file name where performance counter data is written FileNameFormat: Format specification for the output file naming (e.g., monddyy) FileNameFormatPattern: The file naming pattern used for sequential file naming LatestOutputLocation: The full path where the most recent collector output is stored LogAppend: Boolean indicating if new data is appended to existing log files LogCircular: Boolean indicating if the log uses circular buffering (overwrites when full) LogFileFormat: The format of the log file (e.g., csv, binary, sql) LogOverwrite: Boolean indicating if existing log data is overwritten SampleInterval: The sampling interval in milliseconds between performance counter samples SegmentMaxRecords: The maximum number of records per log segment Counters: The collection of performance counters being collected by this collector Additional properties available (not shown by default): CounterDisplayNames: Display names for the performance counters RemoteLatestOutputLocation: UNC path for accessing the latest output location remotely DataCollectorSetXml: The raw XML configuration of the parent data collector set CollectorXml: The raw XML configuration of this specific data collector DataCollectorObject: Flag indicating this is a data collector object Credential: The credential object used for remote access (if applicable) Use Select-Object * to access all properties available in the object. &nbsp;"
  },
  {
    "name": "Get-DbaPfDataCollectorCounter",
    "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.",
    "category": "Utilities",
    "tags": [
      "performance",
      "datacollector",
      "perfcounter"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPfDataCollectorCounter",
    "popularityRank": 602,
    "synopsis": "Retrieves performance counter configurations from Windows Performance Monitor Data Collector Sets.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPfDataCollectorCounter View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves performance counter configurations from Windows Performance Monitor Data Collector Sets. 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. Syntax Get-DbaPfDataCollectorCounter [[-ComputerName] ] [[-Credential] ] [[-CollectorSet] ] [[-Collector] ] [[-Counter] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all counters for all Collector Sets on localhost PS C:\\> Get-DbaPfDataCollectorCounter Example 2: Gets all counters for all Collector Sets on on sql2017 PS C:\\> Get-DbaPfDataCollectorCounter -ComputerName sql2017 Example 3: Gets the &#39;\\Processor(_Total)\\% Processor Time&#39; counter on sql2017 PS C:\\> Get-DbaPfDataCollectorCounter -ComputerName sql2017 -Counter '\\Processor(_Total)\\% Processor Time' Example 4: Gets all counters for the &#39;System Correlation&#39; CollectorSet on sql2017 and sql2016 using alternative... PS C:\\> Get-DbaPfDataCollectorCounter -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet 'System Correlation' Gets all counters for the 'System Correlation' CollectorSet on sql2017 and sql2016 using alternative credentials. Example 5: Gets all counters for the &#39;System Correlation&#39; CollectorSet PS C:\\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Get-DbaPfDataCollector | Get-DbaPfDataCollectorCounter Optional Parameters -ComputerName Specifies the target server(s) where Performance Monitor Data Collector Sets are configured. Use this to audit performance counters on remote SQL Server instances or retrieve counter configurations from multiple servers at once. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to servers using alternative credentials. To use: $scred = Get-Credential, then pass $scred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CollectorSet Filters results to specific Data Collector Set names such as 'System Correlation' or custom SQL performance monitoring sets. Use this when you need to examine counters for particular monitoring scenarios rather than reviewing all configured performance data collection. | Property | Value | | --- | --- | | Alias | DataCollectorSet | | Required | False | | Pipeline | false | | Default Value | | -Collector Filters results to specific Data Collector names within a Collector Set. Use this to narrow down results when a Collector Set contains multiple data collectors and you only need counter details from specific ones. | Property | Value | | --- | --- | | Alias | DataCollector | | Required | False | | Pipeline | false | | Default Value | | -Counter Searches for specific performance counter names using the exact Windows Performance Monitor format like '\\SQLServer:Buffer Manager\\Page life expectancy' or '\\Processor(_Total)\\% Processor Time'. Use this to verify if critical SQL Server or system performance counters are being monitored in your data collection setup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Data Collector objects from Get-DbaPfDataCollector via the pipeline to extract counter configurations. Use this for chaining commands when you want to drill down from Collector Sets to specific Data Collectors and then to their individual performance counters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per counter added to the Data Collector Set. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance DataCollectorSet: The name of the parent Data Collector Set containing the collector DataCollector: The name of the specific Data Collector within the Collector Set Name: The full path of the performance counter (e.g., '\\Processor(_Total)\\% Processor Time') FileName: The output file name where performance counter data will be stored Additional properties available: DataCollectorSetXml: XML configuration of the Data Collector Set Credential: The credential object used for authentication &nbsp;"
  },
  {
    "name": "Get-DbaPfDataCollectorCounterSample",
    "description": "Collects performance counter data from Windows Performance Monitor collector sets and individual counters on SQL Server systems. This function wraps PowerShell's 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.",
    "category": "Utilities",
    "tags": [
      "performance",
      "datacollector",
      "perfcounter"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPfDataCollectorCounterSample",
    "popularityRank": 632,
    "synopsis": "Retrieves real-time performance counter samples from SQL Server systems for monitoring and troubleshooting.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPfDataCollectorCounterSample View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves real-time performance counter samples from SQL Server systems for monitoring and troubleshooting. Description Collects performance counter data from Windows Performance Monitor collector sets and individual counters on SQL Server systems. This function wraps PowerShell's 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. Syntax Get-DbaPfDataCollectorCounterSample [[-ComputerName] ] [[-Credential] ] [[-CollectorSet] ] [[-Collector] ] [[-Counter] ] [-Continuous] [[-ListSet]] [[-MaxSamples] ] [[-SampleInterval] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets a single sample for all counters for all Collector Sets on localhost PS C:\\> Get-DbaPfDataCollectorCounterSample Example 2: Gets a single sample for all counters for all Collector Sets on localhost PS C:\\> Get-DbaPfDataCollectorCounterSample -Counter '\\Processor(_Total)\\% Processor Time' Example 3: Gets 10 samples for all counters for all Collector Sets for servers sql2016 and sql2017 PS C:\\> Get-DbaPfDataCollectorCounter -ComputerName sql2017, sql2016 | Out-GridView -PassThru | Get-DbaPfDataCollectorCounterSample -MaxSamples 10 Example 4: Gets a single sample for all counters for all Collector Sets on sql2017 PS C:\\> Get-DbaPfDataCollectorCounterSample -ComputerName sql2017 Example 5: Gets a single sample for all counters for the &#39;System Correlation&#39; CollectorSet on sql2017 and sql2016 using... PS C:\\> Get-DbaPfDataCollectorCounterSample -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet 'System Correlation' Gets a single sample for all counters for the 'System Correlation' CollectorSet on sql2017 and sql2016 using alternative credentials. Example 6: Gets a single sample for all counters for the &#39;System Correlation&#39; CollectorSet PS C:\\> Get-DbaPfDataCollectorCounterSample -CollectorSet 'System Correlation' Optional Parameters -ComputerName The target computer where performance counters will be collected. Defaults to localhost. Use this when monitoring remote SQL Server systems or collecting performance data from multiple servers simultaneously. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to servers using alternative credentials. To use: $scred = Get-Credential, then pass $scred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CollectorSet Specifies which Performance Monitor Data Collector Set to sample counters from. Accepts wildcard patterns for matching multiple sets. Use this to focus on specific pre-configured collector sets like 'System Performance' or custom SQL Server monitoring sets instead of sampling all available counters. | Property | Value | | --- | --- | | Alias | DataCollectorSet | | Required | False | | Pipeline | false | | Default Value | | -Collector Specifies which individual Data Collector within a Collector Set to sample from. Accepts wildcard patterns. Use this when you need samples from specific collectors rather than all collectors in a set, such as targeting only SQL Server-related collectors. | Property | Value | | --- | --- | | Alias | DataCollector | | Required | False | | Pipeline | false | | Default Value | | -Counter Specifies individual performance counter paths to sample in the standard format like '\\Processor(_Total)\\% Processor Time' or '\\SQLServer:Buffer Manager\\Page life expectancy'. Use this when you need specific counters for targeted troubleshooting rather than sampling all available counters from collector sets. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Continuous Enables continuous sampling until you press CTRL+C instead of taking a single snapshot. Combine with SampleInterval to control timing between samples. Use this during active troubleshooting sessions when you need to monitor performance trends in real-time, such as during query execution or system load events. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ListSet Lists available performance counter sets on the target computers without collecting samples. Supports wildcard patterns for filtering. Use this to discover what counter sets are available before running collection commands, especially useful when working with unfamiliar systems or custom monitoring configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaxSamples Specifies the maximum number of samples to collect from each counter before stopping. Default is 1 sample. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -SampleInterval Sets the time interval between samples in seconds with a minimum and default of 1 second. Use this to control sampling frequency based on your monitoring needs - shorter intervals for active troubleshooting or longer intervals for baseline collection to reduce overhead. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -InputObject Accepts the object output by Get-DbaPfDataCollectorCounter via the pipeline. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject (when -Continuous is not specified) Returns one object per counter sample collected from Performance Monitor. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance DataCollectorSet: The name of the parent Data Collector Set DataCollector: The name of the Data Collector Name: The counter name/path Timestamp: DateTime of the counter collection Path: The counter path in standard Performance Monitor format InstanceName: The instance name from the counter sample CookedValue: The processed/calculated counter value (double) RawValue: The raw counter value before processing (long) SecondValue: The secondary value for certain counter types (long) MultipleCount: Multiple count value for the sample (int) CounterType: The type of performance counter (PerformanceCounterType) SampleTimestamp: The timestamp of the individual sample (datetime) SampleTimestamp100NSec: Timestamp in 100-nanosecond intervals (long) Status: Status of the sample (PerformanceCounterSampleStatus) DefaultScale: Default scaling factor for the counter (int) TimeBase: Time base value for the counter (long) Additional properties available: Sample: Collection of counter samples (excluded from default view) System.Diagnostics.PerformanceCounterSampleData (when -Continuous is specified) When -Continuous is specified, returns raw output from PowerShell's Get-Counter cmdlet providing continuous real-time counter samples until interrupted with CTRL+C. &nbsp;"
  },
  {
    "name": "Get-DbaPfDataCollectorSet",
    "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.",
    "category": "Utilities",
    "tags": [
      "performance",
      "datacollector",
      "perfcounter"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPfDataCollectorSet",
    "popularityRank": 634,
    "synopsis": "Retrieves Windows Performance Monitor Data Collector Sets and their configuration details.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPfDataCollectorSet View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows Performance Monitor Data Collector Sets and their configuration details. 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. Syntax Get-DbaPfDataCollectorSet [[-ComputerName] ] [[-Credential] ] [[-CollectorSet] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets all Collector Sets on localhost PS C:\\> Get-DbaPfDataCollectorSet Example 2: Gets all Collector Sets on sql2017 PS C:\\> Get-DbaPfDataCollectorSet -ComputerName sql2017 Example 3: Gets the &#39;System Correlation&#39; CollectorSet on sql2017 using alternative credentials PS C:\\> Get-DbaPfDataCollectorSet -ComputerName sql2017 -Credential ad\\sqldba -CollectorSet 'System Correlation' Example 4: Displays extra columns and also exposes the original COM object in DataCollectorSetObject PS C:\\> Get-DbaPfDataCollectorSet | Select-Object Optional Parameters -ComputerName Specifies the Windows server(s) where you want to inventory Performance Monitor Data Collector Sets. Use this when checking collector sets across multiple SQL Server hosts or when managing performance monitoring from a central location. Accepts multiple computer names and defaults to the local computer. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to servers using alternative credentials. To use: $scred = Get-Credential, then pass $scred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CollectorSet Specifies the name(s) of specific Data Collector Sets to retrieve instead of returning all collector sets. Use this when you need to check the status or configuration of specific performance monitoring setups like 'SQL Server Default' or custom collector sets. Accepts wildcards and multiple collector set names for targeted monitoring inventory. | Property | Value | | --- | --- | | Alias | DataCollectorSet | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per Data Collector Set found on the target computer(s). Default display properties (via Select-DefaultView): ComputerName: The name of the computer where the Data Collector Set is configured Name: The name of the Data Collector Set DisplayName: The user-friendly display name of the collector set Description: Text description of what the collector set monitors State: Current state (Unknown, Disabled, Queued, Ready, Running) Duration: Duration in seconds for which the collector set will run OutputLocation: File system path where collected data is stored LatestOutputLocation: Path to the most recently collected output files RootPath: Root directory path for the collector set configuration SchedulesEnabled: Boolean indicating if schedules are enabled Segment: Segment configuration value for data collection SegmentMaxDuration: Maximum duration in seconds for a collection segment SegmentMaxSize: Maximum size in MB for a collection segment SerialNumber: Serial number or identifier for the collector set Server: Name of the server hosting the collector set StopOnCompletion: Boolean indicating if the collector set stops automatically when complete Subdirectory: Subdirectory path for organizing collector set output SubdirectoryFormat: Format pattern for subdirectory naming SubdirectoryFormatPattern: Detailed format pattern specification Task: Name of the Windows Task Scheduler task associated with the collector set TaskArguments: Command-line arguments passed to the collector set task TaskRunAsSelf: Boolean indicating if the task runs under the specified user account TaskUserTextArguments: User-specified text arguments for the task UserAccount: Windows user account under which the collector set runs Additional properties available (via Select-Object ):** Keywords: Keywords associated with the collector set for searching/categorizing DescriptionUnresolved: Raw description text before localization/resolution DisplayNameUnresolved: Raw display name before localization/resolution Schedules: Collection of schedule objects for the collector set Xml: Raw XML configuration of the collector set Security: Security descriptor for the collector set DataCollectorSetObject: Boolean indicating the object came from a Data Collector Set COM object TaskObject: Reference to the underlying Task Scheduler COM object Credential: The credentials used to retrieve this collector set &nbsp;"
  },
  {
    "name": "Get-DbaPfDataCollectorSetTemplate",
    "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.",
    "category": "Utilities",
    "tags": [
      "performance",
      "datacollector",
      "perfcounter"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPfDataCollectorSetTemplate",
    "popularityRank": 665,
    "synopsis": "Retrieves Windows Performance Monitor templates designed for SQL Server monitoring and troubleshooting.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPfDataCollectorSetTemplate View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows Performance Monitor templates designed for SQL Server monitoring and troubleshooting. 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. The 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. Syntax Get-DbaPfDataCollectorSetTemplate [[-Path] ] [[-Pattern] ] [[-Template] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns information about all the templates in the local dbatools repository PS C:\\> Get-DbaPfDataCollectorSetTemplate Example 2: Allows you to select a template, then deploys it to sql2017 and immediately starts the DataCollectorSet PS C:\\> Get-DbaPfDataCollectorSetTemplate | Out-GridView -PassThru | Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 | Start-DbaPfDataCollectorSet Example 3: Returns more information about the template, including the full path/filename PS C:\\> Get-DbaPfDataCollectorSetTemplate | Select-Object Optional Parameters -Path Specifies the directory path containing Performance Monitor template XML files. Defaults to the dbatools built-in template repository (\\bin\\perfmontemplates\\collectorsets). Use this when you have custom template files stored in a different location or want to load templates from a network share. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \"$script:PSModuleRoot\\bin\\perfmontemplates\\collectorsets\" | -Pattern Filters templates by matching text patterns against template names and descriptions using regex syntax. Supports wildcards ( becomes .). Use this to find templates for specific scenarios like \"long.query\" to locate long-running query monitoring templates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Template Specifies one or more template names to retrieve by exact match. Accepts multiple values and supports tab completion to browse available templates. Use this when you know the specific template names you need rather than browsing all available templates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per template found in the specified template directory (default: dbatools built-in repository). Default display properties (via Select-DefaultView): Name: The name of the Performance Monitor template Source: The source or origin of the template (from the metadata XML file) UserAccount: The user account under which the template will run when deployed Description: Description of what performance counters and scenarios the template monitors *Additional properties available (via Select-Object ):** Path: Full file system path to the template XML file File: The template XML file name &nbsp;"
  },
  {
    "name": "Get-DbaPlanCache",
    "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.",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "cache",
      "memory"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPlanCache",
    "popularityRank": 476,
    "synopsis": "Retrieves single-use plan cache usage to identify memory waste from adhoc and prepared statements",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaPlanCache View Source Tracy Boggiano, databasesuperhero.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves single-use plan cache usage to identify memory waste from adhoc and prepared statements 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. When 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. The 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. References: https://www.sqlskills.com/blogs/kimberly/plan-cache-adhoc-workloads-and-clearing-the-single-use-plan-cache-bloat/ Note: This command returns results from all SQL server instances on the destination server but the process column is specific to -SqlInstance passed. Syntax Get-DbaPlanCache [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the single use plan cache usage information for SQL Server instance 2017 PS C:\\> Get-DbaPlanCache -SqlInstance sql2017 Example 2: Returns the single use plan cache usage information for SQL Server instance 2017 using login &#39;sqladmin&#39; PS C:\\> Get-DbaPlanCache -SqlInstance sql2017 -SqlCredential sqladmin Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance queried, providing aggregate single-use plan cache statistics. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Size: Total size of single-use adhoc and prepared statement plans; dbasize object convertible to Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes UseCount: Count of single-use adhoc and prepared statement plans found in the plan cache &nbsp;"
  },
  {
    "name": "Get-DbaPowerPlan",
    "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.",
    "category": "Performance",
    "tags": [
      "powerplan",
      "utility"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPowerPlan",
    "popularityRank": 345,
    "synopsis": "Retrieves Windows Power Plan configuration from SQL Server hosts to verify High Performance settings.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPowerPlan View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows Power Plan configuration from SQL Server hosts to verify High Performance settings. 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. By 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. Syntax Get-DbaPowerPlan [-ComputerName] [[-Credential] ] [-List] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the Power Plan settings for sql2017 PS C:\\> Get-DbaPowerPlan -ComputerName sql2017 Example 2: Gets the Power Plan settings for sql2017 using an alternative credential PS C:\\> Get-DbaPowerPlan -ComputerName sql2017 -Credential ad\\admin Example 3: Gets all available Power Plans on sql2017 PS C:\\> Get-DbaPowerPlan -ComputerName sql2017 -List Required Parameters -ComputerName Specifies the SQL Server host computer(s) to check for Windows Power Plan configuration. Accepts multiple server names for bulk power plan auditing. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Default output (when -List is not specified): Returns one object per computer queried, showing the currently active power plan. Properties: ComputerName: The SQL Server host computer name PowerPlan: Name of the currently active power plan (e.g., \"High Performance\", \"Balanced\", \"Power saver\"); shows \"Unknown\" if detection fails When -List is specified: Returns one object per available power plan on each computer, showing all power plans and which one is active. Properties: ComputerName: The SQL Server host computer name PowerPlan: Name of the power plan IsActive: Boolean indicating if this power plan is currently active (True or False) &nbsp;"
  },
  {
    "name": "Get-DbaPrivilege",
    "description": "Audits six Windows privileges that directly impact SQL Server performance and functionality: Lock Pages in Memory, Instant File Initialization, Logon as Batch, Generate Security Audits, Logon as a Service, and Create Global Objects. These privileges are essential for SQL Server service accounts to achieve optimal performance and proper operation.\n\nUse this to verify that SQL Server service accounts have the necessary Windows privileges configured, troubleshoot performance issues related to missing privileges, or audit security configurations across your SQL Server environment. The function exports the local security policy using secedit and parses the results to show which users and groups hold these critical privileges.\n\nRequires Local Admin rights on destination computer(s).",
    "category": "Utilities",
    "tags": [
      "privilege",
      "os",
      "security"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaPrivilege",
    "popularityRank": 207,
    "synopsis": "Retrieves Windows security privileges critical for SQL Server performance from target computers.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaPrivilege View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows security privileges critical for SQL Server performance from target computers. Description Audits six Windows privileges that directly impact SQL Server performance and functionality: Lock Pages in Memory, Instant File Initialization, Logon as Batch, Generate Security Audits, Logon as a Service, and Create Global Objects. These privileges are essential for SQL Server service accounts to achieve optimal performance and proper operation. Use 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. Requires Local Admin rights on destination computer(s). Syntax Get-DbaPrivilege [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the local privileges on computer sqlserver2014a PS C:\\> Get-DbaPrivilege -ComputerName sqlserver2014a Example 2: Gets the local privileges on computers sql1, sql2 and sql3 PS C:\\> 'sql1','sql2','sql3' | Get-DbaPrivilege Example 3: Gets the local privileges on computers sql1 and sql2, and shows them in a grid view PS C:\\> Get-DbaPrivilege -ComputerName sql1,sql2 | Out-GridView Optional Parameters -ComputerName Specifies the target computer names where you want to audit Windows privileges. Accepts multiple computer names for bulk privilege auditing. Use 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 rights. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Credential object used to connect to the computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per unique user or group found across the six Windows security privileges being audited. Properties: ComputerName: The name of the computer where the privilege audit was performed User: The user or group account name; converted from SID to account name if applicable LogonAsBatch: Boolean indicating if the user has SeBatchLogonRight privilege InstantFileInitialization: Boolean indicating if the user has SeManageVolumePrivilege (Instant File Initialization) LockPagesInMemory: Boolean indicating if the user has SeLockMemoryPrivilege GenerateSecurityAudit: Boolean indicating if the user has SeAuditPrivilege LogonAsAService: Boolean indicating if the user has SeServiceLogonRight privilege CreateGlobalObjects: Boolean indicating if the user has SeCreateGlobalPrivilege (required by some backup agents) &nbsp;"
  },
  {
    "name": "Get-DbaProcess",
    "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.",
    "category": "Utilities",
    "tags": [
      "diagnostic",
      "process",
      "session",
      "activitymonitor"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaProcess",
    "popularityRank": 208,
    "synopsis": "Retrieves active SQL Server processes and sessions with detailed connection and activity information.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaProcess View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves active SQL Server processes and sessions with detailed connection and activity information. 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. Use 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. You 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. Thanks 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. Syntax Get-DbaProcess [-SqlInstance] [[-SqlCredential] ] [[-Spid] ] [[-ExcludeSpid] ] [[-Database] ] [[-Login] ] [[-Hostname] ] [[-Program] ] [-ExcludeSystemSpids] [-EnableException] [-Intersect] [ ] &nbsp; Examples &nbsp; Example 1: Shows information about the processes for base\\ctrlb and sa on sqlserver2014a PS C:\\> Get-DbaProcess -SqlInstance sqlserver2014a -Login base\\ctrlb, sa Shows information about the processes for base\\ctrlb and sa on sqlserver2014a. Windows Authentication is used in connecting to sqlserver2014a. Example 2: Shows information about the processes for spid 56 and 57 PS C:\\> Get-DbaProcess -SqlInstance sqlserver2014a -SqlCredential $credential -Spid 56, 77 Shows information about the processes for spid 56 and 57. Uses alternative (SQL or Windows) credentials to authenticate to sqlserver2014a. Example 3: Shows information about the processes that were created in Microsoft SQL Server Management Studio PS C:\\> Get-DbaProcess -SqlInstance sqlserver2014a -Program 'Microsoft SQL Server Management Studio' Example 4: Shows information about the processes that were initiated by hosts (computers/clients) workstationx and... PS C:\\> Get-DbaProcess -SqlInstance sqlserver2014a -Host workstationx, server100 Shows information about the processes that were initiated by hosts (computers/clients) workstationx and server 1000. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Spid Filters results to specific process IDs (SPIDs) you want to monitor. Also includes any processes that are blocked by the specified SPIDs. Use this when investigating specific connections or troubleshooting blocking issues where you need to see both the blocker and blocked processes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSpid Excludes specific process IDs (SPIDs) from the results, even if they match other filter criteria. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Filters results to sessions currently connected to specific databases. Use this when monitoring activity on particular databases, investigating database-specific performance issues, or auditing access to sensitive databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Filters results to sessions connected with specific SQL Server login names or Windows authentication accounts. Use this to monitor connections from specific applications, service accounts, or users when investigating security concerns or connection patterns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Hostname Filters results to sessions originating from specific client machines or server names. Use this when tracking connections from particular workstations, application servers, or investigating connection leaks from specific hosts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Program Filters results to sessions created by specific client applications such as 'Microsoft SQL Server Management Studio' or custom application names. Use this to monitor connections from particular applications, identify connection patterns, or troubleshoot application-specific database issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemSpids Excludes system processes (SPIDs 1-50) from the results to focus only on user connections and application processes. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Intersect If this switch is enabled, take the intersection of Spid, Login, Hostname, Program, and Database rather than the union. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Agent.Job (SMO Process object) Returns one object per active SQL Server process/session matching the specified filter criteria. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Spid: Session ID number of the process Login: SQL Server login or Windows authentication account name LoginTime: DateTime when the session logged in Host: Client machine name/hostname Database: Database currently connected to the session BlockingSpid: Session ID of the process blocking this session (if blocked) Program: Client application name that initiated the session Status: Current status of the session (sleeping, running, etc.) Command: T-SQL command currently being executed Cpu: CPU time consumed in milliseconds MemUsage: Memory usage in pages (8 KB per page) LastRequestStartTime: DateTime when the last request started LastRequestEndTime: DateTime when the last request completed MinutesAsleep: Minutes elapsed since last request ended ClientNetAddress: Client IP address NetTransport: Network transport protocol (Named Pipes, TCP, Shared Memory) EncryptOption: Encryption setting (Off, On, Required, Login) AuthScheme: Authentication scheme used (NTLM, Kerberos, SQL, etc.) NetPacketSize: Network packet size in bytes ClientVersion: Client library version number HostProcessId: Operating system process ID on the client machine IsSystem: Boolean indicating if this is a system session EndpointName: Name of the endpoint the connection is using IsDac: Boolean indicating if this is a Dedicated Admin Connection (DAC) LastQuery: The last T-SQL statement executed in this session Additional properties available (from SMO Process object): Parent: Reference to the parent Server object All other SMO process properties are accessible using Select-Object * &nbsp;"
  },
  {
    "name": "Get-DbaProductKey",
    "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't 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.",
    "category": "Utilities",
    "tags": [
      "productkey",
      "utility"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaProductKey",
    "popularityRank": 21,
    "synopsis": "Retrieves SQL Server product keys from registry data for license compliance and inventory management.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaProductKey View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server product keys from registry data for license compliance and inventory management. 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't 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. Syntax Get-DbaProductKey [-ComputerName] [[-SqlCredential] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets SQL Server versions, editions and product keys for all instances within each server or workstation PS C:\\> Get-DbaProductKey -ComputerName winxp, sqlservera, sqlserver2014a, win2k8 Required Parameters -ComputerName Specifies the SQL Server instances or computer names to retrieve product keys from. Accepts multiple values for bulk operations. Use this when you need to audit license compliance across multiple servers or gather product key inventory during migrations. | Property | Value | | --- | --- | | Alias | SqlInstance | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential This command logs into the SQL instance to gather additional information. Use this parameter to connect to the discovered SQL instances using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential) | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Login to the target Windows instance using alternative credentials. Windows Authentication supported. Accepts credential objects (Get-Credential) | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance found on the target computer(s) with license key information. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Version: The SQL Server version name (e.g., \"SQL Server 2019\", \"SQL Server 2016\") Edition: The SQL Server edition (Enterprise, Standard, Express, Developer, etc.) 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 registry &nbsp;"
  },
  {
    "name": "Get-DbaQueryExecutionTime",
    "description": "Analyzes SQL Server's 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't 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.",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "performance",
      "query"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaQueryExecutionTime",
    "popularityRank": 335,
    "synopsis": "Retrieves stored procedures and SQL statements with the highest CPU execution times from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaQueryExecutionTime View Source Brandon Abshire, netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves stored procedures and SQL statements with the highest CPU execution times from SQL Server instances. Description Analyzes SQL Server's 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. Use 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't have to manually query DMVs or run expensive profiler traces. By 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. Syntax Get-DbaQueryExecutionTime -SqlInstance [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-MaxResultsPerDb ] [-MinExecs ] [[-MinExecMs] ] [[-ExcludeSystem]] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Return the top 100 slowest stored procedures or statements for servers sql2008 and sqlserver2012 PS C:\\> Get-DbaQueryExecutionTime -SqlInstance sql2008, sqlserver2012 Example 2: Return the top 100 slowest stored procedures or statements on server sql2008 for only the TestDB database PS C:\\> Get-DbaQueryExecutionTime -SqlInstance sql2008 -Database TestDB Example 3: Return the top 100 slowest stored procedures or statements on server sql2008 for only the TestDB database... PS C:\\> Get-DbaQueryExecutionTime -SqlInstance sql2008 -Database TestDB -MaxResultsPerDb 100 -MinExecs 200 -MinExecMs 1000 Return 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 1000ms or higher. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for query execution statistics. Accepts wildcards for pattern matching. Use this when troubleshooting performance issues in specific databases instead of scanning all databases on the instance. Helpful for focusing on production databases or isolating performance analysis to databases experiencing issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during the execution time analysis. Accepts wildcards for pattern matching. Use this to avoid processing databases that are known to be performing well or contain only static reference data. Common use case is excluding development or staging databases when analyzing production performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaxResultsPerDb Limits the number of top execution time results returned per database. Defaults to 100 results. Specify a lower number for quick performance overviews or higher numbers for comprehensive analysis. Large values may impact query performance on busy systems with extensive plan cache data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 100 | -MinExecs Filters results to queries that have executed at least this many times. Defaults to 100 executions. Use this to focus on frequently-run queries that have consistent performance patterns rather than one-time queries. Higher values help identify truly problematic queries that impact system performance regularly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 100 | -MinExecMs Filters results to queries with an average execution time of at least this many milliseconds. Defaults to 500ms. Use this to focus on genuinely slow queries rather than fast queries that happen to consume CPU cycles. Lowering this value shows more queries but may include acceptable performance levels. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 500 | -ExcludeSystem Skips analysis of system databases (master, model, msdb, tempdb). Use this when focusing performance analysis on user databases only, since system database queries are typically administrative. System database performance issues are usually infrastructure-related rather than application code problems. | Property | Value | | --- | --- | | Alias | ExcludeSystemDatabases | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 first), where N is controlled by -MaxResultsPerDb (default 100). Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database containing the query ProcName: The procedure or object name; empty string for ad hoc statements ObjectID: The object ID from sys.dm_exec_procedure_stats or sys.dm_exec_query_stats TypeDesc: The type description - \"PROCEDURE\" for stored procedures or \"STATEMENT\" for ad hoc queries Executions: The execution_count - total number of times the query has been executed AvgExecMs: Average execution time in milliseconds (total_worker_time / execution_count / 1000) MaxExecMs: Maximum execution time in milliseconds (max_worker_time / 1000) CachedTime: DateTime when the query plan was cached (1901-01-01 for ad hoc statements) LastExecTime: DateTime when the query last executed TotalWorkerTimeMs: Total CPU worker time in milliseconds across all executions TotalElapsedTimeMs: Total elapsed time in milliseconds across all executions SQLText: Truncated SQL text (first 50 characters for ad hoc statements, procedure name for stored procedures) *Additional properties (available with Select-Object ):** FullStatementText: Complete SQL statement text (full T-SQL for ad hoc statements, procedure name for stored procedures) &nbsp;"
  },
  {
    "name": "Get-DbaRandomizedDataset",
    "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.",
    "category": "Utilities",
    "tags": [
      "datageneration"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRandomizedDataset",
    "popularityRank": 301,
    "synopsis": "Generates random test data using predefined templates for development and testing scenarios",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaRandomizedDataset View Source Sander Stad (@sqlstad, sqlstad.nl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates random test data using predefined templates for development and testing scenarios 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. Syntax Get-DbaRandomizedDataset [[-Template] ] [[-TemplateFile] ] [[-Rows] ] [[-Locale] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Generate a data set based on the default template PersonalData PS C:\\> Get-DbaRandomizedDataset -Template Personaldata Example 2: Generate a data set based on the default template PersonalData with 10 rows PS C:\\> Get-DbaRandomizedDataset -Template Personaldata -Rows 10 Example 3: Generates data set based on a template file in another directory PS C:\\> Get-DbaRandomizedDataset -TemplateFile C:\\Dataset\\FinancialData.json Example 4: Generates multiple data sets PS C:\\> Get-DbaRandomizedDataset -Template Personaldata, FinancialData Example 5: Pipe the templates from Get-DbaRandomizedDatasetTemplate to Get-DbaRandomizedDataset and generate the data set PS C:\\> Get-DbaRandomizedDatasetTemplate -Template PersonalData | Get-DbaRandomizedDataset Optional Parameters -Template Specifies the name of one or more built-in templates to use for data generation. Use this when you want to generate data using predefined column structures like PersonalData which includes names, addresses, and birthdates. The function searches through default templates in the module's bin\\randomizer\\templates directory to find matching names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TemplateFile Specifies the full path to one or more custom JSON template files that define column structures and data types. Use this when you need to generate data based on your own custom templates rather than the built-in ones. Template files must be valid JSON with a Columns array defining Name, Type, and SubType properties for each column. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Rows Specifies how many rows of test data to generate for each template. Use this to control the size of your test dataset based on your development or testing needs. Defaults to 100 rows if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 100 | -Locale Specifies the locale for generating culture-specific data like names, addresses, and phone numbers. Use this when you need test data that matches a specific geographic region or language for realistic testing scenarios. Defaults to 'en' (English) if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | en | -InputObject Accepts template objects piped from Get-DbaRandomizedDatasetTemplate. Use this in pipeline scenarios where you first retrieve templates and then generate data from them. Each input object should contain template information including the FullName path to the JSON template file. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one PSCustomObject per generated row. The properties of each object are dynamically defined by the columns array in the template JSON file. Properties depend on the template used: Each property name corresponds to a column.Name value from the template file Each property value is generated by Get-DbaRandomizedValue based on the column's Type and SubType Property data types vary based on the semantic type specified (string, int, datetime, guid, etc.) Example with PersonalData template (typical properties): FirstName: Generated first name (string) LastName: Generated last name (string) Email: Generated email address (string) PhoneNumber: Generated phone number (string) DateOfBirth: Generated birth date (datetime) Address: Generated street address (string) City: Generated city name (string) ZipCode: Generated postal code (string) Country: Generated country name (string) The 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 scenarios. &nbsp;"
  },
  {
    "name": "Get-DbaRandomizedDatasetTemplate",
    "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.",
    "category": "Utilities",
    "tags": [
      "datageneration"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRandomizedDatasetTemplate",
    "popularityRank": 527,
    "synopsis": "Retrieves JSON template files that define column structures for generating realistic test data",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaRandomizedDatasetTemplate View Source Sander Stad (@sqlstad, sqlstad.nl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves JSON template files that define column structures for generating realistic test data 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. Syntax Get-DbaRandomizedDatasetTemplate [[-Template] ] [[-Path] ] [-ExcludeDefault] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get the templates from the default directory PS C:\\> Get-DbaRandomizedDatasetTemplate Example 2: Get the templates from thedefault directory and filter on PersonalData and Test PS C:\\> Get-DbaRandomizedDatasetTemplate -Template Personaldata, Test Example 3: Get the templates from a custom directory PS C:\\> Get-DbaRandomizedDatasetTemplate -Path C:\\DatasetTemplates Optional Parameters -Template Specifies which template files to retrieve by name (without the .json extension). Use this to filter results when you only need specific templates like \"PersonalData\" or custom templates. If not specified, all available templates from the specified paths are returned. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies one or more directory paths containing custom JSON template files for data generation. Use this when your organization has created custom templates beyond the default dbatools templates. Templates from these paths are added to the default templates unless -ExcludeDefault is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDefault Excludes the built-in dbatools templates from the results. Use this when you only want to work with custom templates from specified paths. The default templates include common data patterns like PersonalData with names, addresses, and dates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties: BaseName: The template name without the .json extension (string) FullName: The complete file path to the JSON template file (string) When 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 filters results to only matching template names. The -ExcludeDefault switch excludes built-in templates and only returns custom templates from specified paths. &nbsp;"
  },
  {
    "name": "Get-DbaRandomizedType",
    "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.",
    "category": "Utilities",
    "tags": [
      "datageneration"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRandomizedType",
    "popularityRank": 625,
    "synopsis": "Lists available data types and subtypes for generating realistic test data during database masking operations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaRandomizedType View Source Sander Stad (@sqlstad, sqlstad.nl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Lists available data types and subtypes for generating realistic test data during database masking operations 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. Syntax Get-DbaRandomizedType [[-RandomizedType] ] [[-RandomizedSubType] ] [[-Pattern] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get all the types and subtypes PS C:\\> Get-DbaRandomizedType Example 2: Find all the types and sub types based on a pattern PS C:\\> Get-DbaRandomizedType -Pattern \"Addr\" Example 3: Find all the sub types for Person PS C:\\> Get-DbaRandomizedType -RandomizedType Person Example 4: Get all the types and subtypes that known by &quot;LastName&quot; PS C:\\> Get-DbaRandomizedType -RandomizedSubType LastName Optional Parameters -RandomizedType Filters results to specific main data categories for realistic test data generation. Use this when you need to focus on particular data types like Person, Address, Finance, Internet, or Random data. Available types include Address, Commerce, Company, Database, Date, Finance, Hacker, Image, Internet, Lorem, Name, Person, Phone, Random, System, and more. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RandomizedSubType Filters results to specific data subtypes within the main categories for precise data masking scenarios. Use this when you need exact data patterns like FirstName, LastName, Email, CreditCardNumber, or ZipCode. Subtypes provide granular control over the fake data generation for targeted column masking. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Pattern Searches both main types and subtypes using pattern matching to find relevant data generators. Use this when you're unsure of exact type names or want to discover related options like searching 'Addr' to find Address-related types. Supports wildcard matching against both Type and SubType columns for flexible discovery. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per unique Type-SubType combination from the available randomizer types and subtypes. Properties: Type: The main data category for generating test data (e.g., Address, Commerce, Person, Finance, Internet) SubType: The specific data pattern within the main category (e.g., FirstName, LastName, ZipCode, CreditCardNumber) Results are always sorted by Type and SubType, with duplicate combinations removed using -Unique. Filters specified by -RandomizedType, -RandomizedSubType, or -Pattern parameters only affect which combinations are returned, not the structure of the output objects. &nbsp;"
  },
  {
    "name": "Get-DbaRandomizedValue",
    "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.",
    "category": "Utilities",
    "tags": [
      "datamasking",
      "datageneration"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRandomizedValue",
    "popularityRank": 564,
    "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",
    "windowsOnly": false,
    "fullContent": "Get-DbaRandomizedValue View Source Sander Stad (@sqlstad, sqlstad.nl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates random data values for SQL Server data types or specialized data patterns for data masking and test data creation 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. This 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. Supports 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. Uses the Bogus library to ensure generated data follows realistic patterns rather than simple random character generation. Syntax Get-DbaRandomizedValue [[-DataType] ] [[-RandomizerType] ] [[-RandomizerSubType] ] [[-Min] ] [[-Max] ] [[-Precision] ] [[-CharacterString] ] [[-Format] ] [[-Symbol] ] [[-Separator] ] [[-Value] ] [[-Locale] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Will return either a 1 or 0 PS C:\\> Get-DbaRandomizedValue -DataType bit Example 2: Will generate a number between -2147483648 and 2147483647 PS C:\\> Get-DbaRandomizedValue -DataType int Example 3: Generates a random zipcode PS C:\\> Get-DbaRandomizedValue -RandomizerType Address -RandomizerSubType Zipcode Example 4: Generates a random zipcode like &quot;1234 56&quot; PS C:\\> Get-DbaRandomizedValue -RandomizerType Address -RandomizerSubType Zipcode -Format \"\" Example 5: Generates a random phonenumber like &quot;(123) 4567890&quot; PS C:\\> Get-DbaRandomizedValue -RandomizerSubType PhoneNumber -Format \"() \" Optional Parameters -DataType Specifies the SQL Server data type for which to generate a random value that matches the type's constraints and range. Use this when you need to generate test data that exactly matches your column's data type, including proper ranges for numeric types and correct formatting for date/time types. Supported types include bigint, bit, bool, char, date, datetime, datetime2, decimal, int, float, guid, money, numeric, nchar, ntext, nvarchar, real, smalldatetime, smallint, text, time, tinyint, uniqueidentifier, userdefineddatatype, varchar. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RandomizerType Selects the category of realistic fake data to generate using the Bogus library instead of basic SQL data types. Use this when you need data that looks realistic for specific domains like names, addresses, or financial information rather than just type-appropriate random values. Available types include Address, Commerce, Company, Database, Date, Finance, Hacker, Hashids, Image, Internet, Lorem, Name, Person, Phone, Random, Rant, System. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RandomizerSubType Defines the specific type of data to generate within a RandomizerType category, such as 'FirstName' under Name or 'ZipCode' under Address. Use this to get precisely the kind of fake data you need, like generating just phone numbers from the Person category or specific address components. Can be used alone and the function will automatically determine the appropriate RandomizerType, or combined with RandomizerType for explicit control. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Min Sets the minimum value or length constraint for generated data, such as the shortest string length or smallest numeric value. Use this to ensure generated data meets your minimum requirements, like ensuring usernames are at least 3 characters or account balances are above zero. Defaults to 1 for most data types; automatically adjusted to data type limits for numeric types like int or smallint. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Max Sets the maximum value or length constraint for generated data, such as the longest string length or largest numeric value. Use this to prevent data from exceeding column limits or business rules, like keeping varchar fields under their defined length or amounts under spending limits. Defaults to 255 for most data types; automatically adjusted to data type limits for numeric types like int or smallint. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Precision Controls the number of decimal places for generated numeric values when using decimal, numeric, real, or float data types. Use this to match your column's precision requirements, ensuring generated monetary amounts or measurements have the correct decimal precision. Defaults to 2 decimal places, which works well for most currency and percentage values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 2 | -CharacterString Defines the character set to use when generating random string data for varchar, char, and similar text data types. Use this to match specific requirements like alphanumeric-only strings for account codes or excluding certain characters that cause issues in your application. Defaults to all letters (upper and lower case) and numbers; customize for specific business rules or technical constraints. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 | -Format Applies custom formatting patterns to generated data, such as phone number formats like \"() -\" or ZIP code patterns like \"\". Use this to ensure generated data matches your application's expected format, making masked data look consistent with production patterns. Works with randomizer types that support formatting; use # as placeholders that will be replaced with appropriate random digits or characters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Symbol Adds a prefix symbol to generated numeric values, such as \"$\" for currency amounts or \"%\" for percentages. Use 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\". Primarily used with Finance randomizer types for realistic monetary displays. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Separator Specifies the delimiter character to use in formatted data like MAC addresses, where you can choose between \":\" or \"-\" separators. Use this to match your network infrastructure's standard format, ensuring generated MAC addresses use the same separator style as your production environment. Most commonly used with Internet randomizer types that generate network-related identifiers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Value Provides the source data for transformation-based randomization methods, particularly when using the \"Shuffle\" subtype to rearrange existing values. Use this when you want to mask data by scrambling rather than replacing it entirely, preserving some characteristics like character count while making it unrecognizable. Required when using RandomizerSubType \"Shuffle\"; the function will randomize the order of characters while preserving commas and decimal points in their original positions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Locale Controls the cultural context for generated data, affecting formats for names, addresses, phone numbers, and other locale-specific information. Use this when you need test data that matches your target region's conventions, such as generating European address formats or non-English names for international applications. Defaults to 'en' for English; change to other locale codes like 'de', 'fr', or 'es' to generate region-appropriate fake data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | en | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Scalar values with type determined by parameters (when using -DataType) System.Int64, System.Int32 (bigint, int, smallint, tinyint data types) Returns a single integer value within the appropriate range for the specified data type System.Decimal, System.Single, System.Double (decimal, float, money, numeric, real data types) Returns a single numeric value with optional symbol ($, %, etc.) and specified precision System.String (varchar, char, nvarchar, nchar, text, ntext data types) Returns a string value with random characters from the specified CharacterString Length controlled by Min and Max parameters (default 1-255 characters) System.String in date/time formats (date, datetime, datetime2, smalldatetime, time data types) date: \"yyyy-MM-dd\" format datetime: \"yyyy-MM-dd HH:mm:ss.fff\" format datetime2: \"yyyy-MM-dd HH:mm:ss.fffffff\" format smalldatetime: \"yyyy-MM-dd HH:mm:ss\" format time: \"HH:mm:ss.fffffff\" format uniqueidentifier/guid: GUID in standard format System.Int32 (bit, bool, userdefineddatatype) Returns 0 or 1 for bit/bool types Returns 0, 1, or $null for userdefineddatatype depending on Max parameter Specialized Randomizer Types (when using -RandomizerType/-RandomizerSubType) Variable return types from the Bogus library: Address types (Address, ZipCode, City, State, Country, BuildingNumber, StreetName, Latitude, Longitude): System.String or System.Double Commerce types (Product, Department, ProductName, Price): System.String or numeric Company types (CompanyName, CatchPhrase, Bs): System.String Database types (Engine, Column, CollationName, Type): System.String Date types (formatted dates or timestamps based on subtype specification): System.String Finance types (Account, Amount, CreditCardNumber, Iban, Bic): System.String or numeric Hacker types (Phrase, Abbreviation, Adjective, Noun, Verb): System.String Image types (URLs or image data): System.String Internet types (Email, UserName, Password, Url, IpAddress, Mac, DomainName): System.String Lorem types (Word, Words, Sentence, Sentences, Paragraph, Paragraphs, Slug, Letter, Lines): System.String or array Name types (FirstName, LastName, FullName, Prefix, Suffix): System.String Person types (various personal information): System.String or other types Phone types (PhoneNumber with optional formatting): System.String 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 Rant types (Review, Reviews): System.String System types (FileName, DirectoryPath, CommonFileName, CommonFileExt, CommonUserAgent): System.String All 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 the selected RandomizerType and RandomizerSubType combination, as well as format and pattern parameters applied. &nbsp;"
  },
  {
    "name": "Get-DbaRegistryRoot",
    "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't 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.",
    "category": "Utilities",
    "tags": [
      "management",
      "os",
      "registry"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRegistryRoot",
    "popularityRank": 489,
    "synopsis": "Discovers Windows registry root paths for SQL Server instances to enable direct registry configuration access",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaRegistryRoot View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Discovers Windows registry root paths for SQL Server instances to enable direct registry configuration access 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't 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. Syntax Get-DbaRegistryRoot [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the registry root for all instances on localhost PS C:\\> Get-DbaRegistryRoot Example 2: Gets the registry root for all instances on server1 PS C:\\> Get-DbaRegistryRoot -ComputerName server1 Optional Parameters -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. Use this when you need registry root paths for SQL Server instances on remote servers for configuration troubleshooting or automated registry modifications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to $ComputerName using alternative Windows credentials | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance found on the specified computer. Properties: ComputerName: The computer name of the SQL Server host InstanceName: The SQL Server instance name (e.g., \"MSSQLSERVER\" for default instance, or instance name for named instances) SqlInstance: The full SQL Server instance name (computer\\instance format, or just computer name for default instance) Hive: The Windows registry hive where the instance configuration is stored (always \"HKLM\" for SQL Server) Path: The registry path within the hive where the instance stores its configuration (e.g., \"Software\\Microsoft\\Microsoft SQL Server\\MSSQL15.MSSQLSERVER\\Setup\") RegistryRoot: The full registry path ready for use with PowerShell registry cmdlets (e.g., \"HKLM:\\Software\\Microsoft\\Microsoft SQL Server\\...\") &nbsp;"
  },
  {
    "name": "Get-DbaRegServer",
    "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.",
    "category": "Utilities",
    "tags": [
      "registeredserver",
      "cms"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRegServer",
    "popularityRank": 64,
    "synopsis": "Retrieves registered SQL Server instances from SSMS, Azure Data Studio, and Central Management Server",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaRegServer View Source Bryan Hamby (@galador) , Chrissy LeMaire (@cl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves registered SQL Server instances from SSMS, Azure Data Studio, and Central Management Server 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. When 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. Local Registered Servers and Azure Data Studio support alternative authentication (excluding MFA) but Central Management Server does not. Syntax Get-DbaRegServer [[-SqlInstance] ] [[-SqlCredential] ] [[-Name] ] [[-ServerName] ] [[-Pattern] ] [[-ExcludeServerName] ] [[-Group] ] [[-ExcludeGroup] ] [[-Id] ] [-IncludeSelf] [-ResolveNetworkName] [-IncludeLocal] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets a list of servers from the local registered servers and azure data studio PS C:\\> Get-DbaRegServer Example 2: Gets a list of servers from the CMS on sqlserver2014a, using Windows Credentials PS C:\\> Get-DbaRegServer -SqlInstance sqlserver2014a Example 3: Gets a list of servers from the CMS on sqlserver2014a and includes sqlserver2014a in the output results PS C:\\> Get-DbaRegServer -SqlInstance sqlserver2014a -IncludeSelf Example 4: Returns only the server names from the CMS on sqlserver2014a, using SQL Authentication to authenticate to the... PS C:\\> Get-DbaRegServer -SqlInstance sqlserver2014a -SqlCredential $credential | Select-Object -Unique -ExpandProperty ServerName Returns only the server names from the CMS on sqlserver2014a, using SQL Authentication to authenticate to the server. Example 5: Gets a list of servers in the HR and Accounting groups from the CMS on sqlserver2014a PS C:\\> Get-DbaRegServer -SqlInstance sqlserver2014a -Group HR, Accounting Example 6: Returns a list of servers in the HR and sub-group Development from the CMS on sqlserver2014a PS C:\\> Get-DbaRegServer -SqlInstance sqlserver2014a -Group HR\\Development Example 7: Returns all registered servers that match the regex pattern &quot;^prod&quot; (e.g., prod-server1, production-db) from... PS C:\\> Get-DbaRegServer -SqlInstance sqlserver2014a -Pattern \"^prod\" Returns all registered servers that match the regex pattern \"^prod\" (e.g., prod-server1, production-db) from the CMS on sqlserver2014a. Example 8: Gets a list of servers in the Production group from the CMS on sqlserver2014a, excluding serverAlfa and... PS C:\\> Get-DbaRegServer -SqlInstance sqlserver2014a -Group Production -ExcludeServerName \"serverAlfa\", \"ServerBeta\" Gets 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. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | (Get-DbatoolsConfigValue -FullName 'commands.get-dbaregserver.defaultcms') | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Filters results to registered servers with specific display names as they appear in SSMS Registered Servers pane. Use this when you need to find servers by their friendly names rather than actual server names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ServerName Filters results to registered servers with specific server instance names (the actual SQL Server connection strings). Use this when you need to find servers by their network names or instance names rather than display names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Pattern Specifies a pattern for filtering registered servers using regular expressions. Use this when you need to match servers by pattern, such as \"^prod\" or \".-db$\". This parameter supports standard .NET regular expression syntax and matches against both Name and ServerName properties. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeServerName Excludes registered servers with specific server instance names (the actual SQL Server connection strings). Use this when you want to retrieve most servers but skip certain instances like those under maintenance or decommissioned. | Property | Value | | --- | --- | | Alias | ExcludeServer | | Required | False | | Pipeline | false | | Default Value | | -Group Filters results to registered servers within specific Central Management Server groups. Supports hierarchical paths using backslash notation (e.g., \"Production\\Database Servers\"). Use this to target servers organized by environment, department, or function. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeGroup Excludes registered servers from specific Central Management Server groups. Use this when you want to retrieve most servers but skip certain groups like \"Test\" or \"Decommissioned\" environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Id Filters results to registered servers with specific internal ID numbers. Use this when you need to retrieve specific servers by their unique identifiers, typically when working with programmatic scripts or automation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSelf Includes the Central Management Server instance itself in the results along with all registered servers. Use this when you need to perform operations on both the CMS and its registered servers in the same workflow. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ResolveNetworkName Performs DNS lookups to return NetBIOS names, FQDN, and IP addresses for each registered server. Use this when you need network information for servers, but be aware this adds processing time due to DNS queries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeLocal Includes local SSMS and Azure Data Studio registered servers in addition to Central Management Server results. Use this when querying a CMS but also want to see servers registered locally on your workstation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'commands.get-dbaregserver.includelocal') | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer Returns 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 one or more locations: Central Management Server (CMS): When SqlInstance parameter is provided Local SSMS Registered Servers: When no SqlInstance provided or -IncludeLocal is specified Azure Data Studio connections: When no SqlInstance provided or -IncludeLocal is specified CMS instance itself: When -IncludeSelf is specified with a CMS query Default display properties (via Select-DefaultView): Name: The display name of the registered server as shown in SSMS Registered Servers or Azure Data Studio ServerName: The actual SQL Server connection string (computer name, IP address, or instance name) Group: The CMS group path (hierarchical, using backslash separators) or null for root-level servers Description: Text description of the registered server Source: Source location of the registration - \"Central Management Servers\", \"Local Server Groups\", or \"Azure Data Studio\" When -ResolveNetworkName is specified, additional properties are included in default display: ComputerName: NetBIOS computer name resolved via DNS FQDN: Fully qualified domain name resolved via DNS IPAddress: IP address resolved via DNS Additional available properties from the RegisteredServer object: ComputerName: NetBIOS computer name of the CMS instance (for CMS-sourced servers) InstanceName: The SQL Server instance name of the CMS (for CMS-sourced servers) SqlInstance: The full SQL Server instance name of the CMS (for CMS-sourced servers) ParentServer: The parent CMS instance name (for CMS-sourced servers) ConnectionString: The connection string with decrypted password if available SecureConnectionString: The connection string as a SecureString object if password was decrypted Id: Internal identifier for the registered server ServerType: Type of server (DatabaseEngine, AnalysisServices, ReportingServices, etc.) CredentialPersistenceType: Whether credentials are stored (mainly for Azure Data Studio sources) All properties from the base RegisteredServer SMO object are accessible using Select-Object . &nbsp;"
  },
  {
    "name": "Get-DbaRegServerGroup",
    "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.",
    "category": "Utilities",
    "tags": [
      "registeredserver",
      "cms"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRegServerGroup",
    "popularityRank": 265,
    "synopsis": "Retrieves server group objects from SQL Server Central Management Server (CMS) for organized server management.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaRegServerGroup View Source Tony Wilhelm (@tonywsql) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves server group objects from SQL Server Central Management Server (CMS) for organized server management. 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. This 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. The 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. Syntax Get-DbaRegServerGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-Group] ] [[-ExcludeGroup] ] [[-Id] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the top level groups from the CMS on sqlserver2014a, using Windows Credentials PS C:\\> Get-DbaRegServerGroup -SqlInstance sqlserver2014a Example 2: Gets the top level groups from the CMS on sqlserver2014a, using alternative credentials to authenticate to... PS C:\\> Get-DbaRegServerGroup -SqlInstance sqlserver2014a -SqlCredential $credential Gets the top level groups from the CMS on sqlserver2014a, using alternative credentials to authenticate to the server. Example 3: Gets the HR and Accounting groups from the CMS on sqlserver2014a PS C:\\> Get-DbaRegServerGroup -SqlInstance sqlserver2014a -Group HR, Accounting Example 4: Returns the sub-group Development of the HR group from the CMS on sqlserver2014a PS C:\\> Get-DbaRegServerGroup -SqlInstance sqlserver2014a -Group HR\\Development Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Group Specifies one or more server group names to retrieve from Central Management Server. Supports hierarchical paths using backslash notation (e.g., 'Production\\WebServers'). Use this when you need specific organizational groups rather than all groups, or when working with nested subgroups within your CMS structure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeGroup Specifies one or more server group names to exclude from the results. Accepts the same hierarchical path format as the Group parameter. Use this when you want all groups except certain ones, such as excluding test environments from production operations or removing deprecated groups from inventory reports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.RegisteredServers.ServerGroup Returns 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 instance. Default display properties (via Select-DefaultView): ComputerName: The computer name of the CMS host (when CMS is database-based) InstanceName: The SQL Server instance name of the CMS SqlInstance: The full SQL Server instance name in computer\\instance format (when CMS is database-based) Name: The name of the server group DisplayName: Display name of the server group for UI presentation Description: Text description of the group's purpose or contents ServerGroups: Collection of child server groups nested under this group RegisteredServers: Collection of registered servers that belong to this group When querying the local file store (no -SqlInstance specified), ComputerName, InstanceName, and SqlInstance properties are not included in the default display, showing only Name, DisplayName, Description, ServerGroups, and RegisteredServers. All properties from the base SMO ServerGroup object are accessible using Select-Object *, including Urn, Parent, and other internal properties. &nbsp;"
  },
  {
    "name": "Get-DbaRegServerStore",
    "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.",
    "category": "Utilities",
    "tags": [
      "registeredserver",
      "cms"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRegServerStore",
    "popularityRank": 430,
    "synopsis": "Creates a RegisteredServersStore object for managing Central Management Server configurations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaRegServerStore View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a RegisteredServersStore object for managing Central Management Server configurations 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. Syntax Get-DbaRegServerStore [[-SqlInstance] ] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a SQL Server Registered Server Store Object from sqlserver2014a PS C:\\> Get-DbaRegServerStore -SqlInstance sqlserver2014a Example 2: Returns a SQL Server Registered Server Store Object from sqlserver2014a by logging in with the sqladmin login PS C:\\> Get-DbaRegServerStore -SqlInstance sqlserver2014a -SqlCredential sqladmin Optional Parameters -SqlInstance Specifies the SQL Server instance hosting the Central Management Server to retrieve the registered server store from. When omitted, returns the local file store containing your locally registered servers from SQL Server Management Studio. Use this when you need to access server groups and registered servers stored in a centralized CMS repository. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.RegisteredServers.RegisteredServersStore Returns 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 Studio. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance hosting the CMS InstanceName: The SQL Server instance name hosting the CMS SqlInstance: The full SQL Server instance name in computer\\instance format DatabaseEngineServerGroup: The root server group containing all registered servers and subgroups ServerGroups: Collection of top-level server groups RegisteredServers: Collection of registered servers at the root level Properties excluded from default display (internal/technical properties): ServerConnection, DomainInstanceName, DomainName, Urn, Properties, Metadata, Parent, ConnectionContext, PropertyMetadataChanged, PropertyChanged, ParentServer All SMO RegisteredServersStore properties are accessible using Select-Object *, including the excluded properties if needed for advanced operations. &nbsp;"
  },
  {
    "name": "Get-DbaReplArticle",
    "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.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaReplArticle",
    "popularityRank": 600,
    "synopsis": "Retrieves detailed information about replication articles from SQL Server publications.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaReplArticle View Source ClÃ¡udio Silva (@claudioessilva), claudioessilva.eu Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed information about replication articles from SQL Server publications. 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. This 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. Syntax Get-DbaReplArticle [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Publication] ] [[-Schema] ] [[-Name] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Retrieve information of all articles from all publications on all databases for server mssql1 PS C:\\> Get-DbaReplArticle -SqlInstance mssql1 Example 2: Retrieve information of all articles from all publications on &#39;pubs&#39; database for server mssql1 PS C:\\> Get-DbaReplArticle -SqlInstance mssql1 -Database pubs Example 3: Retrieve information of all articles from &#39;PubName&#39; on &#39;pubs&#39; database for server mssql1 PS C:\\> Get-DbaReplArticle -SqlInstance mssql1 -Database pubs -Publication PubName Example 4: Retrieve information of articles in the &#39;sales&#39; schema on &#39;pubs&#39; database for server mssql1 PS C:\\> Get-DbaReplArticle -SqlInstance mssql1 -Database pubs -Schema sales Example 5: Retrieve information of &#39;sales&#39; article from &#39;PubName&#39; on &#39;pubs&#39; database for server mssql1 PS C:\\> Get-DbaReplArticle -SqlInstance mssql1 -Database pubs -Publication PubName -Name sales Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to examine for replication articles. Only articles from publications in these databases will be returned. Use this when you need to focus on replication articles within specific databases rather than scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Publication Filters results to articles within specific replication publications. Only articles from these named publications will be returned. Use this when troubleshooting a specific publication or when you need to audit articles within particular publications rather than all publications in the database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need to examine replication articles for objects within specific schemas, such as when troubleshooting schema-specific replication issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Filters results to articles with specific names. Only articles matching these exact names will be returned. Use this when you need to examine specific replication articles by name, such as when troubleshooting issues with particular replicated objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Replication.Article Returns 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 replication publication. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: The database containing the publication PublicationName: The name of the publication containing this article Name: The name of the article as it appears in the publication Type: The type of object being replicated (Table, View, or StoredProcedure) VerticalPartition: Boolean indicating if the article uses vertical partitioning (column filtering) SourceObjectOwner: The schema name of the source object in the publisher database SourceObjectName: The object name of the source table, view, or stored procedure *Additional properties available (use Select-Object to access all): All Microsoft.SqlServer.Replication.Article object properties are accessible, including:* Destination object properties (DestinationObjectOwner, DestinationObjectName) Filter properties for horizontal and vertical partitioning Resolver and conflict handling properties Subscriber-specific properties and transforms Replication-specific metadata about the article All properties from the base SMO Article object are accessible even though only the 10 default properties are displayed without using Select-Object . &nbsp;"
  },
  {
    "name": "Get-DbaReplArticleColumn",
    "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't appearing in replicated data.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaReplArticleColumn",
    "popularityRank": 671,
    "synopsis": "Retrieves column-level replication configuration details for SQL Server publication articles.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaReplArticleColumn View Source ClÃ¡udio Silva (@claudioessilva), claudioessilva.eu Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves column-level replication configuration details for SQL Server publication articles. 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't appearing in replicated data. Syntax Get-DbaReplArticleColumn [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Publication] ] [[-Article] ] [[-Column] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Retrieve information of all replicated columns in any publications on server sqlserver2019 PS C:\\> Get-DbaReplArticleColumn -SqlInstance sqlserver2019 Example 2: Retrieve information of all replicated columns in any publications from the pubs database on server... PS C:\\> Get-DbaReplArticleColumn -SqlInstance sqlserver2019 -Database pubs Retrieve information of all replicated columns in any publications from the pubs database on server sqlserver2019. Example 3: Retrieve information of all replicated columns in the test publication on server sqlserver2019 PS C:\\> Get-DbaReplArticleColumn -SqlInstance sqlserver2019 -Publication test Example 4: Retrieve information of &#39;sales&#39; article from &#39;PubName&#39; on &#39;pubs&#39; database for server sqlserver2019 PS C:\\> Get-DbaReplArticleColumn -SqlInstance sqlserver2019 -Database pubs -Publication PubName -Article sales Example 5: Retrieve information for the state column in any publication from any database on server sqlserver2019 PS C:\\> Get-DbaReplArticleColumn -SqlInstance sqlserver2019 -Column state Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Filters results to specific database(s) containing publications. Accepts wildcards for pattern matching. Use this when you need to focus on replication columns from particular databases rather than scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Publication Filters results to specific publication(s) within the specified databases. Accepts wildcards for pattern matching. Use this when auditing column replication configuration for particular publications or troubleshooting column-level issues in specific publications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Article Filters results to specific article(s) within the publications. Accepts wildcards for pattern matching. Use this when you need to examine column replication details for particular tables or views that are published as articles. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Column Filters results to specific column name(s) across all matched articles. Case-sensitive exact match. Use this when investigating whether specific columns are included in replication or troubleshooting missing columns in subscriber databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per column for each matched article, with detailed article and column information added via NoteProperties. Default display properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: The database containing the publication PublicationName: The publication name ArticleName: The article name ArticleId: The unique identifier for the article ColumnName: The name of the column within the article Additional properties available: Description: Description of the article Type: Type of the article (Table, View, Stored Procedure, etc.) VerticalPartition: Boolean indicating if vertical partitioning is enabled SourceObjectOwner: Schema owner of the source table SourceObjectName: Name of the source table or view &nbsp;"
  },
  {
    "name": "Get-DbaReplDistributor",
    "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.",
    "category": "Utilities",
    "tags": [
      "replication"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaReplDistributor",
    "popularityRank": 627,
    "synopsis": "Retrieves replication distributor configuration and status information from SQL Server instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaReplDistributor View Source William Durkin (@sql_williamd) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves replication distributor configuration and status information from SQL Server instances. 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. Syntax Get-DbaReplDistributor [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Retrieve distributor information for servers sql2008 and sqlserver2012 PS C:\\> Get-DbaReplDistributor -SqlInstance sql2008, sqlserver2012 Example 2: Pipe a SQL Server instance to Get-DbaReplDistributor to retrieve distributor information PS C:\\> Connect-DbaInstance -SqlInstance mssql1 | Get-DbaReplDistributor Required Parameters -SqlInstance The target SQL Server instance or instances to check for replication distributor configuration. Use this to identify which servers in your environment are configured as distributors, where the distribution database is located, and whether they support remote publishers. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Replication.ReplicationServer Returns one ReplicationServer object per SQL Server instance with replication configuration and status information. Default display properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) IsPublisher: Boolean indicating if the instance is configured as a replication publisher IsDistributor: Boolean indicating if the instance is configured as a replication distributor DistributionServer: The name of the server hosting the distribution database (null if not a distributor) DistributionDatabase: The name of the distribution database (null if not a distributor) DistributorInstalled: Boolean indicating if distributor components are installed on the instance DistributorAvailable: Boolean indicating if the distributor is currently available and functional HasRemotePublisher: Boolean indicating if the distributor has remote publishers configured Additional properties available from the ReplicationServer object: ReplicationDatabases: Collection of databases enabled for replication (not necessarily actively replicated) DistributionDatabaseAvailable: Boolean indicating if the distribution database is accessible HardwareBoundary: Indicates hardware boundary for replication PublisherList: Collection of publishers using this distributor Use Select-Object * to access all available properties from the ReplicationServer object. &nbsp;"
  },
  {
    "name": "Get-DbaReplPublication",
    "description": "Scans SQL Server instances to identify and return all replication publications configured as publishers. This function examines each database's 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.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaReplPublication",
    "popularityRank": 601,
    "synopsis": "Retrieves replication publications from SQL Server instances, including transactional, merge, and snapshot publications.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaReplPublication View Source Colin Douglas Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves replication publications from SQL Server instances, including transactional, merge, and snapshot publications. Description Scans SQL Server instances to identify and return all replication publications configured as publishers. This function examines each database's 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. Syntax Get-DbaReplPublication [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Name] ] [[-Type] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Return all publications for servers sql2008 and sqlserver2012 PS C:\\> Get-DbaReplPublication -SqlInstance sql2008, sqlserver2012 Example 2: Return all publications on server sql2008 for only the TestDB database PS C:\\> Get-DbaReplPublication -SqlInstance sql2008 -Database TestDB Example 3: Return all transactional publications on server sql2008 PS C:\\> Get-DbaReplPublication -SqlInstance sql2008 -Type Transactional Example 4: Returns the Mergey publications on server mssql1 PS C:\\> Get-DbaReplPublication -SqlInstance mssql1 -Name Merge Example 5: Returns all publications on server mssql1 using the pipeline PS C:\\> Connect-DbaInstance -SqlInstance mssql1 | Get-DbaReplPublication Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to examine for replication publications. Accepts wildcards and multiple database names. Use this when you need to focus on specific databases instead of scanning all published databases on the instance. Only databases that have replication enabled will return publication information. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Filters results to publications with the specified name. Accepts multiple publication names for batch processing. Use this when you need to check the status or configuration of specific publications rather than viewing all publications in a database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Limits results to specific publication types: Transactional, Merge, or Snapshot. Use this to focus on a particular replication methodology when troubleshooting or auditing specific replication scenarios. Transactional publications provide real-time data synchronization, while Merge publications handle bidirectional conflicts and Snapshot publications provide point-in-time data distribution. | Property | Value | | --- | --- | | Alias | PublicationType | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Transactional,Merge,Snapshot | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Replication.Publication Returns 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 subscriptions. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The SQL Server replication server object DatabaseName: The name of the database containing the publication Name: The name of the publication Type: The publication type (Transactional, Merge, or Snapshot) Articles: Collection of published articles for this publication Subscriptions: Collection of subscriptions to this publication Additional properties available (from SMO Publication object): Description: Textual description of the publication PubId: Unique identifier for the publication Status: Current publication status CompatibilityLevel: Earliest SQL Server version supported by this publication RetentionPeriod: Number of days before subscription expires SnapshotMethod: Data file format of the initial snapshot ReplicateDdl: Whether DDL (schema changes) are replicated to subscribers HasSubscription: Boolean indicating if the publication has subscriptions FtpAddress, FtpPort, FtpSubdirectory: FTP settings for snapshot distribution PreSnapshotScript, PostSnapshotScript: Custom scripts executed before/after snapshot application All properties from the base SMO Publication object are accessible using Select-Object * even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Get-DbaReplPublisher",
    "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.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaReplPublisher",
    "popularityRank": 669,
    "synopsis": "Retrieves SQL Server replication publisher configuration and status from distribution servers.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaReplPublisher View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server replication publisher configuration and status from distribution servers. 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. Syntax Get-DbaReplPublisher [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets publisher for the mssql1 instance PS C:\\> Get-DbaReplPublisher -SqlInstance mssql1 Example 2: Pipes a SQL Server object to get publisher information for the mssql1 instance PS C:\\> Connect-DbaInstance -SqlInstance mssql1 | Get-DbaReplPublisher Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Replication.DistributionPublisher Returns one DistributionPublisher object for each Publisher configured on the distribution server instance. If no publishers are configured, nothing is returned. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Status: The current status of the Publisher (e.g., Healthy, Unhealthy) WorkingDirectory: Directory path where publication data and schema files are stored DistributionDatabase: The name of the distribution database used for this Publisher DistributionPublications: Number of transactional publications at the Publisher PublisherType: The type of Publisher (e.g., MSSQLSERVER for SQL Server, or third-party identifier) Name: The instance name of the Publisher Additional properties available (from SMO DistributionPublisher object): PublisherSecurity: Security context for replication agents connecting to the Publisher RegisteredSubscribers: Collection of Subscribers registered for this Publisher's publications TransPublications: Collection of transactional publications at the Publisher ThirdParty: Boolean indicating if this is a non-SQL Server Publisher TrustedDistributorConnection: Boolean indicating if the distributor connection is trusted HeterogeneousLogReaderAgentExists: Boolean indicating if a Log Reader Agent job exists ConnectionContext: The connection context to the SQL Server instance IsExistingObject: Boolean indicating if the object exists on the server All properties from the base SMO DistributionPublisher object are accessible using Select-Object * even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Get-DbaReplServer",
    "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.",
    "category": "Utilities",
    "tags": [
      "replication"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaReplServer",
    "popularityRank": 586,
    "synopsis": "Retrieves replication configuration and server role information from SQL Server instances",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaReplServer View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves replication configuration and server role information from SQL Server instances 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. Note: The ReplicationDatabases property gets the databases enabled for replication in the connected instance of Microsoft SQL Server/. Not necessarily the databases that are actually replicated. Syntax Get-DbaReplServer [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the replication server object for sql2016 using Windows authentication PS C:\\> Get-DbaReplServer -SqlInstance sql2016 Example 2: Gets the replication server object for sql2016 using SQL authentication PS C:\\> Get-DbaReplServer -SqlInstance sql2016 -SqlCredential repadmin Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Replication.ReplicationServer Returns one ReplicationServer object per SQL Server instance, providing information about the instance's role in the replication topology. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) IsDistributor: Boolean indicating if the instance is configured as a Distributor IsPublisher: Boolean indicating if the instance is configured as a Publisher DistributionServer: The name of the Distributor server (if configured) DistributionDatabase: The name of the distribution database (if configured) Additional properties available (from SMO ReplicationServer object): DistributorInstalled: Boolean indicating if a Distributor is installed DistributorAvailable: Boolean indicating if the Distributor is accessible WorkingDirectory: The Publisher's working directory location DistributionDatabases: Collection of configured distribution databases DistributionPublishers: Collection of Publishers using this Distributor ReplicationDatabases: Collection of databases enabled for replication RegisteredSubscribers: Collection of registered Subscriber instances AgentCheckupInterval: The Distribution Agent checkup frequency setting ConnectionContext: The SQL Server connection context object All properties from the base SMO ReplicationServer object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaReplSubscription",
    "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.\n\nPull subscriptions that exist only in the distribution database (but not in the publisher's syssubscriptions) are also returned, to handle cases where subscriptions were set up outside the normal creation process.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaReplSubscription",
    "popularityRank": 594,
    "synopsis": "Retrieves SQL Server replication subscription details for publications across instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaReplSubscription View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server replication subscription details for publications across instances. 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. Pull subscriptions that exist only in the distribution database (but not in the publisher's syssubscriptions) are also returned, to handle cases where subscriptions were set up outside the normal creation process. Syntax Get-DbaReplSubscription [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-PublicationName] ] [[-SubscriberName] ] [[-SubscriptionDatabase] ] [[-Type] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Return all subscriptions for all publications on server mssql1 PS C:\\> Get-DbaReplSubscription -SqlInstance mssql1 Example 2: Return all subscriptions for all publications on server mssql1 for only the TestDB database PS C:\\> Get-DbaReplSubscription -SqlInstance mssql1 -Database TestDB Example 3: Return all subscriptions for the publication Mergey on server mssql1 PS C:\\> Get-DbaReplSubscription -SqlInstance mssql1 -PublicationName Mergey Example 4: Return all subscriptions for all transactional publications on server mssql1 PS C:\\> Get-DbaReplSubscription -SqlInstance mssql1 -Type Push Example 5: Return all subscriptions for all publications on server mssql1 where the subscriber is mssql2 PS C:\\> Get-DbaReplSubscription -SqlInstance mssql1 -SubscriberName mssql2 Example 6: Return all subscriptions for all publications on server mssql1 where the subscription database is TestDB PS C:\\> Get-DbaReplSubscription -SqlInstance mssql1 -SubscriptionDatabase TestDB Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which publication databases to include when retrieving subscriptions. Accepts multiple database names and wildcards. Use this to focus on subscriptions from specific databases instead of checking all replicated databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PublicationName Filters results to subscriptions from specific publications by name. Accepts multiple publication names. Use this when you need to check subscription status for particular publications rather than all publications on the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SubscriberName Filters results to subscriptions where data is being delivered to specific subscriber instances. Accepts multiple instance names. Use this to monitor subscription health and activity for particular subscriber servers in your replication topology. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SubscriptionDatabase Filters results to subscriptions where data is being delivered to specific databases on subscriber instances. Accepts multiple database names. Use this to track how data flows to particular databases across your subscribers, especially when subscription databases have different names than source databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this to separate subscription management tasks or troubleshoot issues specific to push or pull delivery mechanisms. | Property | Value | | --- | --- | | Alias | PublicationType | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Push,Pull | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Replication.Subscription Returns one Subscription object per subscription found across all qualifying publications. Each object represents a replication relationship between a publisher and subscriber, showing subscription details, delivery method, and synchronization information. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance (publisher) InstanceName: The SQL Server instance name (publisher) SqlInstance: The full SQL Server instance name (computer\\instance) for the publisher DatabaseName: The name of the publication database on the publisher PublicationName: The name of the publication being subscribed to Name: The name of the subscription SubscriberName: The name of the Subscriber instance receiving replicated data SubscriptionDBName: The name of the database on the Subscriber receiving the data SubscriptionType: The type of subscription delivery (Push or Pull) Additional properties available (from SMO Subscription object): AgentJobId: The unique identifier of the agent job used for subscription synchronization AgentSchedule: The schedule for the synchronization agent job execution SynchronizationAgentName: The name of the synchronization agent job Status: The current status of the subscription (Active, Inactive, Uninitialized, etc.) SyncType: The manner in which the subscription is initialized (Automatic, None, Replicating) SubscriberSecurity: The security context for Subscriber connections SynchronizationAgentProcessSecurity: The Windows account credentials for the agent process All properties from the base SMO Subscription object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaResourceGovernor",
    "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.",
    "category": "Utilities",
    "tags": [
      "resourcegovernor"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaResourceGovernor",
    "popularityRank": 562,
    "synopsis": "Retrieves Resource Governor configuration and status from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaResourceGovernor View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Resource Governor configuration and status from SQL Server 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. Syntax Get-DbaResourceGovernor [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the resource governor object of the SqlInstance sql2016 PS C:\\> Get-DbaResourceGovernor -SqlInstance sql2016 Example 2: Gets the resource governor object on Sql1 and Sql2/sqlexpress instances PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaResourceGovernor Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.ResourceGovernor Returns one ResourceGovernor object per instance. The object represents the Resource Governor configuration and includes properties for enabled status, classifier function configuration, and resource pool management. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ClassifierFunction: The fully qualified name of the Resource Governor classifier function (e.g., [dbo].[fn_classifier]) Enabled: Boolean indicating if Resource Governor is enabled on the instance MaxOutstandingIOPerVolume: Maximum number of outstanding I/O operations allowed per disk volume ReconfigurePending: Boolean indicating if a Resource Governor configuration change is pending and requires ALTER RESOURCE GOVERNOR RECONFIGURE ResourcePools: Collection of ResourcePool objects defined on the instance ExternalResourcePools: Collection of ExternalResourcePool objects for machine learning workloads (SQL Server 2016+) Additional properties available (from SMO ResourceGovernor object): Parent: Reference to the parent Server object State: Current state of the SMO object (Existing, Creating, Pending, etc.) Urn: The unified resource name for the ResourceGovernor object All properties from the base SMO ResourceGovernor object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaRgClassifierFunction",
    "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.",
    "category": "Utilities",
    "tags": [
      "migration",
      "resourcegovernor"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRgClassifierFunction",
    "popularityRank": 642,
    "synopsis": "Retrieves the Resource Governor classifier function configured for workload group assignment",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaRgClassifierFunction View Source Alessandro Alpi (@suxstellino), alessandroalpi.blog Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves the Resource Governor classifier function configured for workload group assignment 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. Syntax Get-DbaRgClassifierFunction [[-SqlInstance] ] [[-SqlCredential] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the classifier function from sql2016 PS C:\\> Get-DbaRgClassifierFunction -SqlInstance sql2016 Example 2: Gets the classifier function object on Sql1 and Sql2/sqlexpress instances PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaResourceGovernor | Get-DbaRgClassifierFunction Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Resource Governor objects piped from Get-DbaResourceGovernor. Use this when processing multiple instances or when you already have Resource Governor objects to work with, allowing for efficient pipeline operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.UserDefinedFunction Returns 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 assign incoming connections to appropriate workload groups. If no classifier function is configured on the instance, nothing is returned. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database containing the function (always 'master' for classifier functions) Schema: The schema name containing the classifier function CreateDate: DateTime when the classifier function was created DateLastModified: DateTime when the classifier function was last modified Name: The name of the classifier function DataType: The return data type of the function (should be nvarchar for classifier functions) Additional properties available (from SMO UserDefinedFunction object): AssemblyName: Name of the CLR assembly if this is a CLR function FunctionType: Type of function (Scalar, Table, or Inline) ImplementationType: Implementation type (TransactSql or SqlClr) IsBuiltIn: Boolean indicating if this is a system function IsEditing: Boolean indicating if the function is being edited IsSystemObject: Boolean indicating if the function is a system object Urn: The unified resource name for the function object State: Current state of the SMO object (Existing, Creating, Pending, etc.) All properties from the base SMO UserDefinedFunction object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaRgResourcePool",
    "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.",
    "category": "Utilities",
    "tags": [
      "resourcegovernor"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRgResourcePool",
    "popularityRank": 673,
    "synopsis": "Retrieves SQL Server Resource Governor resource pools with their CPU, memory, and IOPS configuration settings",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaRgResourcePool View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Resource Governor resource pools with their CPU, memory, and IOPS configuration settings 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. Syntax Get-DbaRgResourcePool [[-SqlInstance] ] [[-SqlCredential] ] [[-Type] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the internal resource pools on sql2016 PS C:\\> Get-DbaRgResourcePool -SqlInstance sql2016 Example 2: Gets the internal resource pools on Sql1 and Sql2/sqlexpress instances PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaResourceGovernor | Get-DbaRgResourcePool Example 3: Gets the external resource pools on Sql1 and Sql2/sqlexpress instances PS C:\\> 'Sql1','Sql2/sqlexpress' | Get-DbaResourceGovernor | Get-DbaRgResourcePool -Type External Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies whether to retrieve Internal resource pools (CPU/memory) or External resource pools (R/Python services). Internal pools control SQL Server workloads, while External pools govern Machine Learning Services resource consumption. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Internal | | Accepted Values | Internal,External | -InputObject Accepts Resource Governor objects from Get-DbaResourceGovernor for pipeline processing. Use this when you need to filter or process resource pools from multiple instances collected earlier in your script. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.ResourcePool (Internal pools) or Microsoft.SqlServer.Management.Smo.ExternalResourcePool (External pools) Returns one ResourcePool or ExternalResourcePool object per resource pool found on the instance. The object type depends on the -Type parameter: Type \"Internal\" (default): Returns Microsoft.SqlServer.Management.Smo.ResourcePool objects Type \"External\": Returns Microsoft.SqlServer.Management.Smo.ExternalResourcePool objects Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: Unique identifier for the resource pool Name: Name of the resource pool CapCpuPercentage: CPU cap percentage (0-100 for External pools, always 0 for Internal pools) IsSystemObject: Boolean indicating if this is a system-defined resource pool MaximumCpuPercentage: Maximum CPU percentage allocated to this pool (0-100) MaximumIopsPerVolume: Maximum I/O operations per second per volume (External pools only) MaximumMemoryPercentage: Maximum memory percentage allocated to this pool (0-100) MinimumCpuPercentage: Minimum CPU percentage reserved for this pool (0-100) MinimumIopsPerVolume: Minimum I/O operations per second per volume (External pools only) MinimumMemoryPercentage: Minimum memory percentage reserved for this pool (0-100) WorkloadGroups: Collection of workload groups associated with this resource pool Additional properties available (from SMO ResourcePool or ExternalResourcePool objects): CreateDate: DateTime when the resource pool was created ModifyDate: DateTime when the resource pool was last modified Parent: Reference to the parent ResourceGovernor object State: Current state of the resource pool object (Existing, Creating, Pending, etc.) All properties from the base SMO object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaRgWorkloadGroup",
    "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.",
    "category": "Utilities",
    "tags": [
      "resourcegovernor"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRgWorkloadGroup",
    "popularityRank": 675,
    "synopsis": "Retrieves Resource Governor workload groups from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaRgWorkloadGroup View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Resource Governor workload groups from SQL Server instances 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. Syntax Get-DbaRgWorkloadGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the workload groups on sql2017 PS C:\\> Get-DbaRgWorkloadGroup -SqlInstance sql2017 Example 2: Gets the workload groups on sql2017 PS C:\\> Get-DbaResourceGovernor -SqlInstance sql2017 | Get-DbaRgResourcePool | Get-DbaRgWorkloadGroup Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts resource pool objects from Get-DbaRgResourcePool to retrieve workload groups from specific pools only. Use this to filter workload groups when you need to examine groups within particular resource pools instead of all workload groups across the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.WorkloadGroup Returns 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 handling behavior. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: Unique identifier for the workload group Name: Name of the workload group ExternalResourcePoolName: Name of the associated external resource pool (if applicable) GroupMaximumRequests: Maximum number of concurrent requests allowed in the workload group (0 = unlimited) Importance: Importance level of requests in this group (Low, Medium, High) IsSystemObject: Boolean indicating if this is a system-defined workload group MaximumDegreeOfParallelism: Maximum number of processors for parallel query execution (0 = unlimited) RequestMaximumCpuTimeInSeconds: Maximum CPU time in seconds per request (0 = unlimited) RequestMaximumMemoryGrantPercentage: Maximum memory grant as percentage of resource pool memory RequestMemoryGrantTimeoutInSeconds: Timeout in seconds for memory grant requests Additional properties available (from SMO WorkloadGroup object): ClassifierFunction: Name of the scalar classifier function (if any) CreateDate: DateTime when the workload group was created ModifyDate: DateTime when the workload group was last modified Parent: Reference to the parent ResourcePool object State: Current state of the workload group object All properties from the base SMO object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaRunningJob",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaRunningJob",
    "popularityRank": 281,
    "synopsis": "Retrieves SQL Server Agent jobs that are currently executing",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaRunningJob View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server Agent jobs that are currently executing 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. Use 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. The function refreshes job status information to provide real-time execution details rather than cached data. Syntax Get-DbaRunningJob [[-SqlInstance] ] [[-SqlCredential] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns any active jobs on sql2017 PS C:\\> Get-DbaRunningJob -SqlInstance sql2017 Example 2: Returns all active jobs on multiple instances piped into the function PS C:\\> Get-DbaAgentJob -SqlInstance sql2017, sql2019 | Get-DbaRunningJob Example 3: Returns all active jobs on multiple instances piped into the function PS C:\\> $servers | Get-DbaRunningJob Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts SQL Server Agent job objects piped from Get-DbaAgentJob for filtering to only running jobs. Use this when you need to check execution status on a specific set of jobs rather than all jobs on an instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Agent.Job Returns one Job object for each SQL Server Agent job that is currently executing (not in Idle state). When no jobs are running, the command returns nothing. Default display properties (via Get-DbaAgentJob with Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Name: The name of the Agent job CurrentRunStatus: Current execution status (Executing, Idle, Suspended, etc.) IsEnabled: Boolean indicating if the job is enabled LastRunOutcome: Result of the most recent execution (Succeeded, Failed, Cancelled, etc.) LastRunDate: DateTime of the most recent job execution NextRunDate: DateTime scheduled for the next execution Owner: The login that owns the job CreateDate: DateTime when the job was created Description: Text description of the job's purpose *Additional properties available from the base SMO Agent.Job object via Select-Object :* JobID: Unique identifier (GUID) for the job EventLogLevel: Logging level for event log (Never, OnSuccess, OnFailure, Always) EmailLevel: Email notification level (Never, OnSuccess, OnFailure, Always) NetSendLevel: Network send notification level (Never, OnSuccess, OnFailure, Always) NetsendOperatorName: Name of operator for network send notifications EmailOperatorName: Name of operator for email notifications OperatorToNetSend: Operator configured for network send notifications StartStepID: Step number where execution begins Category: The category/classification of the job DeleteLevel: When to delete job history (Never, OnSuccess, OnFailure, Always) TargetServers: Collection of target servers for multi-server jobs HasSchedule: Boolean indicating if the job has any schedules assigned All properties from the base SMO Agent.Job object are accessible using Select-Object . &nbsp;"
  },
  {
    "name": "Get-DbaSchemaChangeHistory",
    "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't exist before then.",
    "category": "Database Operations",
    "tags": [
      "trace",
      "changes",
      "database",
      "utility"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaSchemaChangeHistory",
    "popularityRank": 399,
    "synopsis": "Retrieves DDL change history from the SQL Server default system trace",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaSchemaChangeHistory View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves DDL change history from the SQL Server default system trace 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't exist before then. Syntax Get-DbaSchemaChangeHistory [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Since] ] [[-Object] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all DDL changes made in all databases on the SQL Server instance localhost since the system trace... PS C:\\> Get-DbaSchemaChangeHistory -SqlInstance localhost Returns all DDL changes made in all databases on the SQL Server instance localhost since the system trace began Example 2: Returns all DDL changes made in all databases on the SQL Server instance localhost in the last 7 days PS C:\\> Get-DbaSchemaChangeHistory -SqlInstance localhost -Since (Get-Date).AddDays(-7) Example 3: Returns all DDL changes made in the Prod and Finance databases on the SQL Server instance localhost in the... PS C:\\> Get-DbaSchemaChangeHistory -SqlInstance localhost -Database Finance, Prod -Since (Get-Date).AddDays(-7) Returns all DDL changes made in the Prod and Finance databases on the SQL Server instance localhost in the last 7 days Example 4: Returns all DDL changes made to the AccountsTable object in the Finance database on the SQL Server instance... PS C:\\> Get-DbaSchemaChangeHistory -SqlInstance localhost -Database Finance -Object AccountsTable -Since (Get-Date).AddDays(-7) Returns all DDL changes made to the AccountsTable object in the Finance database on the SQL Server instance localhost in the last 7 days Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to include when searching for schema changes. Accepts multiple database names and wildcards for pattern matching. Use this when you need to focus on specific databases instead of scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to exclude from the schema change search. Accepts multiple database names for filtering out unwanted databases. Use this to skip system databases, test databases, or any databases you don't want included in the change history results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Since Filters results to show only DDL changes that occurred after the specified date and time. Accepts standard PowerShell date formats. Use this to focus on recent changes or changes within a specific time period, especially helpful for troubleshooting recent issues or compliance reporting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Object Specifies the names of specific database objects to search for in the change history. Accepts multiple object names for targeted searches. Use this when investigating changes to particular tables, views, stored procedures, or other database objects rather than reviewing all schema changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per DDL change (CREATE, DROP, or ALTER operation) found in the SQL Server default system trace. When no schema changes are found matching the filter criteria, the command returns nothing. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) DatabaseName: The database in which the schema change occurred DateModified: DateTime when the DDL operation was executed LoginName: The login name (SQL or Windows) that executed the change UserName: The Windows user name (domain\\username format) if using Windows Authentication, or SQL login name ApplicationName: The application or tool that executed the DDL (e.g., \"SQL Server Management Studio\", \"sqlcmd\") DDLOperation: Type of operation performed - 'Create' for CREATE statements, 'Drop' for DROP statements, 'Alter' for ALTER statements Object: The name of the database object that was created, dropped, or altered (table, procedure, view, etc.) ObjectType: The type of database object affected (Table, StoredProcedure, View, Index, Trigger, UserDefinedFunction, etc.) All 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. &nbsp;"
  },
  {
    "name": "Get-DbaServerRole",
    "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.",
    "category": "Utilities",
    "tags": [
      "role"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaServerRole",
    "popularityRank": 189,
    "synopsis": "Retrieves server-level security roles and their members from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaServerRole View Source Shawn Melton (@wsmelton) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves server-level security roles and their members from SQL Server instances. 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. Syntax Get-DbaServerRole [-SqlInstance] [[-SqlCredential] ] [[-ServerRole] ] [[-ExcludeServerRole] ] [-ExcludeFixedRole] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Outputs list of server-level roles for sql2016a instance PS C:\\> Get-DbaServerRole -SqlInstance sql2016a Example 2: Outputs the server-level role(s) that are not fixed roles on sql2017a instance PS C:\\> Get-DbaServerRole -SqlInstance sql2017a -ExcludeFixedRole Required Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2005 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ServerRole Specifies one or more server-level roles to include in the results. Accepts role names like 'sysadmin', 'dbcreator', or custom role names. Use this when you need to audit specific roles rather than retrieving all server roles from the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeServerRole Specifies one or more server-level roles to exclude from the results. Useful for filtering out roles you don't need to audit. Commonly used to exclude built-in roles like 'public' when focusing on administrative roles with elevated permissions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeFixedRole Excludes built-in fixed server roles from the results, showing only custom user-defined server roles. Use this when auditing custom security configurations or identifying roles created by your organization rather than SQL Server's default roles. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.ServerRole Returns 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 (sysadmin, serveradmin, dbcreator, etc.) plus any custom user-defined server roles. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Role: The name of the server role (same as Name property) Login: Array of login names that are members of this role Owner: The principal that owns the server role IsFixedRole: Boolean indicating if this is a built-in fixed role (sysadmin, serveradmin, etc.) or a custom user-defined role DateCreated: DateTime when the role was created DateModified: DateTime when the role was last modified Additional properties available (from SMO ServerRole object): Name: The name of the server role Urn: The Uniform Resource Name of the server role object Properties: Collection of property objects for the role State: Current state of the SMO object (Existing, Creating, Pending, etc.) All properties from the base SMO ServerRole object are accessible using Select-Object even though only default properties are displayed without using Select-Object . &nbsp;"
  },
  {
    "name": "Get-DbaServerRoleMember",
    "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.",
    "category": "Security",
    "tags": [
      "role",
      "login"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaServerRoleMember",
    "popularityRank": 147,
    "synopsis": "Retrieves server-level role memberships for security auditing and compliance reporting.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaServerRoleMember View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves server-level role memberships for security auditing and compliance reporting. 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. Syntax Get-DbaServerRoleMember [-SqlInstance] [[-SqlCredential] ] [[-ServerRole] ] [[-ExcludeServerRole] ] [[-Login] ] [-ExcludeFixedRole] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all members of all server roles on the local default SQL Server instance PS C:\\> Get-DbaServerRoleMember -SqlInstance localhost Example 2: Returns all members of all server roles on the local and sql2016 SQL Server instances PS C:\\> Get-DbaServerRoleMember -SqlInstance localhost, sql2016 Example 3: Returns all members of all server roles for every server in C:\\servers.txt PS C:\\> $servers = Get-Content C:\\servers.txt PS C:\\> $servers | Get-DbaServerRoleMember Example 4: Returns all members of the sysadmin or dbcreator roles on localhost PS C:\\> Get-DbaServerRoleMember -SqlInstance localhost -ServerRole 'sysadmin', 'dbcreator' Example 5: Returns all members of server-level roles other than sysadmin PS C:\\> Get-DbaServerRoleMember -SqlInstance localhost -ExcludeServerRole 'sysadmin' Example 6: Returns all members of server-level role(s) that are not fixed roles on sql2017a instance PS C:\\> Get-DbaServerRoleMember -SqlInstance sql2017a -ExcludeFixedRole Example 7: Returns all server-level role(s) for the MyFriendlyDeveloper login on localhost PS C:\\> Get-DbaServerRoleMember -SqlInstance localhost -Login 'MyFriendlyDeveloper' Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | Credential | | Required | False | | Pipeline | false | | Default Value | | -ServerRole Specifies which server roles to check for membership. Accepts role names like 'sysadmin', 'dbcreator', 'securityadmin', or custom server roles. Use this when you need to focus your audit on specific high-privilege roles or investigate particular security concerns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeServerRole Excludes specified server roles from the membership report. Useful when you want to see all role memberships except certain roles. Commonly used to exclude low-privilege roles like 'public' when focusing on elevated permissions during security reviews. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Filters results to show only server role memberships for specific logins. Accepts login names including Windows accounts, SQL logins, and service accounts. Use this when investigating permissions for particular users or troubleshooting access issues for specific accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeFixedRole Excludes built-in server roles like sysadmin, securityadmin, and dbcreator, showing only custom server roles created by your organization. Only 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 member 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). Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Role: The name of the server role (sysadmin, dbcreator, securityadmin, or custom role name) Name: The login name that is a member of the role SmoRole: The SMO ServerRole object representing the role - allows access to all ServerRole properties and methods for further analysis SmoLogin: The SMO Login object representing the login - allows access to all Login properties and methods for further analysis Output quantity note: When a login is a member of multiple roles, one object is returned per role-login combination. For example, if 'sa' is a member of both sysadmin and securityadmin roles, two objects are returned - one for each role membership. &nbsp;"
  },
  {
    "name": "Get-DbaService",
    "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).",
    "category": "Server Management",
    "tags": [
      "service",
      "sqlserver",
      "instance",
      "connect"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaService",
    "popularityRank": 34,
    "synopsis": "Retrieves SQL Server-related Windows services from local or remote computers.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaService View Source Klaas Vandenberghe (@PowerDbaKlaas) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server-related Windows services from local or remote computers. 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. Particularly 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. Returns service objects with built-in methods for common operations like Start(), Stop(), Restart(), and ChangeStartMode(), eliminating the need to use separate service management commands. Requires Local Admin rights on destination computer(s). Syntax Get-DbaService [[-ComputerName] ] [-InstanceName ] [-SqlInstance ] [-Credential ] [-Type ] [-AdvancedProperties] [-EnableException] [ ] Get-DbaService [[-ComputerName] ] [-Credential ] [-ServiceName ] [-AdvancedProperties] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets the SQL Server related services on computer sqlserver2014a PS C:\\> Get-DbaService -ComputerName sqlserver2014a Example 2: Gets the SQL Server related services on computers sql1, sql2 and sql3 PS C:\\> 'sql1','sql2','sql3' | Get-DbaService -AdvancedProperties Gets the SQL Server related services on computers sql1, sql2 and sql3. Includes Advanced Properties from the SqlServiceAdvancedProperty Namespace Example 3: Gets the SQL Server related services on computers sql1 and sql2 via the user WindowsUser, and shows them in a... PS C:\\> $cred = Get-Credential WindowsUser PS C:\\> Get-DbaService -ComputerName sql1,sql2 -Credential $cred | Out-GridView Gets the SQL Server related services on computers sql1 and sql2 via the user WindowsUser, and shows them in a grid view. Example 4: Gets the SQL Server related services related to the default instance MSSQLSERVER on computers sql1 and sql2 PS C:\\> Get-DbaService -ComputerName sql1,sql2 -InstanceName MSSQLSERVER Example 5: Gets the SQL Server related services related to the default instance MSSQLSERVER on computers sql1, the named... PS C:\\> Get-DbaService -SqlInstance sql1, sql1\\test, sql2\\test Gets the SQL Server related services related to the default instance MSSQLSERVER on computers sql1, the named instances test on sql1 and sql2. Example 6: Gets the SQL Server related services of type &quot;SSRS&quot; (Reporting Services) on computers in the variable... PS C:\\> Get-DbaService -ComputerName $MyServers -Type SSRS Gets the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers. Example 7: Gets the SQL Server related services with ServiceName MSSQLSERVER or SQLSERVERAGENT for all the servers that... PS C:\\> $MyServers = Get-Content .\\servers.txt PS C:\\> Get-DbaService -ComputerName $MyServers -ServiceName MSSQLSERVER,SQLSERVERAGENT Gets 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. Example 8: Gets the SQL Server related services of types Sql Agent and DB Engine on computer sql1 and changes their... PS C:\\> $services = Get-DbaService -ComputerName sql1 -Type Agent,Engine PS C:\\> $services.ChangeStartMode('Manual') Gets the SQL Server related services of types Sql Agent and DB Engine on computer sql1 and changes their startup mode to 'Manual'. Example 9: Calls a Restart method for each Engine service on computer sql1 PS C:\\> (Get-DbaService -ComputerName sql1 -Type Engine).Restart($true) Optional Parameters -ComputerName Specifies the target computer(s) to retrieve SQL Server services from. Accepts computer names, IP addresses, or FQDN. Use this when you need to check service status across multiple servers in your environment. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -InstanceName Filters results to show only services belonging to the specified SQL Server instance names. Use this when you need to focus on specific instances rather than all SQL Server services on the target computers. | Property | Value | | --- | --- | | Alias | Instance | | Required | False | | Pipeline | false | | Default Value | | -SqlInstance Use a combination of computername and instancename to get the SQL Server related services for specific instances on specific computers. Parameters ComputerName and InstanceName will be ignored if SqlInstance is used. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Credential object used to connect to the computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Filters results to specific SQL Server service types such as Database Engine, SQL Agent, or Reporting Services. Use this when troubleshooting specific service types or performing targeted service management operations. Can be one of the following: \"Agent\", \"Browser\", \"Engine\", \"FullText\", \"SSAS\", \"SSIS\", \"SSRS\", \"PolyBase\", \"Launchpad\", \"PowerBI\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Agent,Browser,Engine,FullText,SSAS,SSIS,SSRS,PolyBase,Launchpad,PowerBI | -ServiceName Specifies exact Windows service names to retrieve, bypassing automatic service discovery. Use this when you know the specific service names and want to avoid the overhead of scanning for all SQL Server services. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AdvancedProperties Includes additional service properties such as SQL Server version, service pack level, SKU name, and cluster information. Use this when you need detailed service information for inventory, compliance, or troubleshooting purposes. Note that this adds processing time to the command. This will also output the additional property SqlInstance based on the Clustered and VSName properties for engine services. Use this property to connect to the correct SQL instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Wmi.SqlService Returns 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 information. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the service ServiceName: The Windows service name (e.g., MSSQLSERVER, SQLSERVERAGENT) ServiceType: The type of SQL Server service (Engine, Agent, FullText, SSIS, SSAS, SSRS, Browser, PolyBase, Launchpad, PowerBI, Unknown) InstanceName: The SQL Server instance name associated with the service DisplayName: The friendly display name of the service StartName: The user account under which the service runs State: The current state of the service (Stopped, Start Pending, Stop Pending, Running) StartMode: The startup mode of the service (Unknown, Automatic, Manual, Disabled) When -AdvancedProperties is specified, additional properties are included: Version: The SQL Server version number of the service SPLevel: The service pack level installed on the service SkuName: The SQL Server edition/SKU name (e.g., Enterprise, Standard) Clustered: Boolean (as numeric or empty) indicating if the service is part of a cluster VSName: The virtual server name if the service is clustered SqlInstance: The full SQL instance name (including virtual server name if clustered) for engine services ScriptMethods (callable on returned objects): Stop([bool]$Force): Stops the service, with optional force parameter Start(): Starts the service Restart([bool]$Force): Restarts the service, with optional force parameter ChangeStartMode([string]$Mode): Changes the startup mode (Automatic, Manual, Disabled) All service objects support Get-Member to view additional properties from the underlying WMI SqlService class. &nbsp;"
  },
  {
    "name": "Get-DbaSpConfigure",
    "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.",
    "category": "Utilities",
    "tags": [
      "spconfig",
      "configure",
      "configuration"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaSpConfigure",
    "popularityRank": 138,
    "synopsis": "Retrieves SQL Server sp_configure settings with default value comparisons for configuration auditing",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaSpConfigure View Source Nic Cain, sirsql.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server sp_configure settings with default value comparisons for configuration auditing 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. Essential 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. Particularly 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. Syntax Get-DbaSpConfigure [-SqlInstance] [[-SqlCredential] ] [[-Name] ] [[-ExcludeName] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all system configuration information on the localhost PS C:\\> Get-DbaSpConfigure -SqlInstance localhost Example 2: Returns system configuration information on multiple instances piped into the function PS C:\\> 'localhost','localhost\\namedinstance' | Get-DbaSpConfigure Example 3: Returns only the system configuration for MaxServerMemory on sql2012 PS C:\\> Get-DbaSpConfigure -SqlInstance sql2012 -Name 'max server memory (MB)' Example 4: Returns system configuration information on sql2012 but excludes for max server memory (MB) and remote access PS C:\\> Get-DbaSpConfigure -SqlInstance sql2012 -ExcludeName 'max server memory (MB)', RemoteAccess | Out-GridView Returns system configuration information on sql2012 but excludes for max server memory (MB) and remote access. Values returned in grid view Example 5: Returns system configuration information on sql2012 using SQL Server Authentication PS C:\\> $cred = Get-Credential SqlCredential PS C:\\> 'sql2012' | Get-DbaSpConfigure -SqlCredential $cred -Name RemoteAccess, 'max server memory (MB)' -ExcludeName 'remote access' | Out-GridView Returns system configuration information on sql2012 using SQL Server Authentication. Only MaxServerMemory is returned as RemoteAccess was also excluded. Required Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Return only specific configuration settings instead of all sp_configure values. Accepts either display names from sp_configure ('max server memory (MB)') or SMO property names ('MaxServerMemory'). Use this when you need to check specific settings like memory configuration, parallelism, or security options without retrieving the full list. | Property | Value | | --- | --- | | Alias | Config,ConfigName | | Required | False | | Pipeline | false | | Default Value | | -ExcludeName Exclude specific configuration settings from the results. Accepts either display names from sp_configure or SMO property names. Useful when generating reports or comparisons where you want to hide standard settings and focus on custom configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per sp_configure setting, providing comprehensive configuration details and comparison against SQL Server defaults. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Name: The SMO property name of the configuration setting (e.g., MaxServerMemory, CostThresholdForParallelism) DisplayName: The sp_configure display name of the setting (e.g., \"max server memory (MB)\") Description: Human-readable description of what the configuration setting controls IsAdvanced: Boolean indicating if this is an advanced configuration setting (requires ShowAdvancedOptions enabled) IsDynamic: Boolean indicating if the setting takes effect immediately (true) or requires restart (false) MinValue: The minimum allowed value for this setting (int/numeric) MaxValue: The maximum allowed value for this setting (int/numeric) ConfiguredValue: The current configured value stored in sys.configurations (may require restart to take effect) RunningValue: The currently running/active value in memory on the SQL Server instance DefaultValue: The out-of-the-box default value for this setting from SQL Server IsRunningDefaultValue: Boolean indicating if the running value matches the default value (true = using default, false = customized) *Hidden properties (accessible with Select-Object ):** ServerName: The server name (same as SqlInstance) Parent: Reference to the SMO Server object ConfigName: Alias for Name property Property: Reference to the underlying SMO ConfigurationProperty object &nbsp;"
  },
  {
    "name": "Get-DbaSpinLockStatistic",
    "description": "Queries sys.dm_os_spinlock_stats to return detailed statistics about SQL Server's 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's internal data structures.\n\nBased on Paul Randal's 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/",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "spinlockstatistics",
      "waits"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaSpinLockStatistic",
    "popularityRank": 501,
    "synopsis": "Retrieves spinlock contention statistics from SQL Server's internal synchronization mechanisms",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaSpinLockStatistic View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves spinlock contention statistics from SQL Server's internal synchronization mechanisms Description Queries sys.dm_os_spinlock_stats to return detailed statistics about SQL Server's 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. This 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's internal data structures. Based on Paul Randal's 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. Returns: SpinLockName - The type of spinlock (e.g., LOCK_HASH, LOGCACHE_ACCESS) Collisions - Number of times threads had to wait for the spinlock Spins - Total number of spin cycles before acquiring the lock SpinsPerCollision - Average spins per collision (efficiency indicator) SleepTime - Total time spent sleeping when spins were exhausted Backoffs - Number of times the thread backed off before retrying Reference: https://www.sqlskills.com/blogs/paul/advanced-performance-troubleshooting-waits-latches-spinlocks/ Syntax Get-DbaSpinLockStatistic [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get SpinLock Statistics for servers sql2008 and sqlserver2012 PS C:\\> Get-DbaSpinLockStatistic -SqlInstance sql2008, sqlserver2012 Example 2: Collects all SpinLock Statistics on server sql2008 into a Data Table PS C:\\> $output = Get-DbaSpinLockStatistic -SqlInstance sql2008 | Select-Object * | ConvertTo-DbaDataTable Example 3: Get SpinLock Statistics for servers sql2008 and sqlserver2012 via pipline PS C:\\> 'sql2008','sqlserver2012' | Get-DbaSpinLockStatistic Example 4: Connects using sqladmin credential and returns SpinLock Statistics from sql2008 PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Get-DbaSpinLockStatistic -SqlInstance sql2008 -SqlCredential $cred Required Parameters -SqlInstance The SQL Server instance. Server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) SpinLockName: The type of spinlock (e.g., LOCK_HASH, LOGCACHE_ACCESS) Collisions: Number of times threads had to wait for the spinlock Spins: Total number of spin cycles before acquiring the lock SpinsPerCollision: Average spins per collision (efficiency indicator) SleepTime: Total time spent sleeping when spins were exhausted (milliseconds) Backoffs: Number of times the thread backed off before retrying &nbsp;"
  },
  {
    "name": "Get-DbaSpn",
    "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.",
    "category": "Server Management",
    "tags": [
      "spn"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaSpn",
    "popularityRank": 79,
    "synopsis": "Retrieves existing Service Principal Names (SPNs) from Active Directory for SQL Server services",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaSpn View Source Drew Furgiuele (@pittfurg), port1433.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves existing Service Principal Names (SPNs) from Active Directory for SQL Server services 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. Syntax Get-DbaSpn [[-ComputerName] ] [[-AccountName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a custom object with SearchTerm (ServerName) and the SPNs that were found PS C:\\> Get-DbaSpn -ComputerName SQLSERVERA -Credential ad\\sqldba Example 2: Returns a custom object with SearchTerm (domain account) and the SPNs that were found PS C:\\> Get-DbaSpn -AccountName domain\\account -Credential ad\\sqldba Example 3: Returns a custom object with SearchTerm (ServerName) and the SPNs that were found for multiple computers PS C:\\> Get-DbaSpn -ComputerName SQLSERVERA,SQLSERVERB -Credential ad\\sqldba Optional Parameters -ComputerName Specifies the SQL Server computer names to retrieve registered SPNs for. Defaults to localhost if not specified. Use this when you need to audit SPN configuration on specific servers or when troubleshooting Kerberos authentication issues across multiple SQL instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -AccountName Specifies the Active Directory service accounts to search for registered SQL Server SPNs. Accepts both user accounts and computer accounts ending with '$'. Use this when you need to audit which SPNs are registered under specific service accounts or when investigating authentication issues related to particular accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential User credential to connect to the remote servers or active directory. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per Service Principal Name (SPN) found. The command supports two search modes that return the same object structure: Properties: Input: The search term provided (computer name or account name) AccountName: The Active Directory service account name ServiceClass: Always \"MSSQLSvc\" for SQL Server SPNs Port: The port number if present in the SPN; null if no port is specified SPN: The full Service Principal Name value &nbsp;"
  },
  {
    "name": "Get-DbaSsisEnvironmentVariable",
    "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't queried. Each parameter (besides SqlInstance and SqlCredential) acts as a filter to include or exclude specific environments or folders.",
    "category": "Utilities",
    "tags": [
      "ssis",
      "ssisdb",
      "variable"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaSsisEnvironmentVariable",
    "popularityRank": 462,
    "synopsis": "Retrieves environment variables from SSIS Catalog with decrypted sensitive values",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaSsisEnvironmentVariable View Source Bartosz Ratajczyk (@b_ratajczyk) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves environment variables from SSIS Catalog with decrypted sensitive values 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. This 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. The function communicates directly with SSISDB database - the SQL Server Integration Services service isn't queried. Each parameter (besides SqlInstance and SqlCredential) acts as a filter to include or exclude specific environments or folders. Syntax Get-DbaSsisEnvironmentVariable [-SqlInstance] [[-SqlCredential] ] [[-Environment] ] [[-EnvironmentExclude] ] [[-Folder] ] [[-FolderExclude] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets variables of &#39;DEV&#39; environment located in &#39;DWH_ETL&#39; folder on &#39;localhost&#39; Server PS C:\\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -Folder DWH_ETL Example 2: Gets variables of &#39;DEV&#39; environment(s) located in folders &#39;DWH_ETL&#39;, &#39;DEV2&#39; and &#39;QA&#39; on &#39;localhost&#39; server PS C:\\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -Folder DWH_ETL, DEV2, QA Example 3: Gets variables of &#39;DEV&#39; environments located in folders other than &#39;DWH_ETL&#39;, &#39;DEV2&#39; and &#39;QA&#39; on &#39;localhost&#39;... PS C:\\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV -FolderExclude DWH_ETL, DEV2, QA Gets variables of 'DEV' environments located in folders other than 'DWH_ETL', 'DEV2' and 'QA' on 'localhost' server Example 4: Gets variables of &#39;DEV&#39; and &#39;PROD&#39; environment(s) located in folders &#39;DWH_ETL&#39;, &#39;DEV2&#39; and &#39;QA&#39; on... PS C:\\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -Environment DEV, PROD -Folder DWH_ETL, DEV2, QA Gets variables of 'DEV' and 'PROD' environment(s) located in folders 'DWH_ETL', 'DEV2' and 'QA' on 'localhost' server Example 5: Gets variables of environments other than &#39;DEV&#39; and &#39;PROD&#39; located in folders &#39;DWH_ETL&#39;, &#39;DEV2&#39; and &#39;QA&#39; on... PS C:\\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -EnvironmentExclude DEV, PROD -Folder DWH_ETL, DEV2, QA Gets variables of environments other than 'DEV' and 'PROD' located in folders 'DWH_ETL', 'DEV2' and 'QA' on 'localhost' server Example 6: Gets variables of environments other than &#39;DEV&#39; and &#39;PROD&#39; located in folders other than &#39;DWH_ETL&#39;, &#39;DEV2&#39;... PS C:\\> Get-DbaSsisEnvironmentVariable -SqlInstance localhost -EnvironmentExclude DEV, PROD -FolderExclude DWH_ETL, DEV2, QA Gets variables of environments other than 'DEV' and 'PROD' located in folders other than 'DWH_ETL', 'DEV2' and 'QA' on 'localhost' server Example 7: Gets all SSIS environments except &#39;DEV&#39; and &#39;PROD&#39; from &#39;localhost&#39; server PS C:\\> 'localhost' | Get-DbaSsisEnvironmentVariable -EnvironmentExclude DEV, PROD Gets all SSIS environments except 'DEV' and 'PROD' from 'localhost' server. The server name comes from pipeline Example 8: Gets all SSIS environments from &#39;SRV1&#39; and &#39;SRV3&#39; servers PS C:\\> 'SRV1', 'SRV3' | Get-DbaSsisEnvironmentVariable Gets all SSIS environments from 'SRV1' and 'SRV3' servers. The server's names come from pipeline Example 9: Gets all variables from &#39;DEV&#39; Environment(s) on servers &#39;SRV1&#39; and &#39;SRV2&#39; and outputs it as the GridView PS C:\\> 'SRV1', 'SRV2' | Get-DbaSsisEnvironmentVariable DEV | Out-GridView Gets all variables from 'DEV' Environment(s) on servers 'SRV1' and 'SRV2' and outputs it as the GridView. The server names come from the pipeline. Example 10: Gets all variables from Environments other than &#39;DEV&#39; and &#39;PROD&#39; on &#39;localhost&#39; server, selects Name and... PS C:\\> 'localhost' | Get-DbaSsisEnvironmentVariable -EnvironmentExclude DEV, PROD | Select-Object -Property Name, Value | Where-Object {$_.Name -match '^a'} | Out-GridView Gets all variables from Environments other than 'DEV' and 'PROD' on 'localhost' server, selects Name and Value properties for variables that names start with letter 'a' and outputs it as the GridView Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Environment Specifies one or more SSIS environment names to retrieve variables from within the SSISDB catalog. Use this when you need variables from specific environments like 'DEV', 'QA', or 'PROD' rather than all environments in a folder. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnvironmentExclude Excludes specified SSIS environment names from the results when retrieving variables. Most effective when used without the Environment parameter to get all environments except those specified. Helpful when you want to audit all non-production environments or exclude specific environments from configuration reviews. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Folder Specifies one or more SSISDB catalog folder names that contain the environments you want to query. Use this to limit your search to specific project folders when you have environments organized by application or team. If omitted, the function searches all folders in the SSISDB catalog. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FolderExclude Excludes specified SSISDB catalog folder names from the search when retrieving environment variables. Most effective when used without the Folder parameter to search all folders except those specified. Useful when you want to exclude test folders, archived projects, or specific application folders from your audit. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SSIS environment variable found in the filtered environments and folders. Sensitive variable values are automatically decrypted and returned in plaintext. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Folder: The SSISDB catalog folder name containing the environment Environment: The name of the SSIS environment containing the variable Id: Unique identifier for the variable within the environment Name: The logical name of the environment variable Description: Text description of the variable's purpose Type: The type of variable (typically 'String', 'Int32', etc.) IsSensitive: Boolean indicating if the variable value is sensitive (encrypted in SSISDB) BaseDataType: The base data type used for the variable value storage Value: The actual variable value; automatically decrypted if sensitive, plaintext if not &nbsp;"
  },
  {
    "name": "Get-DbaSsisExecutionHistory",
    "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.",
    "category": "Performance",
    "tags": [
      "general",
      "ssis"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaSsisExecutionHistory",
    "popularityRank": 363,
    "synopsis": "Retrieves SSIS package execution history from the SSIS catalog database (SSISDB).",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaSsisExecutionHistory View Source Chris Tucker (@ChrisTuc47368095) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SSIS package execution history from the SSIS catalog database (SSISDB). 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. Useful 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. Syntax Get-DbaSsisExecutionHistory [-SqlInstance] [[-SqlCredential] ] [[-Since] ] [[-Status] ] [[-Project] ] [[-Folder] ] [[-Environment] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get all history items for SMTQ01 in folder SMTQ_PRC PS C:\\> Get-DbaSsisExecutionHistory -SqlInstance SMTQ01 -Folder SMTQ_PRC Example 2: Gets all failed or canceled executions for SMTQ01 PS C:\\> Get-DbaSsisExecutionHistory -SqlInstance SMTQ01 -Status Failed,Cancelled Example 3: Shows what would happen if the command were executed and would return the SQL statement that would be... PS C:\\> Get-DbaSsisExecutionHistory -SqlInstance SMTQ01,SMTQ02 -Status Failed,Cancelled Shows what would happen if the command were executed and would return the SQL statement that would be executed per instance. Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Since Limits results to executions that started on or after the specified date and time. Accepts datetime objects or strings. Use this to focus on recent executions when analyzing current issues or to exclude older historical data from large catalogs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Status Filters results to specific execution statuses such as Failed, Succeeded, or Running. Accepts multiple status values. Commonly used to find failed executions for troubleshooting or to monitor currently running packages during peak processing times. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this when troubleshooting issues within particular projects or analyzing execution patterns for specific deployments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Folder Filters results to specific SSIS catalog folders that contain projects and packages. Accepts an array of folder names. Useful for focusing on executions within specific organizational folders or when troubleshooting deployments in particular environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Environment Filters results to specific SSIS environments that were used during package execution. Accepts an array of environment names. Use this to analyze executions that used particular environment variables or to troubleshoot environment-specific configuration issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 catalog.executions view. Properties: ExecutionID: Unique identifier for the SSIS package execution instance FolderName: The SSISDB catalog folder name containing the project ProjectName: The name of the SSIS project that contains the executed package PackageName: The name of the SSIS package that was executed ProjectLsn: The project's Log Sequence Number indicating deployment version Environment: The environment used during execution (folder\\environment format, empty string if no environment) StatusCode: String representation of the execution status (Created, Running, Cancelled, Failed, Pending, Halted, Succeeded, Stopping, or Completed) StartTime: dbadatetime object representing when the package execution started EndTime: dbadatetime object representing when the package execution ended (NULL for running executions) ElapsedMinutes: Integer number of minutes elapsed between start and end time LoggingLevel: Integer value representing the logging level (0-5) used during execution &nbsp;"
  },
  {
    "name": "Get-DbaStartupParameter",
    "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.",
    "category": "Utilities",
    "tags": [
      "wsman",
      "sqlwmi",
      "memory",
      "startup"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaStartupParameter",
    "popularityRank": 339,
    "synopsis": "Retrieves SQL Server startup parameters from the Windows service configuration",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaStartupParameter View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server startup parameters from the Windows service configuration 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. Useful 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. See https://msdn.microsoft.com/en-us/library/ms190737.aspx for more information. Syntax Get-DbaStartupParameter [-SqlInstance] [[-Credential] ] [-Simple] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Logs into SQL WMI as the current user then displays the values for numerous startup parameters PS C:\\> Get-DbaStartupParameter -SqlInstance sql2014 Example 2: Logs in to WMI using the ad\\sqladmin credential and gathers simplified information about the SQL Server... PS C:\\> $wincred = Get-Credential ad\\sqladmin PS C:\\> Get-DbaStartupParameter -SqlInstance sql2014 -Credential $wincred -Simple Logs in to WMI using the ad\\sqladmin credential and gathers simplified information about the SQL Server Startup Parameters. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Allows you to login to servers using alternate Windows credentials. $scred = Get-Credential, then pass $scred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | SqlCredential | | Required | False | | Pipeline | false | | Default Value | | -Simple Returns only essential startup information: file paths (master data, master log, error log), trace flags, and the complete parameter string. Use this when you need a quick overview without detailed startup mode flags like single-user, minimal start, or monitoring settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance containing startup parameter configuration. When -Simple is specified, returns 9 essential properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) MasterData: Path to the master database file MasterLog: Path to the master transaction log file ErrorLog: Path to the SQL Server error log file TraceFlags: Array of trace flag integers, or \"None\" if no trace flags are configured DebugFlags: Array of debug flag integers, or \"None\" if no debug flags are configured ParameterString: The complete raw startup parameter string from Windows service configuration When -Simple is not specified (default), additional properties are included: CommandPromptStart: Boolean indicating if -c parameter is set (startup without GUI) MinimalStart: Boolean indicating if -f parameter is set (minimal configuration startup) MemoryToReserve: Integer value of -g parameter in MB, or 0 if not set (memory reserved for SQL Server) SingleUser: Boolean indicating if -m parameter is set (single-user mode enabled) SingleUserName: Application name for single-user mode, or empty string if not applicable NoLoggingToWinEvents: Boolean indicating if -n parameter is set (Windows event logging disabled) StartAsNamedInstance: Boolean indicating if -s parameter is set (named instance startup) DisableMonitoring: Boolean indicating if -x parameter is set (monitoring disabled) IncreasedExtents: Boolean indicating if -E parameter is set (increased extents enabled) &nbsp;"
  },
  {
    "name": "Get-DbaStartupProcedure",
    "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.",
    "category": "Utilities",
    "tags": [
      "procedure",
      "startup",
      "startupprocedure"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaStartupProcedure",
    "popularityRank": 571,
    "synopsis": "Retrieves stored procedures configured to run automatically when SQL Server starts up.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaStartupProcedure View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves stored procedures configured to run automatically when SQL Server starts up. 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. Syntax Get-DbaStartupProcedure [-SqlInstance] [[-SqlCredential] ] [[-StartupProcedure] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns an object with all startup procedures for the Instance2 instance on SqlBox1 PS C:\\> Get-DbaStartupProcedure -SqlInstance SqlBox1\\Instance2 Example 2: Returns an object with a startup procedure named &#39;dbo.StartupProc&#39; for the Instance2 instance on SqlBox1 PS C:\\> Get-DbaStartupProcedure -SqlInstance SqlBox1\\Instance2 -StartupProcedure 'dbo.StartupProc' Example 3: Returns an object with all startup procedures for every server listed in the Central Management Server on... PS C:\\> Get-DbaRegServer -SqlInstance sql2014 | Get-DbaStartupProcedure Returns an object with all startup procedures for every server listed in the Central Management Server on sql2014 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartupProcedure Filters results to check if specific stored procedures are configured as startup procedures. Accepts procedure names in 'schema.procedurename' format or just 'procedurename' for dbo schema. Use this when auditing server configurations or verifying that critical initialization procedures are properly configured to run at startup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.StoredProcedure Returns one StoredProcedure object for each stored procedure configured as a startup procedure in the master database. Connection context properties are added via NoteProperty. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Database name containing the stored procedure (always \"master\" for startup procedures) Schema: The schema name containing the stored procedure ObjectId: The object ID of the stored procedure within SQL Server CreateDate: DateTime when the stored procedure was created DateLastModified: DateTime when the stored procedure was last modified Name: The name of the stored procedure ImplementationType: The implementation type of the procedure (T-SQL or CLR) Startup: Boolean indicating if the procedure is configured as a startup procedure *Additional properties available from the SMO StoredProcedure object (use Select-Object ):** Parent: Reference to the parent database object Owner: The principal that owns the stored procedure ExecutionContext: Execution context (Caller or Owner) IsEncrypted: Boolean indicating if the procedure is encrypted IsRecompiled: Boolean indicating if the procedure is recompiled on execution IsSystemObject: Boolean indicating if this is a system object Urn: The Unified Resource Name for the object State: The current state of the SMO object (Existing, Creating, Pending, etc.) &nbsp;"
  },
  {
    "name": "Get-DbaSuspectPage",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "pages",
      "dbcc"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaSuspectPage",
    "popularityRank": 563,
    "synopsis": "Retrieves suspect page records from msdb database for corruption detection and analysis",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaSuspectPage View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves suspect page records from msdb database for corruption detection and analysis 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. Syntax Get-DbaSuspectPage [-SqlInstance] [[-Database] ] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Retrieve any records stored for Suspect Pages on the sql2016 SQL Server PS C:\\> Get-DbaSuspectPage -SqlInstance sql2016 Example 2: Retrieve any records stored for Suspect Pages on the sql2016 SQL Server and the Test database only PS C:\\> Get-DbaSuspectPage -SqlInstance sql2016 -Database Test Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Database Filters suspect page results to a specific database name. When omitted, returns suspect pages from all databases on the instance. Use this when investigating corruption issues in a particular database or when you need to focus troubleshooting efforts on a single database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per suspect page record found in the msdb.dbo.suspect_pages table. If no suspect pages exist, nothing is returned. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database containing the suspect page FileId: The file ID where the corrupt page is located (integer) PageId: The page ID of the suspect page (integer) EventType: The type of corruption event (823 or 824 I/O error, Bad Checksum, Torn Page, Restored, Repaired (DBCC), or Deallocated (DBCC)) ErrorCount: The number of times this page has been encountered as suspect (integer) LastUpdateDate: The date and time when the page was last detected as suspect (datetime) &nbsp;"
  },
  {
    "name": "Get-DbaTcpPort",
    "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't work, then remoting is used. If neither work, it defaults to T-SQL which can provide only the port.",
    "category": "Utilities",
    "tags": [
      "network",
      "connection",
      "tcp",
      "sqlwmi"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaTcpPort",
    "popularityRank": 173,
    "synopsis": "Returns the TCP port used by the specified SQL Server.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaTcpPort View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Returns the TCP port used by the specified SQL Server. Description By default, this function returns just the TCP port used by the specified SQL Server. If -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. Remote sqlwmi is used by default. If this doesn't work, then remoting is used. If neither work, it defaults to T-SQL which can provide only the port. Syntax Get-DbaTcpPort [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [-All] [-ExcludeIpv6] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns just the port number for the default instance on sqlserver2014a PS C:\\> Get-DbaTcpPort -SqlInstance sqlserver2014a Example 2: Returns an object with server name and port number for the sqlexpress on winserver and the default instance... PS C:\\> Get-DbaTcpPort -SqlInstance winserver\\sqlexpress, sql2016 Returns an object with server name and port number for the sqlexpress on winserver and the default instance on sql2016. Example 3: Returns an object with server name, IPAddress (ipv4 and ipv6), port and static ($true/$false) for... PS C:\\> Get-DbaTcpPort -SqlInstance sqlserver2014a, sql2016 -All Returns an object with server name, IPAddress (ipv4 and ipv6), port and static ($true/$false) for sqlserver2014a and sql2016. Remote sqlwmi is used by default. If this doesn't work, then remoting is used. If neither work, it defaults to T-SQL which can provide only the port. Example 4: Returns an object with server name, IPAddress (just ipv4), port and static ($true/$false) for every server... PS C:\\> Get-DbaRegServer -SqlInstance sql2014 | Get-DbaTcpPort -ExcludeIpv6 -All Returns an object with server name, IPAddress (just ipv4), port and static ($true/$false) for every server listed in the Central Management Server on sql2014. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Allows you to connect to servers using alternate Windows credentials $scred = Get-Credential, then pass $scred object to the -SqlCredential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Credential object used to connect to the Computer as a different user | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -All Returns comprehensive network configuration details including server name, IP addresses (IPv4 and IPv6), port numbers, and whether the port assignment is static. Use this when troubleshooting connectivity issues or when you need complete network configuration information instead of just the port number. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeIpv6 Excludes IPv6 addresses from the output when used with the All parameter, showing only IPv4 network configurations. Use this in environments where IPv6 is disabled or when you only need to focus on IPv4 connectivity for troubleshooting. | Property | Value | | --- | --- | | Alias | Ipv4 | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Default output (without -All parameter): Returns one object per instance with basic connection information. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) IPAddress: The IP address that SQL Server is listening on (IPv4 or IPv6) Port: The TCP port number that SQL Server is using (integer) When -All parameter is specified: Returns one object per TCP/IP address configuration on the instance, with detailed network settings including both IPv4 and IPv6 addresses (unless -ExcludeIpv6 is used). Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Name: The configuration name (IPAll, IP1, IP2, IP3, IP4, etc.) Active: Boolean indicating if this IP address is currently active Enabled: Boolean indicating if this IP address is enabled in the configuration IpAddress: The IP address value (IPv4 or IPv6 notation) TcpDynamicPorts: The dynamic port range if dynamic port assignment is configured TcpPort: The static TCP port number if static port assignment is configured IsUsed: Boolean indicating whether this IP/port combination is actually in use (based on ListenAll property and Enabled status) When -ExcludeIpv6 is specified with -All: Returns only IPv4 addresses, filtering out any IPv6 entries from the results. &nbsp;"
  },
  {
    "name": "Get-DbaTempdbUsage",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "tempdb"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaTempdbUsage",
    "popularityRank": 137,
    "synopsis": "Gets Tempdb usage for running queries.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaTempdbUsage View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Gets Tempdb usage for running queries. 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. Syntax Get-DbaTempdbUsage [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets tempdb usage for localhost\\SQLDEV2K14 PS C:\\> Get-DbaTempdbUsage -SqlInstance localhost\\SQLDEV2K14 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per running session that has allocated or deallocated tempdb space. For sessions with no tempdb allocation activity, no object is returned. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Spid: Session ID of the running query (int) StatementCommand: The SQL command being executed (SELECT, INSERT, UPDATE, DELETE, etc.) QueryText: The actual T-SQL statement text being executed ProcedureName: Schema-qualified name of the stored procedure if applicable StartTime: DateTime when the request started executing CurrentUserAllocatedKB: Current user object allocation in KB for this session (int) TotalUserAllocatedKB: Total user object allocation in KB (int) UserDeallocatedKB: User object deallocation in KB (int) TotalUserDeallocatedKB: Total user object deallocation in KB (int) InternalAllocatedKB: Internal object allocation in KB (int) TotalInternalAllocatedKB: Total internal object allocation in KB (int) InternalDeallocatedKB: Internal object deallocation in KB (int) TotalInternalDeallocatedKB: Total internal object deallocation in KB (int) RequestedReads: Number of physical read operations performed by the request (int) RequestedWrites: Number of write operations performed by the request (int) RequestedLogicalReads: Number of logical read operations performed by the request (int) RequestedCPUTime: CPU time in milliseconds used by the request (int) IsUserProcess: Boolean indicating if the session is a user process (true) or system process (false) Status: Current status of the session (running, sleeping, dormant, etc.) Database: Name of the database being accessed LoginName: SQL Server login name OriginalLoginName: Original login name before impersonation if applicable NTDomain: Windows domain name if Windows authentication is used NTUserName: Windows username if Windows authentication is used HostName: Client computer hostname ProgramName: Name of the client application (e.g., SQL Server Management Studio, SSMS) LoginTime: DateTime when the session logged in LastRequestedStartTime: DateTime when the last request started LastRequestedEndTime: DateTime when the last request ended &nbsp;"
  },
  {
    "name": "Get-DbatoolsChangeLog",
    "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.",
    "category": "Utilities",
    "tags": [
      "module",
      "changelog"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbatoolsChangeLog",
    "popularityRank": 531,
    "synopsis": "Opens the dbatools release changelog in your default browser",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbatoolsChangeLog View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Opens the dbatools release changelog in your default browser 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. Syntax Get-DbatoolsChangeLog [-Local] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Opens a browser to our online changelog PS C:\\> Get-DbatoolsChangeLog Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs None This command does not return any objects. It opens the dbatools release changelog in your default browser or displays a message for unsupported options. &nbsp;"
  },
  {
    "name": "Get-DbatoolsConfig",
    "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.",
    "category": "Utilities",
    "tags": [
      "module"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbatoolsConfig",
    "popularityRank": 185,
    "synopsis": "Retrieves dbatools module configuration settings and preferences.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbatoolsConfig View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves dbatools module configuration settings and preferences. 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. Syntax Get-DbatoolsConfig [[-FullName] ] [-Force] [ ] Get-DbatoolsConfig [[-Name] ] [[-Module] ] [-Force] [ ] &nbsp; Examples &nbsp; Example 1: Retrieves the configuration element for the key &quot;Mail.To&quot; PS C:\\> Get-DbatoolsConfig 'Mail.To' Example 2: Retrieve all configuration elements from all modules, even hidden ones PS C:\\> Get-DbatoolsConfig -Force Optional Parameters -FullName Default: \"\" Specifies the complete configuration key in Module.Name format to retrieve specific dbatools settings. Use this to find exact configuration values like \"sql.connection.timeout\" or \"mail.smtpserver\" without needing to specify module and name separately. Supports wildcards for pattern matching across all configuration keys. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Default: \"\" Specifies the configuration name to search for within a specific module. Use this with the Module parameter to find settings like \"timeout\" within the \"sql\" module or \"smtpserver\" within the \"mail\" module. Supports wildcards for finding multiple related configuration names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Module Default: \"\" Specifies which dbatools module's configuration settings to retrieve. Use this to focus on specific areas like \"sql\" for connection settings, \"mail\" for email configurations, or \"path\" for default file locations. Commonly used modules include sql, mail, path, and logging. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Includes hidden configuration values that are normally not displayed in the output. Use this when troubleshooting dbatools behavior or when you need to see internal configuration settings that control advanced module functionality. Hidden settings often include debugging flags and internal module state information. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Configuration.ConfigurationValue Returns 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 configuration name. Properties: Module: The module name component (e.g., \"sql\", \"mail\", \"path\", \"logging\") Name: The configuration setting name within the module (e.g., \"timeout\", \"smtpserver\") Value: The current value stored in the configuration setting (can be any object type) Description: Human-readable description of what the configuration controls Hidden: Boolean indicating if this is a hidden configuration setting When 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 by default unless -Force is specified. &nbsp;"
  },
  {
    "name": "Get-DbatoolsConfigValue",
    "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.",
    "category": "Utilities",
    "tags": [
      "module"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbatoolsConfigValue",
    "popularityRank": 417,
    "synopsis": "Retrieves a specific dbatools configuration value by its exact name.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbatoolsConfigValue View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves a specific dbatools configuration value by its exact name. 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. Syntax Get-DbatoolsConfigValue [-FullName] [[-Fallback] ] [-NotNull] [ ] &nbsp; Examples &nbsp; Example 1: Returns the configured value that was assigned to the key &#39;System.MailServer&#39; PS C:\\> Get-DbatoolsConfigValue -Name 'System.MailServer' Example 2: Returns the configured value for &#39;Default.CoffeeMilk&#39; PS C:\\> Get-DbatoolsConfigValue -Name 'Default.CoffeeMilk' -Fallback 0 Returns the configured value for 'Default.CoffeeMilk'. If no such value is configured, it returns '0' instead. Required Parameters -FullName Specifies the exact configuration setting name in Module.Name format (like 'sql.connection.timeout' or 'path.dbatoolsdata'). Use this to retrieve specific dbatools module settings that control behavior like connection timeouts, default file paths, or email configurations. | Property | Value | | --- | --- | | Alias | Name | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -Fallback Provides a default value to return when the specified configuration setting doesn't exist or is set to null. Use this in scripts when you need a reliable value even if the configuration hasn't been set, such as providing a default timeout of 30 seconds when no custom timeout is configured. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NotNull Forces the function to throw an error instead of returning null when no configuration value is found. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs object Returns 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 stored in that configuration. Return behavior: If the configuration exists and has a value, returns that value If the configuration doesn't exist or is null AND -Fallback is specified, returns the Fallback value If the configuration doesn't exist or is null AND -NotNull is specified, throws an error If the configuration doesn't exist or is null AND neither -Fallback nor -NotNull is specified, returns $null Special handling: String values of \"Mandatory\" are automatically converted to $true and \"Optional\" are converted to $false to prevent switch parameter parsing issues. &nbsp;"
  },
  {
    "name": "Get-DbatoolsError",
    "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.",
    "category": "Utilities",
    "tags": [
      "module",
      "support"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbatoolsError",
    "popularityRank": 480,
    "synopsis": "Retrieves detailed error information from failed dbatools commands for troubleshooting",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbatoolsError View Source Chrissy LeMaire (@cl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed error information from failed dbatools commands for troubleshooting 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. Syntax Get-DbatoolsError [[-First] ] [[-Last] ] [[-Skip] ] [-All] [ ] &nbsp; Examples &nbsp; Example 1: Returns detailed error information for the most recent dbatools error PS C:\\> Get-DbatoolsError Example 2: Returns detailed error information for all dbatools-related errors PS C:\\> Get-DbatoolsError -All Example 3: Returns the oldest dbatools-related error in the pipeline PS C:\\> Get-DbatoolsError -Last 1 Optional Parameters -First Specifies the number of most recent dbatools errors to return. Defaults to 1 if no parameters are specified. Use this when you need to examine the latest few errors after a batch operation or troubleshooting session. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Last Specifies the number of oldest dbatools errors to return from the error history. Use this when you need to see the earliest errors that occurred during a session or to trace the root cause of cascading failures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Skip Specifies the number of most recent dbatools errors to skip before returning results. Use this when you want to ignore the latest error and examine previous errors, or when paging through error history. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -All Returns detailed information for all dbatools-related errors in the current PowerShell session. Use this when creating support tickets, analyzing error patterns, or performing comprehensive troubleshooting of multiple failed commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Management.Automation.ErrorRecord Returns one or more ErrorRecord objects from the PowerShell global error collection, filtered to show only dbatools-related errors based on the FullyQualifiedErrorId containing \"dbatools\". Properties (selected from ErrorRecord): CategoryInfo: The error category classification (e.g., ConnectionError, PermissionDenied, SyntaxError) ErrorDetails: Additional structured error information including message and recommendations Exception: The underlying .NET exception that was thrown FullyQualifiedErrorId: Fully qualified error identifier used to identify dbatools-related errors InvocationInfo: Details about where and how the error occurred in the script (file, line, column, command name) PipelineIterationInfo: Information about the position in the pipeline when the error occurred PSMessageDetails: Additional PowerShell message details if available ScriptStackTrace: Stack trace showing the call hierarchy at the point of the error TargetObject: The object that was being processed when the error occurred All properties from the full ErrorRecord object are available using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbatoolsLog",
    "description": "Retrieves log entries from dbatools' internal logging system, allowing you to troubleshoot command execution and track what happened during script runs. Use this when dbatools commands aren't 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.",
    "category": "Utilities",
    "tags": [
      "module",
      "support"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbatoolsLog",
    "popularityRank": 258,
    "synopsis": "Retrieves internal log entries and error messages from dbatools module execution",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbatoolsLog View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves internal log entries and error messages from dbatools module execution Description Retrieves log entries from dbatools' internal logging system, allowing you to troubleshoot command execution and track what happened during script runs. Use this when dbatools commands aren't 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. Syntax Get-DbatoolsLog [[-FunctionName] ] [[-ModuleName] ] [[-Target] ] [[-Tag] ] [[-Last] ] [-LastError] [[-Skip] ] [[-Runspace] ] [[-Level] {Critical | Important | Output | Significant | VeryVerbose | Verbose | SomewhatVerbose | System | Debug | InternalComment | Warning}] [-Raw] [-Errors] [ ] &nbsp; Examples &nbsp; Example 1: Returns all log entries currently in memory PS C:\\> Get-DbatoolsLog Example 2: Returns the last log entry type of error PS C:\\> Get-DbatoolsLog -LastError Example 3: Returns all log entries that targeted the object &quot;a&quot; in the second last execution sent PS C:\\> Get-DbatoolsLog -Target \"a\" -Last 1 -Skip 1 Example 4: Returns all log entries within the last 5 executions that contained the tag &quot;fail&quot; PS C:\\> Get-DbatoolsLog -Tag \"fail\" -Last 5 Optional Parameters -FunctionName Filters log entries to show only messages from dbatools functions matching this pattern. Supports wildcards. Use this when troubleshooting specific commands like 'Backup-DbaDatabase' or when you want to see all backup-related functions with 'Backup-Dba'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ModuleName Filters log entries to show only messages from modules matching this pattern. Supports wildcards. Use this when working with multiple PowerShell modules and you only want to see dbatools-related log entries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | * | -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. Use this when troubleshooting issues with a particular SQL Server instance or database to see only relevant log entries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Tag Filters log entries to show only messages that contain any of the specified tags. Use this to find specific types of operations like 'backup', 'restore', or 'migration' when tracking down issues with particular dbatools workflows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Last Returns log entries from only the last X PowerShell command executions in your current session. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -LastError Returns only the most recent error message from the dbatools logging system. Use this as a quick way to see what went wrong with your last dbatools command execution without scrolling through all log entries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Skip Specifies how many recent executions to skip when using the -Last parameter. Use this when you want to see log entries from earlier executions, like '-Last 3 -Skip 2' to see the 3rd, 4th, and 5th most recent executions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Runspace Filters log entries to show only messages from the specified PowerShell runspace GUID. Use this when troubleshooting parallel or background dbatools operations to isolate messages from specific execution threads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Level Filters log entries by message severity level (Critical, Error, Warning, Info, Verbose, etc.). Use 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). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Raw Returns log messages in their original format without flattening multiline content like SQL statements. Use this when you need to see the exact formatting of SQL queries or error messages for detailed troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Errors Returns error entries from dbatools' error tracking system instead of regular log entries. Use this when you specifically need to see exceptions and errors that occurred during dbatools command execution, separate from informational logging. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Message.LogEntry (when -Raw is specified) Returns raw internal LogEntry objects from the dbatools logging system without any property filtering or flattening of multiline content. PSCustomObject (default) Returns log entries with the following properties formatted for user display: CallStack: The PowerShell call stack at the point the log entry was created ComputerName: The name of the computer where the log entry was generated File: The PowerShell script file name where the log entry originated FunctionName: The name of the dbatools function that created the log entry Level: The severity level of the log message (Critical, Error, Warning, Info, Verbose, Debug, etc.) Line: The line number in the script file where the log entry was generated Message: The log message text with multiline content (SQL statements, multiline errors) flattened to single line by joining with spaces and collapsing multiple spaces ModuleName: The name of the module that generated the log entry (typically \"dbatools\") Runspace: The PowerShell runspace GUID in which the log entry was created Tags: Array of tag strings associated with the log entry for categorization (e.g., \"backup\", \"restore\", \"connection\") TargetObject: The SQL Server object being processed when the log entry was created (e.g., server name, database name) Timestamp: The DateTime when the log entry was created Type: The type of log entry (Information, Error, Warning, etc.) Username: The username of the person executing the command that generated the log entry Note: Use -Raw to return unmodified LogEntry objects with Message content preserved in original multiline format for detailed troubleshooting of SQL statements. &nbsp;"
  },
  {
    "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.<PathName>\". 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.",
    "category": "Utilities",
    "tags": [],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbatoolsPath",
    "popularityRank": 451,
    "synopsis": "Retrieves configured file paths used by dbatools functions for storing temporary files, logs, and output data.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbatoolsPath View Source Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves configured file paths used by dbatools functions for storing temporary files, logs, and output data. 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. Paths can be configured using Set-DbatoolsPath or directly through the configuration system by creating settings with the format \"Path.Managed. \". 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. Syntax Get-DbatoolsPath [-Name] [ ] &nbsp; Examples &nbsp; Example 1: Returns the temp path PS C:\\> Get-DbatoolsPath -Name 'temp' Required Parameters -Name Specifies the name of the configured path to retrieve. Common predefined paths include 'Temp' for temporary file operations, 'LocalAppData' for user-specific application data, 'AppData' for roaming profile data, and 'ProgramData' for system-wide application data. Use 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 directories or report output locations. Custom path names can be defined using Set-DbatoolsPath and referenced here for consistent file management across your SQL Server administration scripts. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Outputs System.String Returns 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 custom-defined path). Returns $null if the specified path name is not configured. &nbsp;"
  },
  {
    "name": "Get-DbaTopResourceUsage",
    "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've 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.\"",
    "category": "Advanced Features",
    "tags": [
      "diagnostic",
      "performance",
      "query"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaTopResourceUsage",
    "popularityRank": 288,
    "synopsis": "Identifies the most resource-intensive cached queries from sys.dm_exec_query_stats for performance troubleshooting",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaTopResourceUsage View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies the most resource-intensive cached queries from sys.dm_exec_query_stats for performance troubleshooting 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. When 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. You 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. This command is based off of queries provided by Michael J. Swart at http://michaeljswart.com/go/Top20 Per Michael: \"I've 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.\" Syntax Get-DbaTopResourceUsage [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Type] ] [[-Limit] ] [-EnableException] [-ExcludeSystem] [ ] &nbsp; Examples &nbsp; Example 1: Return the 80 (20 x 4 types) top usage results by duration, frequency, IO, and CPU servers for servers... PS C:\\> Get-DbaTopResourceUsage -SqlInstance sql2008, sql2012 Return the 80 (20 x 4 types) top usage results by duration, frequency, IO, and CPU servers for servers sql2008 and sql2012 Example 2: Return the highest usage by duration (top 20) and frequency (top 20) for the TestDB on sql2008 PS C:\\> Get-DbaTopResourceUsage -SqlInstance sql2008 -Type Duration, Frequency -Database TestDB Example 3: Return the highest usage by duration (top 30) and frequency (top 30) for the TestDB on sql2016 PS C:\\> Get-DbaTopResourceUsage -SqlInstance sql2016 -Limit 30 Example 4: Return the 80 (20 x 4 types) top usage results by duration, frequency, IO, and CPU servers for servers... PS C:\\> Get-DbaTopResourceUsage -SqlInstance sql2008, sql2012 -ExcludeSystem Return 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 Example 5: Return all the columns plus the QueryPlan column PS C:\\> Get-DbaTopResourceUsage -SqlInstance sql2016| Select-Object Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for resource-intensive queries. Accepts multiple database names. Use this when troubleshooting performance issues in specific databases rather than analyzing server-wide query performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip when analyzing query performance across the SQL Server instance. Use this to exclude test databases, archived databases, or other databases that aren't relevant to your performance investigation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies which resource usage metrics to analyze: Duration, Frequency, IO, CPU, or All (default). Use 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 operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | All | | Accepted Values | All,Duration,Frequency,IO,CPU | -Limit Controls how many top resource-consuming query hashes to return for each metric type (default is 20). Increase this value when you need to analyze more queries, or decrease it to focus on only the most problematic queries during initial performance triage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 20 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeSystem Excludes system objects like replication procedures (sp_MS% objects) from the query analysis results. Use this when you want to focus on application queries rather than system maintenance operations that may consume resources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 metric type Ã— 4 metric types). Duration metric results (when -Type includes \"Duration\"): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name Database: The database context where the query executed ObjectName: The stored procedure or object name containing the query (or ' ' for ad-hoc queries) QueryHash: The binary hash identifier for the query TotalElapsedTimeMs: Total elapsed time in milliseconds for this cached query execution plan ExecutionCount: Total number of times this query execution plan was executed AverageDurationMs: Average elapsed time per execution in milliseconds QueryTotalElapsedTimeMs: Total elapsed time for all occurrences of this query hash QueryText: The actual SQL statement text being executed Frequency metric results (when -Type includes \"Frequency\"): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name Database: The database context where the query executed ObjectName: The stored procedure or object name containing the query (or ' ' for ad-hoc queries) QueryHash: The binary hash identifier for the query ExecutionCount: Number of times this query execution plan was executed QueryTotalExecutions: Total execution count for all occurrences of this query hash QueryText: The actual SQL statement text being executed IO metric results (when -Type includes \"IO\"): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name Database: The database context where the query executed ObjectName: The stored procedure or object name containing the query (or ' ' for ad-hoc queries) QueryHash: The binary hash identifier for the query TotalIO: Total logical reads and writes (sum of logical read and write operations) ExecutionCount: Number of times this query execution plan was executed AverageIO: Average IO operations per execution QueryTotalIO: Total IO operations for all occurrences of this query hash QueryText: The actual SQL statement text being executed CPU metric results (when -Type includes \"CPU\"): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name Database: The database context where the query executed ObjectName: The stored procedure or object name containing the query (or ' ' for ad-hoc queries) QueryHash: The binary hash identifier for the query CpuTime: Total worker time in microseconds (CPU time consumed) ExecutionCount: Number of times this query execution plan was executed AverageCpuMs: Average CPU time per execution in milliseconds QueryTotalCpu: Total CPU time for all occurrences of this query hash QueryText: The actual SQL statement text being executed Additional property available with Select-Object :** QueryPlan: The actual execution plan XML (excluded from default display via Select-DefaultView) The -ExcludeSystem parameter filters out system replication procedures (sp_MS%) from all result sets. The -Database and -ExcludeDatabase parameters filter results to specific databases before aggregation. &nbsp;"
  },
  {
    "name": "Get-DbaTrace",
    "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.",
    "category": "Performance",
    "tags": [
      "trace"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaTrace",
    "popularityRank": 370,
    "synopsis": "Retrieves SQL Server trace information including status, file paths, and configuration details",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaTrace View Source Garry Bargsley (@gbargsley), blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server trace information including status, file paths, and configuration details 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. Syntax Get-DbaTrace [-SqlInstance] [[-SqlCredential] ] [[-Id] ] [-Default] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Lists all the trace files on the sql2016 SQL Server PS C:\\> Get-DbaTrace -SqlInstance sql2016 Example 2: Lists the default trace information on the sql2016 SQL Server PS C:\\> Get-DbaTrace -SqlInstance sql2016 -Default Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Id Specifies the trace ID(s) to retrieve information for. Accepts single values or arrays of trace IDs. Use this when you need to check specific traces instead of retrieving all configured traces on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Default Returns only the default system trace (usually trace ID 1) which SQL Server automatically creates for auditing DDL operations. Use this when you need to locate the default trace file for troubleshooting schema changes, login events, or security auditing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: The trace ID number Status: Numeric trace status value (0=stopped, 1=running, 2=closed) IsRunning: Boolean indicating if the trace is currently running Path: The file path where the trace output is stored MaxSize: Maximum size of the trace file in megabytes (0=unlimited) StopTime: DateTime when the trace is scheduled to stop, or null if running indefinitely MaxFiles: Maximum number of rollover files (0=unlimited) IsRowset: Boolean indicating if trace output is written as rowset IsRollover: Boolean indicating if rollover file creation is enabled IsShutdown: Boolean indicating if trace will stop on server shutdown IsDefault: Boolean indicating if this is the default system trace BufferCount: Number of in-memory buffers allocated for the trace BufferSize: Size of each buffer in kilobytes FilePosition: Current file position for trace output ReaderSpid: Server process ID reading the trace (SPID) StartTime: DateTime when the trace was started LastEventTime: DateTime of the most recent trace event EventCount: Number of events captured by the trace DroppedEventCount: Number of events dropped due to buffer limitations The properties RemotePath, Parent, and SqlCredential are also available but excluded from default view. Use Select-Object * to access all properties. &nbsp;"
  },
  {
    "name": "Get-DbaTraceFlag",
    "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.",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "traceflag",
      "dbcc"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaTraceFlag",
    "popularityRank": 432,
    "synopsis": "Retrieves currently enabled global trace flags from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaTraceFlag View Source Kevin Bullen (@sqlpadawan) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves currently enabled global trace flags from SQL Server instances. 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. Syntax Get-DbaTraceFlag [-SqlInstance] [[-SqlCredential] ] [[-TraceFlag] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all Trace Flag information on the local default SQL Server instance PS C:\\> Get-DbaTraceFlag -SqlInstance localhost Example 2: Returns all Trace Flag(s) for the local and sql2016 SQL Server instances PS C:\\> Get-DbaTraceFlag -SqlInstance localhost, sql2016 Example 3: Returns Trace Flag status for TF 4199 and 3205 for the local SQL Server instance if they are enabled PS C:\\> Get-DbaTraceFlag -SqlInstance localhost -TraceFlag 4199,3205 Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need to check the status of specific trace flags rather than reviewing all enabled flags on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 are enabled, nothing is returned. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) TraceFlag: The trace flag number (integer, e.g., 4199, 3205, 1118) Global: Boolean indicating if the trace flag is enabled globally on the server Status: Status value for the trace flag (typically 1 for enabled, 0 for disabled) The property Session (indicating session-level flag status) is available but excluded from default view. Use Select-Object * to access all properties including Session. &nbsp;"
  },
  {
    "name": "Get-DbaUptime",
    "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.",
    "category": "Server Management",
    "tags": [
      "cim",
      "instance",
      "utility"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaUptime",
    "popularityRank": 192,
    "synopsis": "Retrieves uptime information for SQL Server instances and their hosting Windows servers",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaUptime View Source Stuart Moore (@napalmgram), stuart-moore.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves uptime information for SQL Server instances and their hosting Windows servers 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. Syntax Get-DbaUptime [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host... PS C:\\> Get-DbaUptime -SqlInstance SqlBox1\\Instance2 Returns 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 instance on winserver Example 2: Returns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host... PS C:\\> Get-DbaUptime -SqlInstance winserver\\sqlexpress, sql2016 Returns 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 instance on host winserver and the default instance on host sql2016 Example 3: Returns an object with SQL Server start time, uptime as TimeSpan object, uptime as a string, and Windows host... PS C:\\> Get-DbaRegServer -SqlInstance sql2014 | Get-DbaUptime Returns 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 listed in the Central Management Server on sql2014 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Specifies Windows credentials to connect to the hosting server for retrieving Windows boot time and uptime information. Use 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 account that lacks WMI access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance containing uptime information for both SQL Server and its hosting Windows server. Properties: ComputerName: The Windows server computer name (from DNS resolution) InstanceName: The SQL Server instance name SqlServer: The full SQL Server instance name SqlStartTime: DateTime when SQL Server was started (based on tempdb creation date) SqlUptime: TimeSpan object showing SQL Server uptime duration SinceSqlStart: Formatted string of SQL Server uptime as \"X days Y hours Z minutes A seconds\" WindowsBootTime: DateTime when the Windows server was last booted WindowsUptime: TimeSpan object showing Windows server uptime duration SinceWindowsBoot: Formatted string of Windows uptime as \"X days Y hours Z minutes A seconds\" &nbsp;"
  },
  {
    "name": "Get-DbaUserPermission",
    "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.",
    "category": "Utilities",
    "tags": [
      "security",
      "user"
    ],
    "verb": "Get",
    "popular": true,
    "url": "/Get-DbaUserPermission",
    "popularityRank": 39,
    "synopsis": "Audits comprehensive security permissions across SQL Server instances using DISA STIG methodology",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaUserPermission View Source Brandon Abshire, netnerds.net , Josh Smith Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Audits comprehensive security permissions across SQL Server instances using DISA STIG methodology 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. This 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. The 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. Note that if you interrupt this command prematurely (Ctrl-C), it will leave behind a STIG schema in tempdb that should be manually cleaned up. Syntax Get-DbaUserPermission [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-ExcludeSystemDatabase] [-IncludePublicGuest] [-IncludeSystemObjects] [-ExcludeSecurables] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Check server and database permissions for servers sql2008 and sqlserver2012 PS C:\\> Get-DbaUserPermission -SqlInstance sql2008, sqlserver2012 Example 2: Check server and database permissions on server sql2008 for only the TestDB database PS C:\\> Get-DbaUserPermission -SqlInstance sql2008 -Database TestDB Example 3: Check server and database permissions on server sql2008 for only the TestDB database, including public and... PS C:\\> Get-DbaUserPermission -SqlInstance sql2008 -Database TestDB -IncludePublicGuest -IncludeSystemObjects Check server and database permissions on server sql2008 for only the TestDB database, including public and guest grants, and sys schema objects. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to audit for user permissions and role memberships. Accepts multiple database names and supports wildcards. Use this when you need to focus the security audit on specific databases rather than scanning the entire instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during the security audit. Useful for excluding databases that don't require security review. Common scenarios include excluding development databases or databases with known compliant configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemDatabase Excludes system databases (master, model, msdb, tempdb) from the security audit. Focuses the output on user databases only. Use this when compliance requirements only apply to application databases and not SQL Server system databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludePublicGuest Includes permissions granted to the public database role and guest user account in the audit results. Use this for complete security visibility, as public and guest permissions affect all users and can create unintended access paths. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSystemObjects Includes permissions on system schema objects (sys, INFORMATION_SCHEMA) in the audit results. Enable this when security policies require auditing access to metadata views and system functions that could expose sensitive information. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeSecurables Excludes object-level permissions (tables, views, procedures, functions) from the audit and returns only role memberships. Use this for high-level security reviews focused on role-based access rather than granular object permissions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 containing contextual information about the grantor, grantee, and permission state. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Object: The scope of the permission - 'SERVER' for server-level permissions, or the database name for database-level permissions Type: The type of audit row - 'SERVER LOGINS', 'SERVER SECURABLES', 'DB ROLE MEMBERS', or 'DB SECURABLES' Member: The login or principal name (populated for role membership rows only) RoleSecurableClass: The role name for membership records, securable class for permission records, or 'None' SchemaOwner: The schema/owner name for object permissions (empty for role memberships) Securable: The name of the securable object being granted permissions (table, procedure, etc.) - empty for role memberships GranteeType: The type of grantee (USER, ROLE, APPLICATION ROLE) - empty for role memberships Grantee: The principal name that was granted the permission - empty for role memberships Permission: The permission name (SELECT, INSERT, EXECUTE, etc.) - empty for role memberships State: The permission state (GRANT or DENY) - empty for role memberships Grantor: The principal that granted the permission - empty for role memberships GrantorType: The type of grantor (USER, ROLE) - empty for role memberships SourceView: The STIG schema view the data came from - empty for role memberships Note: 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. Object permission records populate all securable-related properties. &nbsp;"
  },
  {
    "name": "Get-DbaWaitingTask",
    "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's 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/",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "waits",
      "task"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWaitingTask",
    "popularityRank": 444,
    "synopsis": "Retrieves detailed information about currently waiting sessions and their wait types from SQL Server dynamic management views.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaWaitingTask View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed information about currently waiting sessions and their wait types from SQL Server dynamic management views. 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's 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. This command is based on the waiting task T-SQL script published by Paul Randal. Reference: https://www.sqlskills.com/blogs/paul/updated-sys-dm_os_waiting_tasks-script-2/ Syntax Get-DbaWaitingTask [-SqlInstance] [[-SqlCredential] ] [[-Spid] ] [-IncludeSystemSpid] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns the waiting task for all sessions on sqlserver2014a PS C:\\> Get-DbaWaitingTask -SqlInstance sqlserver2014a Example 2: Returns the waiting task for all sessions (user and system) on sqlserver2014a PS C:\\> Get-DbaWaitingTask -SqlInstance sqlserver2014a -IncludeSystemSpid Required Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version XXXX or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Spid Filters results to show waiting tasks for specific session IDs only. Accepts one or more SPIDs as an array. Use this when troubleshooting known problematic sessions or when you want to focus on specific user connections instead of scanning all active sessions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -IncludeSystemSpid Includes system sessions (SPIDs) in the results along with user sessions. By default, only user sessions are returned. Enable this when diagnosing system-level performance issues or when system processes might be causing blocking or resource contention. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per waiting session found on the SQL Server instance, with the following default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Spid: The session ID (SPID) of the waiting session Thread: The execution context ID (thread number within the session) Scheduler: The scheduler ID managing this task WaitMs: The duration of the wait in milliseconds WaitType: The type of wait (e.g., CXPACKET, LCK_M_IX, PAGEIOLATCH_SH, etc.) BlockingSpid: The session ID (SPID) blocking this session, or 0 if no blocking *Additional properties available with Select-Object :** ResourceDesc: Detailed resource description from the wait (e.g., database:file:page IDs for page waits) NodeId: For CXPACKET waits, the parallel exchange node ID from ResourceDesc Dop: Degree of Parallelism for parallel execution waits; null for serial execution DbId: Database ID where the wait is occurring SqlText: The SQL text being executed in the waiting session (excluded from default display) QueryPlan: The query execution plan as XML (excluded from default display) InfoUrl: URL to SQLSkills wait type documentation for this specific wait type (excluded from default display) When -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. &nbsp;"
  },
  {
    "name": "Get-DbaWaitResource",
    "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're investigating blocking chains or deadlocks, you see wait_resource values like 'PAGE: 10:1:9180084' or 'KEY: 7:35457594073541168 (de21f92a1572)' in DMVs, but these don't 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.",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "pages",
      "dbcc"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWaitResource",
    "popularityRank": 459,
    "synopsis": "Translates wait resource strings into human-readable database object information for troubleshooting blocking and deadlocks",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaWaitResource View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Translates wait resource strings into human-readable database object information for troubleshooting blocking and deadlocks 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're investigating blocking chains or deadlocks, you see wait_resource values like 'PAGE: 10:1:9180084' or 'KEY: 7:35457594073541168 (de21f92a1572)' in DMVs, but these don't tell you which actual table or index is involved. For 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. This 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. Syntax Get-DbaWaitResource [-SqlInstance] [[-SqlCredential] ] [-WaitResource] [-Row] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Will return an object containing; database name, data file name, schema name and the object which owns the... PS C:\\> Get-DbaWaitResource -SqlInstance server1 -WaitResource 'PAGE: 10:1:9180084' Will return an object containing; database name, data file name, schema name and the object which owns the resource Example 2: Will return an object containing; database name, schema name and index name which is being waited on PS C:\\> Get-DbaWaitResource -SqlInstance server2 -WaitResource 'KEY: 7:35457594073541168 (de21f92a1572)' Example 3: Will return an object containing; database name, schema name and index name which is being waited on, and in... PS C:\\> Get-DbaWaitResource -SqlInstance server2 -WaitResource 'KEY: 7:35457594073541168 (de21f92a1572)' -row Will 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. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -WaitResource Specifies the cryptic wait resource identifier from sys.dm_exec_requests that you need to decode into readable database object information. Accepts PAGE format like 'PAGE: 10:1:9180084' or KEY format like 'KEY: 7:35457594073541168 (de21f92a1572)'. Use this when troubleshooting blocking chains or deadlocks to identify which specific table, index, or page is causing contention. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Row Returns the actual data from the locked row in addition to the object information for KEY wait resources. Provides the specific record values that are causing the lock contention, which helps identify patterns or problematic data. Only works with KEY wait resources and uses NOLOCK hint to retrieve the current row data safely. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Output varies based on the wait resource type specified: PAGE Wait Resources (when WaitResource matches 'PAGE: dbid:fileid:pageid' format): Returns one object with the following properties: DatabaseID: The database ID from the wait resource DatabaseName: The name of the database containing the page DataFileName: The logical name of the data file containing the page DataFilePath: The physical file system path to the data file ObjectID: The internal object ID (table or index) owning the page ObjectName: The name of the table or index that owns the page ObjectSchema: The schema name containing the object ObjectType: The type of object (USER_TABLE, CLUSTERED_INDEX, NONCLUSTERED_INDEX, HEAP, etc.) KEY Wait Resources (when WaitResource matches 'KEY: hobtid (physicallocation)' format): Returns one object with the following properties: DatabaseID: The database ID from the wait resource DatabaseName: The name of the database containing the key SchemaName: The schema name containing the object IndexName: The name of the index or heap being waited on ObjectID: The internal object ID of the table ObjectName: The name of the table that owns the index or heap HobtID: The heap or B-tree ID (allocation unit ID) being waited on When -Row is specified with KEY wait resources: The output is expanded to include the actual data row from the table. The full row contents are returned as properties matching the table's column names. When the row data cannot be retrieved (row was deleted or moved), only the key resource object properties are returned. &nbsp;"
  },
  {
    "name": "Get-DbaWaitStatistic",
    "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's 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/",
    "category": "Performance",
    "tags": [
      "diagnostic",
      "waits",
      "waitstats"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWaitStatistic",
    "popularityRank": 298,
    "synopsis": "Retrieves SQL Server wait statistics for performance analysis and troubleshooting",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaWaitStatistic View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves SQL Server wait statistics for performance analysis and troubleshooting 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's 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. Returns: WaitType Category WaitSeconds ResourceSeconds SignalSeconds WaitCount Percentage AverageWaitSeconds AverageResourceSeconds AverageSignalSeconds URL Reference: https://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/ Syntax Get-DbaWaitStatistic [-SqlInstance] [[-SqlCredential] ] [[-Threshold] ] [-IncludeIgnorable] [[-ExcludeWaitType] ] [[-IncludeWaitType] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Check wait statistics for servers sql2008 and sqlserver2012 PS C:\\> Get-DbaWaitStatistic -SqlInstance sql2008, sqlserver2012 Example 2: Check wait statistics on server sql2008 for thresholds above 98% and include wait stats that are most often... PS C:\\> Get-DbaWaitStatistic -SqlInstance sql2008 -Threshold 98 -IncludeIgnorable Check wait statistics on server sql2008 for thresholds above 98% and include wait stats that are most often, but not always, ignorable Example 3: Shows detailed notes, if available, from Paul&#39;s post PS C:\\> Get-DbaWaitStatistic -SqlInstance sql2008 | Select-Object Example 4: Collects all Wait Statistics (including ignorable waits) on server sql2008 into a Data Table PS C:\\> $output = Get-DbaWaitStatistic -SqlInstance sql2008 -Threshold 100 -IncludeIgnorable | Select-Object | ConvertTo-DbaDataTable Example 5: Displays the output then loads the associated sqlskills website for each result PS C:\\> $output = Get-DbaWaitStatistic -SqlInstance sql2008 PS C:\\> foreach ($row in ($output | Sort-Object -Unique Url)) { Start-Process ($row).Url } Displays the output then loads the associated sqlskills website for each result. Opens one tab per unique URL. Example 6: Gets wait statistics excluding parallelism waits (CXPACKET and CXCONSUMER) in addition to the default... PS C:\\> Get-DbaWaitStatistic -SqlInstance sql2016 -ExcludeWaitType \"CXPACKET\", \"CXCONSUMER\" Gets wait statistics excluding parallelism waits (CXPACKET and CXCONSUMER) in addition to the default ignorable waits. Example 7: Gets wait statistics and ensures BROKER_RECEIVE_WAITFOR is included even though it&#39;s in the default ignorable... PS C:\\> Get-DbaWaitStatistic -SqlInstance sql2016 -IncludeWaitType \"BROKER_RECEIVE_WAITFOR\" Gets wait statistics and ensures BROKER_RECEIVE_WAITFOR is included even though it's in the default ignorable list. Required Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2005 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when you need to see all wait activity or when investigating unusual issues with specific features like mirroring or Availability Groups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeWaitType Additional wait types to exclude beyond the default ignorable list. Provide an array of wait type names (e.g., \"CXPACKET\", \"CXCONSUMER\"). Use this when you want to filter out specific waits that may not be relevant to your analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeWaitType Wait types to always include in results, even if they appear in the ignorable list. Provide an array of wait type names. Use this to ensure specific waits are shown regardless of the -IncludeIgnorable switch setting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 Server wait type. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) WaitType: The name of the SQL Server wait type (e.g., PAGEIOLATCH_EX, LCK_M_IX) Category: The wait category classification (e.g., Buffer IO, Lock, Network IO, CPU, Idle, Memory, etc.) WaitSeconds: Total time in seconds the system has waited on this wait type (decimal) ResourceSeconds: Time in seconds spent waiting for a resource to become available (decimal) SignalSeconds: Time in seconds spent waiting for a signal after acquiring the resource (decimal) WaitCount: Total number of times this wait type has occurred (bigint) Percentage: Percentage of total system wait time consumed by this wait type (0-100, decimal) AverageWaitSeconds: Average time per wait occurrence in seconds (decimal) AverageResourceSeconds: Average resource wait time per occurrence in seconds (decimal) AverageSignalSeconds: Average signal wait time per occurrence in seconds (decimal) URL: Hyperlink to sqlskills.com detailed documentation for this wait type (XML/string) *Additional properties available (use Select-Object ):* Notes: Detailed diagnostic explanation of the wait type and troubleshooting guidance from Paul Randal's methodology (when using Select-Object ) Ignorable: Boolean indicating whether this wait type is typically safe to ignore during troubleshooting (only shown when -IncludeIgnorable is specified) When -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 type. &nbsp;"
  },
  {
    "name": "Get-DbaWindowsLog",
    "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.",
    "category": "Utilities",
    "tags": [
      "logging",
      "os"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWindowsLog",
    "popularityRank": 473,
    "synopsis": "Retrieves and parses SQL Server error log entries from the file system for analysis and troubleshooting",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWindowsLog View Source Drew Furgiuele , Friedrich Weinmann (@FredWeinmann) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves and parses SQL Server error log entries from the file system for analysis and troubleshooting 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. Syntax Get-DbaWindowsLog [[-SqlInstance] ] [[-Start] ] [[-End] ] [[-Credential] ] [[-MaxThreads] ] [[-MaxRemoteThreads] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all lines in the errorlogs that have event number 18456 in them This exists to ignore the Script... PS C:\\> $ErrorLogs = Get-DbaWindowsLog -SqlInstance sql01\\sharepoint PS C:\\> $ErrorLogs | Where-Object ErrorNumber -eq 18456 Returns all lines in the errorlogs that have event number 18456 in them This exists to ignore the Script Analyzer rule for Start-Runspace Optional Parameters -SqlInstance The instance(s) to retrieve the event logs from | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Start Filters log entries to include only those occurring after this timestamp. Defaults to January 1, 1970. Use this to focus on recent issues or events within a specific timeframe when troubleshooting SQL Server problems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Combine with Start parameter to create specific time windows for analyzing SQL Server events during known problem periods. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaxThreads Controls the maximum number of parallel threads used on the local computer for processing multiple SQL instances. Defaults to unlimited. Set a specific limit when processing many instances simultaneously to prevent overwhelming the local system with too many concurrent operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaxRemoteThreads Sets the maximum number of parallel threads executed on each target SQL Server for processing error log files. Defaults to 2. Keep 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 2 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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, SPID, severity, error number, and the log message. Properties: InstanceName: The SQL Server instance name where the log entry originated (format: ComputerName\\InstanceName or ComputerName for default instance) Timestamp: The date and time when the error log entry was recorded (DateTime) Spid: The SQL Server process ID (SPID) associated with the log entry; typically a string value like \"s\", \"sa\", \"sr\" for system processes (string) Severity: The severity level of the error (0-25 numeric scale; 10+ indicates user errors, lower values indicate informational messages, string representation) ErrorNumber: The SQL Server error number; 0 for informational messages, >0 for actual errors (int) State: The error state number providing additional diagnostic context for the error (int) Message: The full text of the error log message (string) Note: 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. Results are always output as log entries are parsed during the remote execution, not held in memory. &nbsp;"
  },
  {
    "name": "Get-DbaWsfcAvailableDisk",
    "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's 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.",
    "category": "Utilities",
    "tags": [
      "wsfc",
      "fci",
      "windowscluster",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWsfcAvailableDisk",
    "popularityRank": 468,
    "synopsis": "Retrieves shared storage disks available for clustering but not yet assigned to a Windows Server Failover Cluster.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWsfcAvailableDisk View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves shared storage disks available for clustering but not yet assigned to a Windows Server Failover Cluster. 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's 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. All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node. Syntax Get-DbaWsfcAvailableDisk [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets available disks from the failover cluster cluster01 PS C:\\> Get-DbaWsfcAvailableDisk -ComputerName cluster01 Optional Parameters -ComputerName Specifies the Windows Server Failover Cluster name or any cluster node name to query for available disks. Use this when you need to check shared storage from a specific cluster, especially when managing multiple clusters or troubleshooting storage visibility across cluster nodes. Accepts multiple values to query several clusters simultaneously. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the cluster using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.Management.Infrastructure.CimInstance#root/MSCluster/MSCluster_AvailableDisk Returns 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. All properties from the MSCluster_AvailableDisk WMI class are returned, including: Properties added via Add-Member: State: Current operational state of the disk ClusterName: Name of the cluster ClusterFqdn: Fully qualified domain name of the cluster Standard WMI properties from MSCluster_AvailableDisk: Name: Label or designation of the disk Id: Unique disk identifier (GUID for virtual disks, GptGuid or Signature for physical disks) Size: Physical disk capacity in bytes Number: Disk number as seen on the host node Status: Operational status (OK, Degraded, Error, etc.) ConnectedNodes: Array of cluster node names that can access the disk Signature: MBR disk signature value GptGuid: GUID for GPT-partitioned disks ScsiPort: SCSI port number ScsiBus: SCSI bus identifier ScsiTargetID: SCSI target identification number ScsiLUN: SCSI logical unit number Node: Name of the node providing the disk information ResourceName: Resource name when adding disk to cluster All properties from the base WMI object are accessible; the function returns the complete object without filtering. &nbsp;"
  },
  {
    "name": "Get-DbaWsfcCluster",
    "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.",
    "category": "Utilities",
    "tags": [
      "wsfc",
      "fci",
      "windowscluster",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWsfcCluster",
    "popularityRank": 118,
    "synopsis": "Retrieves Windows Server Failover Cluster configuration and status information for SQL Server high availability environments.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWsfcCluster View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows Server Failover Cluster configuration and status information for SQL Server high availability environments. 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. DBAs 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. All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node. Syntax Get-DbaWsfcCluster [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets failover cluster information about cluster01 PS C:\\> Get-DbaWsfcCluster -ComputerName cluster01 Example 2: Shows all cluster values, including the ones not shown in the default view PS C:\\> Get-DbaWsfcCluster -ComputerName cluster01 | Select-Object Optional Parameters -ComputerName Specifies the target Windows Server Failover Cluster to query, either by cluster name or individual node name. Use the cluster name when connecting to an active cluster, or specify a node name when the cluster service may be down. Defaults to the local computer if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the cluster using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.Management.Infrastructure.CimInstance#root/MSCluster/MSCluster_Cluster Returns one cluster object per target cluster specified via ComputerName parameter. Each object contains cluster-wide configuration and status information. Default display properties (via Select-DefaultView): Name: The name of the cluster Fqdn: Fully qualified domain name of the cluster State: Current operational state of the cluster (added via NoteProperty) DrainOnShutdown: Boolean indicating if nodes drain resources during service shutdown (uint32) DynamicQuorumEnabled: Boolean indicating if dynamic quorum adjustment is enabled (uint32) EnableSharedVolumes: Boolean indicating if Cluster Shared Volumes feature is enabled (uint32) SharedVolumesRoot: The root directory path for Cluster Shared Volumes QuorumPath: File system path where quorum files are maintained QuorumType: Current quorum type as a string (Majority Node Majority, Node and Disk Majority, No Majority - Disk Only, Node Majority, or Witness) QuorumTypeValue: Numeric identifier representing the quorum type (uint32) RequestReplyTimeout: Timeout period in milliseconds for request-reply operations (uint32) Additional properties from MSCluster_Cluster WMI class (accessible via Select-Object ):* Caption: Short text description of the cluster Description: Detailed cluster description InstallDate: DateTime when the cluster was installed Status: Cluster operational status string AddEvictDelay: Seconds between node eviction and new node admission AdminAccessPoint: Type of cluster administrative access point BackupInProgress: Indicates if cluster backup is running ClusterEnforcedAntiAffinity: Hard enforcement status of group anti-affinity ClusterFunctionalLevel: Current cluster functional level ClusterLogLevel: Cluster logging verbosity level ClusterLogSize: Maximum log file size per node ClusSvcHangTimeout: Heartbeat timeout before node considered hung CrossSiteDelay: Heartbeat delay between sites in milliseconds CrossSiteThreshold: Missed heartbeats before cross-site failure detected CrossSubnetDelay: Heartbeat delay between subnets in milliseconds CrossSubnetThreshold: Missed heartbeats before cross-subnet failure detected CsvBalancer: Automatic CSV balancing enabled status GracePeriodEnabled: Node grace period feature status GracePeriodTimeout: Grace period timeout in milliseconds IgnorePersistentStateOnStartup: Whether cluster brings online previously running groups MaxNumberOfNodes: Maximum nodes allowed in cluster NetftIPSecEnabled: IPSec security for internal cluster traffic PrimaryOwnerName: Primary cluster owner name PrimaryOwnerContact: Primary owner contact information S2DEnabled: Storage Spaces Direct feature enablement SameSubnetDelay: Heartbeat delay on same subnet in milliseconds SameSubnetThreshold: Missed heartbeats on same subnet before failure detected SharedVolumeCompatibleFilters: Filters compatible with direct I/O SharedVolumeIncompatibleFilters: Filters that prevent direct I/O usage S2DCacheBehavior, S2DCacheDeviceModel, S2DIOLatencyThreshold: Storage Spaces Direct configuration options WitnessDynamicWeight: Configured witness weight for quorum calculations All other properties defined in the MSCluster_Cluster WMI class All 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. &nbsp;"
  },
  {
    "name": "Get-DbaWsfcDisk",
    "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.",
    "category": "Utilities",
    "tags": [
      "wsfc",
      "fci",
      "windowscluster",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWsfcDisk",
    "popularityRank": 530,
    "synopsis": "Retrieves detailed information about clustered physical disks from Windows Server Failover Clusters.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWsfcDisk View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed information about clustered physical disks from Windows Server Failover Clusters. 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. All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node. Syntax Get-DbaWsfcDisk [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets disk information from the failover cluster cluster01 PS C:\\> Get-DbaWsfcDisk -ComputerName cluster01 Optional Parameters -ComputerName Specifies the Windows Server Failover Cluster to query for disk information. Accepts either a cluster node name or the cluster name itself. Use this when managing SQL Server Failover Cluster Instances to monitor storage across different cluster environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the cluster using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per clustered disk partition found on the failover cluster. Default display properties (via Select-DefaultView): ClusterName: The name of the Windows Server Failover Cluster ClusterFqdn: The fully qualified domain name of the cluster ResourceGroup: The owner group of the disk resource Disk: The disk resource name State: The current state of the disk resource FileSystem: The file system type (NTFS, ReFS, etc.) Path: The mount path of the disk partition Label: The volume label assigned to the disk Size: Total size of the disk partition; dbasize object convertible to Bytes, KB, MB, GB, TB Free: Free space available on the disk partition; dbasize object with unit conversion SerialNumber: The serial number of the physical disk *Additional properties available (using Select-Object ):** MountPoints: Array of mount points for the disk partition ClusterDisk: The CIM MSCluster_Disk object representing the physical disk ClusterDiskPart: The CIM MSCluster_DiskPartition object with full partition metadata ClusterResource: The CIM MSCluster_Resource object representing the cluster resource &nbsp;"
  },
  {
    "name": "Get-DbaWsfcNetwork",
    "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.",
    "category": "Utilities",
    "tags": [
      "wsfc",
      "fci",
      "windowscluster",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWsfcNetwork",
    "popularityRank": 509,
    "synopsis": "Retrieves network configuration details from Windows Server Failover Clustering for SQL Server high availability troubleshooting.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWsfcNetwork View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves network configuration details from Windows Server Failover Clustering for SQL Server high availability troubleshooting. 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. All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node. Syntax Get-DbaWsfcNetwork [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets network information from the failover cluster cluster01 PS C:\\> Get-DbaWsfcNetwork -ComputerName cluster01 Optional Parameters -ComputerName Specifies the Windows Server Failover Cluster name or any cluster node name to retrieve network configuration from. Use this to target a specific cluster when troubleshooting network connectivity issues with SQL Server FCIs or Availability Groups. Accepts multiple cluster names for bulk network configuration analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the cluster using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per cluster network found on the Windows Server Failover Cluster. Properties: ClusterName: The name of the Windows Server Failover Cluster ClusterFqdn: The fully qualified domain name of the cluster Name: The network name within the cluster configuration Address: The network address (IP address or network identifier) AddressMask: The subnet mask or network address mask IPv4Addresses: Array of IPv4 addresses assigned to this cluster network IPv4PrefixLengths: Array of IPv4 prefix lengths corresponding to IPv4Addresses IPv6Addresses: Array of IPv6 addresses assigned to this cluster network IPv6PrefixLengths: Array of IPv6 prefix lengths corresponding to IPv6Addresses QuorumType: The quorum type indicator (numeric value) QuorumTypeValue: The quorum type value representation RequestReplyTimeout: The request/reply timeout value in milliseconds Role: The role of the network in the cluster (cluster, client, etc.) &nbsp;"
  },
  {
    "name": "Get-DbaWsfcNetworkInterface",
    "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.",
    "category": "Utilities",
    "tags": [
      "wsfc",
      "fci",
      "windowscluster",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWsfcNetworkInterface",
    "popularityRank": 620,
    "synopsis": "Retrieves network interface configuration from Windows Server Failover Cluster nodes.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWsfcNetworkInterface View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves network interface configuration from Windows Server Failover Cluster nodes. 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. Use 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. All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node. Syntax Get-DbaWsfcNetworkInterface [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets network interface information from the failover cluster cluster01 PS C:\\> Get-DbaWsfcNetworkInterface -ComputerName cluster01 Example 2: Shows all network interface values, including the ones not shown in the default view PS C:\\> Get-DbaWsfcNetworkInterface -ComputerName cluster01 | Select-Object Optional Parameters -ComputerName Specifies the Windows Server Failover Cluster name or any cluster node name to query for network interface information. Use this when troubleshooting SQL Server FCI connectivity issues or documenting cluster network topology. Accepts cluster names, node names, or IP addresses of cluster resources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the cluster using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Management.ManagementObject Returns one network interface object per adapter found on cluster nodes queried. Each object represents a network interface configuration with IP address and DHCP settings. Default display properties (via Select-DefaultView): ClusterName: The name of the Windows Server Failover Cluster ClusterFqdn: The fully qualified domain name of the cluster Name: The name of the network interface Network: The name or identifier of the network this interface belongs to Node: The name of the cluster node this interface is assigned to Adapter: The network adapter identifier or friendly name Address: The IP address assigned to this interface DhcpEnabled: Boolean indicating if DHCP is enabled for this interface IPv4Addresses: String array of IPv4 addresses configured on this interface IPv6Addresses: String array of IPv6 addresses configured on this interface Additional properties available via Select-Object :** All properties from the MSCluster_NetworkInterface WMI class, including network role, state, and adapter-level details. &nbsp;"
  },
  {
    "name": "Get-DbaWsfcNode",
    "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.",
    "category": "Utilities",
    "tags": [
      "wsfc",
      "fci",
      "windowscluster",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWsfcNode",
    "popularityRank": 251,
    "synopsis": "Retrieves detailed node information from Windows Server Failover Clusters hosting SQL Server instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWsfcNode View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed node information from Windows Server Failover Clusters hosting SQL Server instances. 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. DBAs 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. All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node. Syntax Get-DbaWsfcNode [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets node information from the failover cluster cluster01 PS C:\\> Get-DbaWsfcNode -ComputerName cluster01 Example 2: Shows all node values, including the ones not shown in the default view PS C:\\> Get-DbaWsfcNode -ComputerName cluster01 | Select-Object Optional Parameters -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. Use this when you need to connect to a specific cluster hosting SQL Server FCIs or Availability Groups to retrieve node details. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the cluster using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Management.ManagementObject Returns one node object per cluster member node queried. Each object represents a cluster node with ownership and version information. Default display properties (via Select-DefaultView): ClusterName: The name of the Windows Server Failover Cluster ClusterFqdn: The fully qualified domain name of the cluster Name: The name of the cluster node (server name) PrimaryOwnerName: The primary owner of the node resource PrimaryOwnerContact: Contact information for the primary owner Dedicated: Boolean indicating if the node is dedicated to clustering NodeHighestVersion: The highest cluster API version supported by this node NodeLowestVersion: The lowest cluster API version supported by this node Additional properties available via Select-Object :** All properties from the MSCluster_Node WMI class, including node state, resource ownership, and cluster communication details. &nbsp;"
  },
  {
    "name": "Get-DbaWsfcResource",
    "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't 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.",
    "category": "Utilities",
    "tags": [
      "wsfc",
      "fci",
      "windowscluster",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWsfcResource",
    "popularityRank": 374,
    "synopsis": "Retrieves detailed information about cluster resources in a Windows Server Failover Cluster",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWsfcResource View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves detailed information about cluster resources in a Windows Server Failover Cluster 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. Use this when diagnosing cluster resource failures, planning maintenance windows, or investigating why SQL Server services aren't failing over properly. The state information helps identify stuck resources, while ownership details show which node currently hosts each resource. All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node. Syntax Get-DbaWsfcResource [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets resource information from the failover cluster cluster01 PS C:\\> Get-DbaWsfcResource -ComputerName cluster01 Example 2: Shows all resource values, including the ones not shown in the default view PS C:\\> Get-DbaWsfcResource -ComputerName cluster01 | Select-Object Optional Parameters -ComputerName Specifies the target cluster to query for resource information. Can be any cluster node name or the cluster name itself. Use this when managing multiple clusters or when connecting from outside the cluster to gather resource status and configuration details. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the cluster using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs MSCluster_Resource (with added NoteProperties) Returns 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 instance, or network name. Default display properties (via Select-DefaultView): ClusterName: The name of the Windows Server Failover Cluster ClusterFqdn: The fully qualified domain name of the cluster Name: The resource name State: Current operational status of the resource (Online, Offline, Failed, Initializing, Pending, Unknown, etc.) Type: The resource type (e.g., \"Physical Disk\", \"IP Address\", \"Network Name\") OwnerGroup: The resource group this resource belongs to OwnerNode: The cluster node currently hosting this resource PendingTimeout: Timeout in milliseconds for bringing resource online/offline (typically 180000 ms / 3 minutes) PersistentState: Boolean indicating whether resource should be online when Cluster Service starts QuorumCapable: Boolean indicating if the resource can be selected as quorum resource RequiredDependencyClasses: Array of resource classes this resource depends on RequiredDependencyTypes: Array of resource types that are required dependencies RestartAction: Action on failure - Do Not Restart (0), Restart Without Failover (1), Restart With Failover (2) RestartDelay: Time delay in milliseconds before restart attempt RestartPeriod: Interval in milliseconds for restart attempt tracking RestartThreshold: Maximum number of restart attempts within RestartPeriod RetryPeriodOnFailure: Interval in milliseconds before retrying a failed resource SeparateMonitor: Boolean indicating if resource requires isolated Resource Monitor process Additional properties available (WMI MSCluster_Resource object): Id: Unique identifier for the resource CoreResource: Boolean indicating if resource is essential to cluster IsAlivePollInterval: Polling interval in milliseconds for operational checks LooksAlivePollInterval: Polling interval in milliseconds for appearance checks DeadlockTimeout: Timeout in milliseconds for deadlock detection Status: Status message string (e.g., \"OK\", \"Error\", \"Degraded\") ResourceSpecificStatus: Resource-specific status information IsClusterSharedVolume: Boolean indicating if resource is a cluster shared volume MonitorProcessId: Process ID of resource monitor managing this resource Characteristics: Resource characteristics flags Flags: Resource configuration flags InstallDate: DateTime when resource was installed Caption: Short description of the resource CryptoCheckpoints: Array of encrypted checkpoints for resource backup/restore RegistryCheckpoints: Array of registry checkpoints for resource backup/restore LocalQuorumCapable: Boolean indicating if usable as quorum in local quorum clusters ResourceClass: Classification (Storage, Network, User) All properties from the WMI MSCluster_Resource class are accessible using Select-Object . &nbsp;"
  },
  {
    "name": "Get-DbaWsfcResourceGroup",
    "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.",
    "category": "Utilities",
    "tags": [
      "wsfc",
      "fci",
      "windowscluster",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWsfcResourceGroup",
    "popularityRank": 678,
    "synopsis": "Retrieves Windows Server Failover Cluster resource group status and ownership information",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWsfcResourceGroup View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows Server Failover Cluster resource group status and ownership information 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. Use 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. All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node. Syntax Get-DbaWsfcResourceGroup [[-ComputerName] ] [[-Credential] ] [[-Name] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets resource group information from the failover cluster cluster01 PS C:\\> Get-DbaWsfcResourceGroup -ComputerName cluster01 Example 2: Shows all resource values, including the ones not shown in the default view PS C:\\> Get-DbaWsfcResourceGroup -ComputerName cluster01 | Select-Object Optional Parameters -ComputerName Specifies the target Windows Server Failover Cluster to query, either as a cluster name or any node name within the cluster. Use this when connecting to specific failover clusters hosting SQL Server FCI or Availability Group resources. Defaults to the local computer if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the cluster using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Filters results to only include resource groups with the specified names. Supports multiple values. Use this when you need to check specific SQL Server resource groups like 'SQL Server (MSSQLSERVER)' or named Availability Groups. Omit this parameter to retrieve all resource groups in the cluster. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.Management.Infrastructure.CimInstance#root/MSCluster/MSCluster_ResourceGroup Returns one resource group object per resource group found on the specified Windows Server Failover Cluster. Default display properties (via Select-DefaultView): ClusterName: The name of the Windows Server Failover Cluster ClusterFqdn: The fully qualified domain name of the cluster Name: The name of the resource group State: Current resource group state (Online, Offline, Failed, or Unknown) PersistentState: The desired persistent state of the resource group OwnerNode: The cluster node that currently owns this resource group Additional properties available from WMI MSCluster_ResourceGroup object (via Select-Object ):** Characteristics: Resource group characteristics bitmask CreationTime: DateTime when the resource group was created Description: Text description of the resource group Flags: Resource group flags GroupType: Type of resource group PrivateProperties: Collection of private property objects ResourceType: The resource type of this group StateInfo: Detailed state information Topology: Cluster topology information &nbsp;"
  },
  {
    "name": "Get-DbaWsfcResourceType",
    "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.",
    "category": "Utilities",
    "tags": [
      "wsfc",
      "fci",
      "windowscluster",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWsfcResourceType",
    "popularityRank": 565,
    "synopsis": "Retrieves available resource types from Windows Server Failover Cluster for SQL Server FCI configuration.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWsfcResourceType View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves available resource types from Windows Server Failover Cluster for SQL Server FCI configuration. 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. Returns 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. All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node. Syntax Get-DbaWsfcResourceType [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets resource type information from the failover cluster cluster01 PS C:\\> Get-DbaWsfcResourceType -ComputerName cluster01 Optional Parameters -ComputerName Specifies the target Windows Server Failover Cluster by providing either a cluster node name or the cluster name itself. Use this when connecting to a specific cluster to retrieve its available resource types for SQL Server FCI planning or troubleshooting. Defaults to the local computer name if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the cluster using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.Management.Infrastructure.CimInstance#root/MSCluster/MSCluster_ResourceType Returns 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 Server instances, network names, and shared storage. Default display properties (via Select-DefaultView): ClusterName: Name of the cluster containing this resource type ClusterFqdn: Fully qualified domain name of the cluster Name: Name of the resource type (key property) DisplayName: Displayed name for the resource type shown in user interfaces DllName: File name of the dynamic-link library that implements the resource type RequiredDependencyTypes: Array of resource type names that resources of this type must depend on (Windows Server 2012+) Additional properties available (from WMI MSCluster_ResourceType object): Caption: Short textual description of the resource type Description: Detailed description of the resource type Characteristics: Bit flags defining resource type characteristics Flags: Resource type flags ResourceClass: Classification of resource type (Storage, Network, User, Unknown) QuorumCapable: Boolean indicating if resource can be selected as quorum resource IsAlivePollInterval: Recommended poll interval in milliseconds for liveness checks LooksAlivePollInterval: Recommended poll interval in milliseconds for operational status checks DeadlockTimeout: Milliseconds before declaring a deadlock in resource calls PendingTimeout: Milliseconds before forcibly terminating unresponsive resources AdminExtensions: Class identifiers for Cluster Administrator extension DLLs Status: Current operational status of the resource type All properties from the WMI MSCluster_ResourceType object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaWsfcRole",
    "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.",
    "category": "Utilities",
    "tags": [
      "wsfc",
      "fci",
      "windowscluster",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWsfcRole",
    "popularityRank": 322,
    "synopsis": "Retrieves Windows Server Failover Cluster role status and ownership information for SQL Server monitoring",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWsfcRole View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Windows Server Failover Cluster role status and ownership information for SQL Server monitoring 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. Use 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. All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node. Syntax Get-DbaWsfcRole [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets role information from the failover cluster cluster01 PS C:\\> Get-DbaWsfcRole -ComputerName cluster01 Example 2: Shows all role values, including the ones not shown in the default view PS C:\\> Get-DbaWsfcRole -ComputerName cluster01 | Select-Object Optional Parameters -ComputerName Specifies the cluster node name or cluster name to connect to for retrieving role information. Accepts multiple values for querying multiple clusters. Use this when you need to check role status on remote clusters or when working with multiple cluster environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the cluster using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.Management.Infrastructure.CimInstance#root/MSCluster/MSCluster_ResourceGroup Returns 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 a single unit. Default display properties (via Select-DefaultView): ClusterName: Name of the cluster containing this role ClusterFqdn: Fully qualified domain name of the cluster Name: Name of the resource group (key property), typically the cluster role name (e.g., SQL Server instance name) OwnerNode: Name of the node currently hosting this resource group State: Current state of the resource group translated to readable format (Online, Offline, Failed, Partial Online, Pending, or Unknown) Additional properties available (from WMI MSCluster_ResourceGroup object): Caption: Short textual description of the resource group Description: Detailed comments about the resource group Id: Network identifier for the group Status: Current status string (OK, Error, Degraded, Unknown, etc.) InstallDate: DateTime when the group was created Characteristics: Bit flags defining group characteristics Flags: Flags set for the group DefaultOwner: Node number where group was last activated or moved (node preferences) AutoFailbackType: Whether automatic failback to preferred owner is enabled (0=Prevent, 1=Allow) FailbackWindowStart: Earliest hour (local cluster time) group can move back to preferred node (-1 to 23) FailbackWindowEnd: Latest hour group can move back to preferred node (-1 to 23) FailoverPeriod: Hours during which failover threshold applies (1-1193 hours) FailoverThreshold: Maximum number of failover attempts allowed within FailoverPeriod PersistentState: Whether group stays offline or comes online when Cluster service starts Priority: Priority value for the resource group (0-4999) AntiAffinityClassNames: Groups that should not be hosted on the same cluster node GroupType: Type of resource group (cluster, SQL Server instance, file server, virtual machine, etc.) IsCore: Boolean indicating if group is essential cluster group that cannot be deleted CCFEpoch: Current CCF (Cluster Configuration Fence) of the resource group (Windows Server 2016+) ResiliencyPeriod: Resiliency period in seconds (Windows Server 2016+) All 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 current cluster state. &nbsp;"
  },
  {
    "name": "Get-DbaWsfcSharedVolume",
    "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.",
    "category": "Utilities",
    "tags": [
      "wsfc",
      "fci",
      "windowscluster",
      "ha"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaWsfcSharedVolume",
    "popularityRank": 576,
    "synopsis": "Retrieves Cluster Shared Volume configuration and status from Windows Server Failover Clusters hosting SQL Server instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Get-DbaWsfcSharedVolume View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Cluster Shared Volume configuration and status from Windows Server Failover Clusters hosting SQL Server instances. 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. DBAs 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. All Windows Server Failover Clustering (Wsfc) commands require local admin on each member node. Syntax Get-DbaWsfcSharedVolume [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets shared volume (CSV) information from the failover cluster cluster01 PS C:\\> Get-DbaWsfcSharedVolume -ComputerName cluster01 Optional Parameters -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the cluster using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Management.ManagementObject Returns one ClusterSharedVolume WMI object per shared volume found on the cluster, with three added NoteProperties providing cluster context. Default display properties (ClusterSharedVolume WMI class properties plus): ClusterName: Name of the Windows Server Failover Cluster ClusterFqdn: Fully qualified domain name of the failover cluster State: Current state of the cluster shared volume (Online, Offline, Failed, etc.), converted from numeric value All properties from the underlying ClusterSharedVolume WMI class are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaXEObject",
    "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.",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaXEObject",
    "popularityRank": 554,
    "synopsis": "Retrieves Extended Events objects available for monitoring and troubleshooting on SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaXEObject View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Extended Events objects available for monitoring and troubleshooting on SQL Server instances. 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. Syntax Get-DbaXEObject [-SqlInstance] [[-SqlCredential] ] [[-Type] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Lists all the XE Objects on the sql2016 SQL Server PS C:\\> Get-DbaXEObject -SqlInstance sql2016 Example 2: Lists all the XE Objects of type Action and Event on the sql2017 SQL Server PS C:\\> Get-DbaXEObject -SqlInstance sql2017 -Type Action, Event Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Filters the Extended Events objects by specific component types to help you find the XE building blocks you need. Use this when planning XE sessions to focus on specific components rather than viewing all available objects. Events capture SQL Server activities, Actions attach additional data to events, Targets define where to store captured data, and Predicates filter which events to capture. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Default display properties (excludes ComputerName, InstanceName, ObjectTypeRaw): PackageName: Name of the Extended Events package (e.g., 'package0', 'sqlserver') ObjectType: Type of XE object (Event, Action, Target, Map, Message, Type, PredicateComparator, PredicateSource) TargetName: Name of the Extended Events object Description: Description of what the XE object does *All properties available when using Select-Object :** ComputerName: The computer name hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: Full SQL Server instance name (computer\\instance format) PackageName: Name of the Extended Events package ObjectType: Friendly-formatted object type ObjectTypeRaw: Raw database value ('type', 'event', 'target', 'pred_compare', 'pred_source', 'action', 'map', 'message') TargetName: Name of the Extended Events object Description: Description of the XE object Use the -Type parameter to filter results to specific component types without changing the output structure. &nbsp;"
  },
  {
    "name": "Get-DbaXESession",
    "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's 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.",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaXESession",
    "popularityRank": 366,
    "synopsis": "Retrieves Extended Events sessions with detailed configuration and status information from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaXESession View Source Klaas Vandenberghe (@PowerDBAKlaas) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Extended Events sessions with detailed configuration and status information from SQL Server 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's 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. Syntax Get-DbaXESession [-SqlInstance] [[-SqlCredential] ] [[-Session] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a custom object with ComputerName, SQLInstance, Session, StartTime, Status and other properties PS C:\\> Get-DbaXESession -SqlInstance ServerA\\sql987 Example 2: Returns a formatted table displaying ComputerName, SqlInstance, Session, and Status PS C:\\> Get-DbaXESession -SqlInstance ServerA\\sql987 | Format-Table ComputerName, SqlInstance, Session, Status -AutoSize Example 3: Returns a custom object with ComputerName, SqlInstance, Session, StartTime, Status and other properties, from... PS C:\\> 'ServerA\\sql987','ServerB' | Get-DbaXESession Returns a custom object with ComputerName, SqlInstance, Session, StartTime, Status and other properties, from multiple SQL instances. Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Session Filters results to specific Extended Events sessions by name. Accepts multiple session names as an array. Use this when you need to check status or configuration of particular sessions rather than viewing all XE sessions on the instance. | Property | Value | | --- | --- | | Alias | Sessions | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.XEvent.Session Returns one Session object per Extended Events session found on the specified SQL Server instance(s). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the Extended Events session Status: Current session status - either \"Running\" or \"Stopped\" StartTime: DateTime when the session was started (null if stopped) AutoStart: Boolean indicating if the session starts automatically when SQL Server starts State: SMO object state (Existing, Creating, Pending, etc.) Targets: Collection of target objects configured for this session TargetFile: Array of resolved file paths for all event_file targets (includes UNC paths for network access) Events: Collection of Extended Events configured in this session MaxMemory: Maximum memory allocation for the session in KB MaxEventSize: Maximum event size the session will capture in KB Additional properties added as NoteProperties: Session: The session name (alias for Name property) RemoteTargetFile: Array of UNC paths for all target files (for remote file access) Parent: Reference to the parent Microsoft.SqlServer.Management.Smo.Server object Store: Reference to the Microsoft.SqlServer.Management.XEvent.XEStore object *Additional properties available from SMO Session object (via Select-Object ):** ID: Unique identifier for the session EventRetentionMode: Event retention behavior setting MaxDispatchLatency: Maximum dispatch latency in seconds MemoryPartitionMode: Memory partitioning strategy TrackCausality: Boolean indicating if causality tracking is enabled IdentityKey: Identity key of the session object &nbsp;"
  },
  {
    "name": "Get-DbaXESessionTarget",
    "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't capturing data as expected.",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaXESessionTarget",
    "popularityRank": 606,
    "synopsis": "Retrieves Extended Events session targets with their configurations and file locations.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaXESessionTarget View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves Extended Events session targets with their configurations and file locations. 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't capturing data as expected. Syntax Get-DbaXESessionTarget [-SqlCredential ] [-Session ] [-Target ] [-EnableException] [ ] Get-DbaXESessionTarget -SqlInstance [-SqlCredential ] [-Session ] [-Target ] [-EnableException] [ ] Get-DbaXESessionTarget [-SqlCredential ] [-Session ] [-Target ] -InputObject [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Shows targets for the system_health session on ServerA\\sql987 PS C:\\> Get-DbaXESessionTarget -SqlInstance ServerA\\sql987 -Session system_health Example 2: Returns the targets for the system_health session on sql2016 PS C:\\> Get-DbaXESession -SqlInstance sql2016 -Session system_health | Get-DbaXESessionTarget Example 3: Return only the package0.event_file target for the system_health session on sql2016 PS C:\\> Get-DbaXESession -SqlInstance sql2016 -Session system_health | Get-DbaXESessionTarget -Target package0.event_file Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -InputObject Accepts Extended Events session objects from Get-DbaXESession through the pipeline. Allows chaining commands for more complex filtering. Use this when you've already retrieved specific XE sessions and want to examine their targets without re-querying the server. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Session Filters results to specific Extended Events sessions by name. Supports wildcards and multiple session names. Use this when you only need target information from particular XE sessions instead of all sessions on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Target Filters results to specific target types such as 'event_file', 'ring_buffer', or 'event_counter'. Supports multiple target names. Use this when you need information about particular target types, like finding all file-based targets or checking ring buffer configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.XEvent.Target Returns 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 buffers, event counters, etc.). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Session: The name of the Extended Events session containing this target SessionStatus: Current session status - either \"Running\" or \"Stopped\" Name: The target type/name (e.g., 'package0.event_file', 'package0.ring_buffer') ID: Unique identifier for this target within the session Field: Collection of target field configuration parameters PackageName: The Extended Events package name that provides this target type (usually 'package0') File: Array of resolved file paths for file-based targets (includes UNC paths for network access) Description: Description of the target type and its purpose ScriptName: The target name formatted for scripting purposes Additional properties added as NoteProperties: TargetFile: Array of resolved file paths for this target (local paths) RemoteTargetFile: Array of UNC paths for this target (for remote file access) *Additional properties available from SMO Target object (via Select-Object ):** TargetFields: Collection containing detailed configuration parameters for the target State: SMO object state (Existing, Creating, Pending, etc.) Urn: Unified Resource Name for the target object IdentityKey: Identity key of the target object KeyChain: Identity path of the object ModuleID: Module identifier for the target Parent: Reference to parent Session object Properties: Collection of property objects for this target &nbsp;"
  },
  {
    "name": "Get-DbaXESessionTargetFile",
    "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.\n\nFor remote SQL Server instances, this function accesses files via Windows admin shares (e.g. \\\\server\\C$\\...) by performing a Get-ChildItem against the resolved UNC path. This is Windows-only and does not work with Linux-hosted SQL Server or Docker containers.\n\nImportant: SqlCredential alone is not sufficient for remote access. The PowerShell session must be running as a Windows account with read access to the target files on the SQL Server host (typically a local administrator). If access is denied, you will see an error like \"Access to the path '\\\\server\\C$\\...' is denied.\"",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaXESessionTargetFile",
    "popularityRank": 561,
    "synopsis": "Retrieves physical Extended Events target files from the file system for analysis and troubleshooting.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaXESessionTargetFile View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves physical Extended Events target files from the file system for analysis and troubleshooting. 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. For remote SQL Server instances, this function accesses files via Windows admin shares (e.g. \\\\server\\C$\\...) by performing a Get-ChildItem against the resolved UNC path. This is Windows-only and does not work with Linux-hosted SQL Server or Docker containers. Important: SqlCredential alone is not sufficient for remote access. The PowerShell session must be running as a Windows account with read access to the target files on the SQL Server host (typically a local administrator). If access is denied, you will see an error like \"Access to the path '\\\\server\\C$\\...' is denied.\" Syntax Get-DbaXESessionTargetFile [-SqlCredential ] [-Session ] [-Target ] [-EnableException] [ ] Get-DbaXESessionTargetFile -SqlInstance [-SqlCredential ] [-Session ] [-Target ] [-EnableException] [ ] Get-DbaXESessionTargetFile [-SqlCredential ] [-Session ] [-Target ] -InputObject [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Shows Target Files for the &#39;Long Running Queries&#39; session on sql2017 PS C:\\> Get-DbaXESessionTargetFile -SqlInstance sql2017 -Session 'Long Running Queries' Example 2: Returns the target files for the &#39;Long Running Queries&#39; session on sql2016 PS C:\\> Get-DbaXESession -SqlInstance sql2016 -Session 'Long Running Queries' | Get-DbaXESessionTarget | Get-DbaXESessionTargetFile Example 3: Reads XEvents from a named session without knowing the file path in advance PS C:\\> Get-DbaXESession -SqlInstance sql2019 -Session deadlocks | Get-DbaXESessionTarget | Get-DbaXESessionTargetFile | Read-DbaXEFile Reads XEvents from a named session without knowing the file path in advance. This full pipeline resolves the session to its physical .xel files and reads them. Requires the PowerShell session to be running as a Windows account with read access to the target files on the SQL Server host. If the session is still running, stop it first to force a rollover so the latest events are flushed to disk. Required Parameters -SqlInstance The target SQL Server | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -InputObject Accepts Extended Events target objects piped from Get-DbaXESessionTarget for processing their associated target files. Use this when you want to chain commands to first get specific targets and then retrieve their corresponding physical files on the file system. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Session Specifies the Extended Events session name to retrieve target files from. Filters results to only include files generated by the specified session. Use this when you want to focus on files from a specific XE session like 'system_health' or custom monitoring sessions rather than all sessions on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when a session has multiple targets and you only need files from specific targets like 'event_file' or custom target configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns 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. Properties: Name: The file name with extension (e.g., system_health_0_130000000000000000.xel) FullName: The complete file path including directory DirectoryName: The directory path containing the file Length: File size in bytes LastWriteTime: DateTime when the file was last modified CreationTime: DateTime when the file was created Attributes: File attributes (e.g., Archive, Compressed) Directory: DirectoryInfo object for the parent directory Extension: The file extension (.xel or .xem) All properties from the standard PowerShell FileInfo object are available and can be accessed with Select-Object *. &nbsp;"
  },
  {
    "name": "Get-DbaXESessionTemplate",
    "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's 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's Templates that come with SSMS\nJes Borland's \"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's 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",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaXESessionTemplate",
    "popularityRank": 619,
    "synopsis": "Retrieves metadata from Extended Event session templates to help you discover and select pre-built monitoring solutions.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaXESessionTemplate View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves metadata from Extended Event session templates to help you discover and select pre-built monitoring solutions. 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. Use 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's particularly helpful for discovering templates that monitor specific areas like performance, deadlocks, or security events. The 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. The default repository contains templates from: Microsoft's Templates that come with SSMS Jes Borland's \"Everyday Extended Events\" presentation and GitHub repository (https://github.com/grrlgeek/extended-events) Christian Grafe (@ChrGraefe) XE Repo: https://github.com/chrgraefe/sqlscripts/blob/master/XE-Events/ Erin Stellato's Blog: https://www.sqlskills.com/blogs/erin/ Some profile templates converted using: sp_SQLskills_ConvertTraceToExtendedEvents.sql Jonathan M. Kehayias, SQLskills.com http://sqlskills.com/blogs/jonathan Syntax Get-DbaXESessionTemplate [[-Path] ] [[-Pattern] ] [[-Template] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns information about all the templates in the local dbatools repository PS C:\\> Get-DbaXESessionTemplate Example 2: Allows you to select a Session template, then import it to the specified instance and start the session PS C:\\> Get-DbaXESessionTemplate | Out-GridView -PassThru | Import-DbaXESessionTemplate -SqlInstance sql2017 | Start-DbaXESession Example 3: Returns information about all the templates in your local XEventTemplates repository PS C:\\> Get-DbaXESessionTemplate -Path \"$home\\Documents\\SQL Server Management Studio\\Templates\\XEventTemplates\" Example 4: Returns information about all the templates that match the word &quot;duration&quot; in the title, category or body PS C:\\> Get-DbaXESessionTemplate -Pattern duration Example 5: Returns more information about the template, including the full path/filename PS C:\\> Get-DbaXESessionTemplate | Select-Object Optional Parameters -Path Specifies the directory path containing Extended Event template XML files. Defaults to the built-in dbatools template repository. Use this when you want to browse custom or additional templates stored in your own directory instead of the default collection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \"$script:PSModuleRoot\\bin\\XEtemplates\" | -Pattern Filters templates by searching for the specified text pattern across template names, categories, sources, and descriptions. Use this to quickly find templates related to specific monitoring scenarios like \"deadlock\", \"performance\", or \"security\" without browsing all available templates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Template Specifies the exact name(s) of specific templates to retrieve, matching the template file names without the .xml extension. Use this when you know the specific template names you want to examine, such as \"Deadlock_Tracking\" or \"Query_Duration_Performance\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 and supplementary information from the metadata catalog. Default display properties (via Select-DefaultView): Name: The session name from the template (e.g., 'system_health', 'Deadlock_Tracking') Category: The template category for organizational grouping (e.g., 'Performance', 'Security', 'Monitoring') Source: The source or author of the template (e.g., 'Microsoft', 'Jes Borland', 'Christian Grafe') Compatibility: Comma-separated list of SQL Server versions this template is compatible with (e.g., '2008, 2012, 2014, 2016, 2017, 2019') Description: Text description of what the template monitors or its intended use case Additional properties available (use Select-Object to view):* TemplateName: The template name element from XML Path: FileInfo object representing the template file path File: The template file name with extension Use Select-Object to access all properties including the file path and additional metadata embedded in the template objects. &nbsp;"
  },
  {
    "name": "Get-DbaXEStore",
    "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.",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Get",
    "popular": false,
    "url": "/Get-DbaXEStore",
    "popularityRank": 608,
    "synopsis": "Retrieves the Extended Events store object for managing XEvent sessions and configurations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Get-DbaXEStore View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves the Extended Events store object for managing XEvent sessions and configurations 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. Syntax Get-DbaXEStore [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns an XEvent Store PS C:\\> Get-DbaXEStore -SqlInstance ServerA\\sql987 Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.XEvent.XEStore Returns one XEStore object per SQL Server instance specified, providing access to Extended Events sessions, packages, and configuration management. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) ServerName: The name of the SQL Server instance from the XEStore object Sessions: Collection of Extended Events sessions on the instance Packages: Collection of XEvent packages available on the instance RunningSessionCount: The number of currently active/running XEvent sessions All properties from the base SMO XEStore object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Grant-DbaAgPermission",
    "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't exist on the target instance, simplifying multi-server availability group deployments.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Grant",
    "popular": false,
    "url": "/Grant-DbaAgPermission",
    "popularityRank": 254,
    "synopsis": "Grants specific permissions to logins for availability groups and database mirroring endpoints.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Grant-DbaAgPermission View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Grants specific permissions to logins for availability groups and database mirroring endpoints. 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't exist on the target instance, simplifying multi-server availability group deployments. Syntax Grant-DbaAgPermission [[-SqlInstance] ] [[-SqlCredential] ] [[-Login] ] [[-AvailabilityGroup] ] [-Type] [[-Permission] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Adds CreateAnyDatabase permissions to the SharePoint availability group on sql2017a PS C:\\> Grant-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup SharePoint -Permission CreateAnyDatabase Adds CreateAnyDatabase permissions to the SharePoint availability group on sql2017a. Does not prompt for confirmation. Example 2: Adds CreateAnyDatabase permissions to the ag1 and ag2 availability groups on sql2017a PS C:\\> Grant-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup ag1, ag2 -Permission CreateAnyDatabase -Confirm Adds CreateAnyDatabase permissions to the ag1 and ag2 availability groups on sql2017a. Prompts for confirmation. Example 3: Grants the selected logins Connect permissions on the DatabaseMirroring endpoint for sql2017a PS C:\\> Get-DbaLogin -SqlInstance sql2017a | Out-GridView -Passthru | Grant-DbaAgPermission -Type EndPoint Required Parameters -Type Specifies whether to grant permissions on database mirroring endpoints or availability groups. Use 'Endpoint' for database mirroring endpoint permissions or 'AvailabilityGroup' for AG-level permissions. Endpoint permissions are needed for replicas to communicate, while AvailabilityGroup permissions control AG management operations. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | | Accepted Values | Endpoint,AvailabilityGroup | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Specifies the SQL Server logins that will receive the permissions. Windows logins are automatically created if they don't exist on the target instance. Use this when you need to grant permissions to specific service accounts or users for availability group operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies which availability groups to grant permissions on. Required when using Type 'AvailabilityGroup'. Use this to limit permission grants to specific AGs rather than all availability groups on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Permission Specifies which permissions to grant. Defaults to 'Connect' for basic endpoint access. For endpoints: Connect, Alter, Control, and others. For availability groups: Alter, Control, TakeOwnership, ViewDefinition only. Use 'CreateAnyDatabase' for AGs to allow automatic seeding of new databases to replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Connect | | Accepted Values | 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've already retrieved specific logins and want to grant them permissions. Provides an alternative to specifying individual login names with the -Login parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per permission grant operation when granting permissions on database mirroring endpoints or availability groups. When performing GrantAvailabilityGroupCreateDatabasePrivilege operations, no output is returned. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Name: The login name that was granted the permission Permission: The permission type that was granted (Connect, Alter, Control, TakeOwnership, ViewDefinition) Type: Always \"Grant\" indicating this is a permission grant operation Status: Status of the grant operation (\"Success\" if completed without error) &nbsp;"
  },
  {
    "name": "Import-Command",
    "description": null,
    "category": "Utilities",
    "tags": [],
    "verb": "Import",
    "popular": false,
    "url": "/Import-Command",
    "popularityRank": 0,
    "synopsis": "\r\nImport-Command [-Path <string>] [<CommonParameters>]\r\n",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Import-Command View Source Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters Synopsis Import-Command [-Path ] [ ] Description Syntax Import-CommandsyntaxItem ---------- {@{name= Import-Command; CommonParameters=True; WorkflowCommonParameters=False; parameter=System.Object[]}} &nbsp; Examples &nbsp; Optional Parameters -Path | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | &nbsp;"
  },
  {
    "name": "Import-DbaBinaryFile",
    "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's limits.",
    "category": "Backup & Restore",
    "tags": [
      "migration",
      "backup",
      "export"
    ],
    "verb": "Import",
    "popular": false,
    "url": "/Import-DbaBinaryFile",
    "popularityRank": 520,
    "synopsis": "Loads binary files from the filesystem into SQL Server database tables",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Import-DbaBinaryFile View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Loads binary files from the filesystem into SQL Server database tables 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. The 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. Files 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's limits. Syntax Import-DbaBinaryFile [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Table] ] [[-Schema] ] [[-Statement] ] [[-FileNameColumn] ] [[-BinaryColumn] ] [-NoFileNameColumn] [[-InputObject] ] [[-FilePath] ] [[-Path] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Imports all photos from C:\\photos into the photos table in the employees database on sqlcs PS C:\\> Get-ChildItem C:\\photos | Import-DbaBinaryFile -SqlInstance sqlcs -Database employees -Table photos Imports 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. Example 2: Imports the file adalsql.msi into the BunchOFiles table in the tempdb database on sqlcs PS C:\\> Import-DbaBinaryFile -SqlInstance sqlcs -Database tempdb -Table BunchOFiles -FilePath C:\\azure\\adalsql.msi Imports 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. Example 3: Imports the file adalsql.msi into the BunchOFiles table in the tempdb database on sqlcs PS C:\\> Import-DbaBinaryFile -SqlInstance sqlcs -Database tempdb -Table BunchOFiles -FilePath C:\\azure\\adalsql.msi -FileNameColumn fname -BinaryColumn data Imports 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. Optional Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target database where the binary files will be imported. Required when not using InputObject. Use this to identify which database contains the table for storing your binary files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Specifies the target table where binary files will be stored. Must contain at least one binary-type column (binary, varbinary, image). Use this when importing files into a specific table designed for file storage. Supports three-part naming (db.schema.table). If the object has special characters please wrap them in square brackets [ ]. Using dbo.First.Table will try to find table named 'Table' on schema 'First' and database 'dbo'. The correct way to find table named 'First.Table' on schema 'dbo' is by passing dbo.[First.Table] Any actual usage of the ] must be escaped by duplicating the ] character. The correct way to find a table Name] in schema Schema.Name is by passing [Schema.Name].[Name]]] | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Specifies the schema containing the target table. Defaults to the user's default schema if not specified. Use this when your table exists in a non-default schema or when you need to be explicit about schema ownership. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Statement Provides a custom INSERT statement for complex import scenarios. Must include @FileContents parameter for binary data. Use this when automatic column detection fails or when you need custom INSERT logic with joins, triggers, or computed columns. Example: INSERT INTO db.tbl ([FileNameColumn], [bBinaryColumn]) VALUES (@FileName, @FileContents) The @FileContents parameter is required. Include @FileName parameter if storing filenames. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileNameColumn Specifies which column will store the original filename. Auto-detects columns containing 'name' if not specified. Use this when your table has multiple name-related columns or when auto-detection fails to identify the correct column. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BinaryColumn Specifies which column will store the binary file data. Auto-detects binary, varbinary, or image columns if not specified. Use this when your table has multiple binary columns or when auto-detection fails to identify the correct storage column. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoFileNameColumn Indicates that the target table does not have a column for storing filenames. Only the binary data will be imported. Use this when your table design only stores file content without filename metadata for blob storage scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts table objects from Get-DbaDbTable for pipeline-based imports. Alternative to specifying Database and Table parameters. Use this when working with multiple tables or when integrating with other dbatools commands that return table objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -FilePath Specifies one or more individual files to import into the database table. Accepts pipeline input from Get-ChildItem. Use this when importing specific files rather than entire directories. Cannot be used with Path parameter. | Property | Value | | --- | --- | | Alias | FullName | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Path Specifies a directory containing files to import. Recursively processes all files within the directory and subdirectories. Use this when bulk importing multiple files from a folder structure. Cannot be used with FilePath parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per file imported. Each object contains status and context information about the import operation. Properties: ComputerName: The computer name of the SQL Server instance where the file was imported InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database where the file was imported Table: The name of the table where the binary file was stored FilePath: The full file system path of the source file that was imported Status: The import operation status (\"Success\" when file was successfully imported) &nbsp;"
  },
  {
    "name": "Import-DbaCsv",
    "description": "Import-DbaCsv uses .NET's 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't 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.",
    "category": "Data Operations",
    "tags": [
      "import",
      "data",
      "utility"
    ],
    "verb": "Import",
    "popular": true,
    "url": "/Import-DbaCsv",
    "popularityRank": 14,
    "synopsis": "Imports CSV files into SQL Server tables using high-performance bulk copy operations.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Import-DbaCsv View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Imports CSV files into SQL Server tables using high-performance bulk copy operations. Description Import-DbaCsv uses .NET's 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. When the target table doesn't 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. Supports 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. Perfect for ETL processes, data migrations, or loading reference data where you need reliable, fast imports with proper error handling and transaction safety. Syntax Import-DbaCsv [[-Path] ] [-SqlInstance] [[-SqlCredential] ] [-Database] [[-Table] ] [[-Schema] ] [-Truncate] [[-Delimiter] ] [-SingleColumn] [[-BatchSize] ] [[-NotifyAfter] ] [-TableLock] [-CheckConstraints] [-FireTriggers] [-KeepIdentity] [-KeepNulls] [[-Column] ] [[-ColumnMap] ] [-KeepOrdinalOrder] [-AutoCreateTable] [-NoColumnOptimize] [-NoProgress] [-NoHeaderRow] [-UseFileNameForSchema] [[-Quote] ] [[-Escape] ] [[-Comment] ] [[-TrimmingOption] ] [[-BufferSize] ] [[-ParseErrorAction] ] [[-Encoding] ] [[-NullValue] ] [[-MaxQuotedFieldLength] ] [-SkipEmptyLine] [-SupportsMultiline] [-UseColumnDefault] [-NoTransaction] [[-MaxDecompressedSize] ] [[-SkipRows] ] [[-QuoteMode] ] [[-DuplicateHeaderBehavior] ] [[-MismatchedFieldAction] ] [-DistinguishEmptyFromNull] [-NormalizeQuotes] [-CollectParseErrors] [[-MaxParseErrors] ] [[-StaticColumns] ] [[-DateTimeFormats] ] [[-Culture] ] [[-SampleRows] ] [-DetectColumnTypes] [-Parallel] [[-ThrottleLimit] ] [[-ParallelBatchSize] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Imports the entire comma-delimited housing.csv to the SQL &quot;markets&quot; database on a SQL Server named sql001... PS C:\\> Import-DbaCsv -Path C:\\temp\\housing.csv -SqlInstance sql001 -Database markets Imports the entire comma-delimited housing.csv to the SQL \"markets\" database on a SQL Server named sql001, using the first row as column names. Since a table name was not specified, the table name is automatically determined from filename as \"housing\". Example 2: Imports the entire tab-delimited housing.csv, including the first row which is not used for colum names, to... PS C:\\> Import-DbaCsv -Path .\\housing.csv -SqlInstance sql001 -Database markets -Table housing -Delimiter \"`t\" -NoHeaderRow Imports 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. Example 3: Imports the entire pipe-delimited huge.txt to the locations database, into the latitudes table on a SQL... PS C:\\> Import-DbaCsv -Path C:\\temp\\huge.txt -SqlInstance sqlcluster -Database locations -Table latitudes -Delimiter \"|\" Imports the entire pipe-delimited huge.txt to the locations database, into the latitudes table on a SQL Server named sqlcluster. Example 4: Imports the single column CSV into TempTable PS C:\\> Import-DbaCsv -Path c:\\temp\\SingleColumn.csv -SqlInstance sql001 -Database markets -Table TempTable -SingleColumn Example 5: Imports every CSV in the \\\\FileServer\\csvs path into both sql001 and sql002&#39;s tempdb database PS C:\\> Get-ChildItem -Path \\\\FileServer\\csvs | Import-DbaCsv -SqlInstance sql001, sql002 -Database tempdb -AutoCreateTable Imports every CSV in the \\\\FileServer\\csvs path into both sql001 and sql002's tempdb database. Each CSV will be imported into an automatically determined table name. Example 6: Shows what would happen if the command were to be executed PS C:\\> Get-ChildItem -Path \\\\FileServer\\csvs | Import-DbaCsv -SqlInstance sql001, sql002 -Database tempdb -AutoCreateTable -WhatIf Example 7: Import only Name, Address and Mobile even if other columns exist PS C:\\> Import-DbaCsv -Path c:\\temp\\dataset.csv -SqlInstance sql2016 -Database tempdb -Column Name, Address, Mobile Import only Name, Address and Mobile even if other columns exist. All other columns are ignored and therefore null or default values. Example 8: Will import the contents of C:\\temp\\schema.data.csv to table &#39;data&#39; in schema &#39;schema&#39; PS C:\\> Import-DbaCsv -Path C:\\temp\\schema.data.csv -SqlInstance sql2016 -database tempdb -UseFileNameForSchema Example 9: Will import the contents of C:\\temp\\schema.data.csv to table &#39;testtable&#39; in schema &#39;schema&#39; PS C:\\> Import-DbaCsv -Path C:\\temp\\schema.data.csv -SqlInstance sql2016 -database tempdb -UseFileNameForSchema -Table testtable Example 10: The CSV field &#39;Text&#39; is inserted into SQL column &#39;FirstName&#39; and CSV field Number is inserted into the SQL... PS C:\\> $columns = @{ >> Text = 'FirstName' >> Number = 'PhoneNumber' >> } PS C:\\> Import-DbaCsv -Path c:\\temp\\supersmall.csv -SqlInstance sql2016 -Database tempdb -ColumnMap $columns The CSV field 'Text' is inserted into SQL column 'FirstName' and CSV field Number is inserted into the SQL Column 'PhoneNumber'. All other columns are ignored and therefore null or default values. Example 11: If the CSV has no headers, passing a ColumnMap works when you have as the key the ordinal of the column... PS C:\\> $columns = @{ >> 0 = 'FirstName' >> 1 = 'PhoneNumber' >> } PS C:\\> Import-DbaCsv -Path c:\\temp\\supersmall.csv -SqlInstance sql2016 -Database tempdb -NoHeaderRow -ColumnMap $columns If the CSV has no headers, passing a ColumnMap works when you have as the key the ordinal of the column (0-based). In this example the first CSV field is inserted into SQL column 'FirstName' and the second CSV field is inserted into the SQL Column 'PhoneNumber'. Example 12: Imports a CSV file that uses a multi-character delimiter (::) PS C:\\> Import-DbaCsv -Path C:\\temp\\data.csv -SqlInstance sql001 -Database tempdb -Table MyTable -Delimiter \"::\" -AutoCreateTable Imports a CSV file that uses a multi-character delimiter (::). The new CSV reader supports delimiters of any length, not just single characters. Example 13: Imports a gzip-compressed CSV file PS C:\\> Import-DbaCsv -Path C:\\temp\\data.csv.gz -SqlInstance sql001 -Database tempdb -Table MyTable -AutoCreateTable Imports a gzip-compressed CSV file. Compression is automatically detected from the .gz extension and the file is decompressed on-the-fly during import without extracting to disk. Example 14: Skips the first 3 rows of the file before reading headers and data PS C:\\> Import-DbaCsv -Path C:\\temp\\export.csv -SqlInstance sql001 -Database tempdb -Table MyTable -SkipRows 3 -AutoCreateTable Skips the first 3 rows of the file before reading headers and data. Useful for files that have metadata rows, comments, or report headers before the actual CSV content begins. Example 15: Handles CSV files with duplicate column headers by automatically renaming them (e.g., Name, Name_2, Name_3) PS C:\\> Import-DbaCsv -Path C:\\temp\\data.csv -SqlInstance sql001 -Database tempdb -Table MyTable -DuplicateHeaderBehavior Rename -AutoCreateTable Handles CSV files with duplicate column headers by automatically renaming them (e.g., Name, Name_2, Name_3). Without this, duplicate headers would cause an error. Example 16: Imports a CSV where some rows have fewer fields than the header row PS C:\\> Import-DbaCsv -Path C:\\temp\\messy.csv -SqlInstance sql001 -Database tempdb -Table MyTable -MismatchedFieldAction PadWithNulls -AutoCreateTable Imports a CSV where some rows have fewer fields than the header row. Missing fields are padded with NULL values instead of throwing an error. Useful for importing data from systems that omit trailing empty fields. Example 17: Uses lenient quote parsing for CSV files with improperly escaped quotes PS C:\\> Import-DbaCsv -Path C:\\temp\\data.csv -SqlInstance sql001 -Database tempdb -Table MyTable -QuoteMode Lenient -AutoCreateTable Uses lenient quote parsing for CSV files with improperly escaped quotes. This is useful when importing data from systems that don't follow RFC 4180 strictly, such as files with embedded quotes that aren't doubled. Example 18: Imports CSV data into a table with specific column types PS C:\\> # Import CSV with proper type conversion to a pre-created table PS C:\\> $query = \"CREATE TABLE TypedData (id INT, amount DECIMAL(10,2), active BIT, created DATETIME)\" PS C:\\> Invoke-DbaQuery -SqlInstance sql001 -Database tempdb -Query $query PS C:\\> Import-DbaCsv -Path C:\\temp\\typed.csv -SqlInstance sql001 -Database tempdb -Table TypedData Imports CSV data into a table with specific column types. The CSV reader automatically converts string values to the appropriate SQL Server types (INT, DECIMAL, BIT, DATETIME, etc.) during import. Example 19: Imports a large CSV file using parallel processing for improved performance PS C:\\> Import-DbaCsv -Path C:\\temp\\large.csv -SqlInstance sql001 -Database tempdb -Table BigData -AutoCreateTable -Parallel Imports a large CSV file using parallel processing for improved performance. The -Parallel switch enables concurrent line reading, parsing, and type conversion, which can provide 2-4x speedup on multi-core systems for files with 100K+ rows. Example 20: Imports a large CSV with parallel processing limited to 4 worker threads PS C:\\> Import-DbaCsv -Path C:\\temp\\huge.csv -SqlInstance sql001 -Database tempdb -Table HugeData -AutoCreateTable -Parallel -ThrottleLimit 4 Imports a large CSV with parallel processing limited to 4 worker threads. Use -ThrottleLimit to control resource usage on shared systems or when you want to limit CPU consumption during the import. Example 21: Imports a very large CSV with parallel processing using larger batch sizes PS C:\\> Import-DbaCsv -Path C:\\temp\\massive.csv -SqlInstance sql001 -Database tempdb -Table MassiveData -AutoCreateTable -Parallel -ParallelBatchSize 500 Imports a very large CSV with parallel processing using larger batch sizes. Increase -ParallelBatchSize for very large files (millions of rows) to reduce synchronization overhead. The default is 100. Example 22: Performs a full data refresh by truncating the existing table before importing PS C:\\> Import-DbaCsv -Path C:\\temp\\refresh.csv -SqlInstance sql001 -Database tempdb -Table LookupData -Truncate Performs a full data refresh by truncating the existing table before importing. The truncate and import operations are wrapped in a transaction, so if the import fails, the original data is preserved. Example 23: Imports CSV data and adds three static columns (SourceFile, ImportDate, Region) to every row PS C:\\> $static = @{ SourceFile = \"sales_2024.csv\"; ImportDate = (Get-Date); Region = \"EMEA\" } PS C:\\> Import-DbaCsv -Path C:\\temp\\sales.csv -SqlInstance sql001 -Database sales -Table SalesData -StaticColumns $static -AutoCreateTable Imports CSV data and adds three static columns (SourceFile, ImportDate, Region) to every row. This is useful for tracking data lineage and tagging imported records with metadata. Example 24: Imports a CSV with Oracle-style date formats (e.g., &quot;15-Jan-2024&quot;) PS C:\\> Import-DbaCsv -Path C:\\temp\\oracle_export.csv -SqlInstance sql001 -Database tempdb -Table OracleData -DateTimeFormats @(\"dd-MMM-yyyy\", \"dd-MMM-yyyy HH:mm:ss\") -AutoCreateTable Imports a CSV with Oracle-style date formats (e.g., \"15-Jan-2024\"). The -DateTimeFormats parameter specifies custom format strings to parse non-standard date columns correctly. Example 25: Imports a CSV with German number formatting where comma is the decimal separator (e.g., &quot;1.234,56&quot;) PS C:\\> Import-DbaCsv -Path C:\\temp\\german_data.csv -SqlInstance sql001 -Database tempdb -Table GermanData -Culture \"de-DE\" -AutoCreateTable Imports a CSV with German number formatting where comma is the decimal separator (e.g., \"1.234,56\"). The -Culture parameter ensures numbers are parsed correctly according to the specified locale. Example 26: Imports sales.csv and creates the table with optimal column types inferred from the first 10,000 rows PS C:\\> Import-DbaCsv -Path C:\\temp\\sales.csv -SqlInstance sql001 -Database sales -Table SalesData -AutoCreateTable -SampleRows 10000 Imports sales.csv and creates the table with optimal column types inferred from the first 10,000 rows. Instead of nvarchar(MAX) for all columns, the table will have appropriate types like int, decimal(10,2), datetime2, bit, or varchar(50) based on the actual data patterns detected. This is fast but has a small risk if data patterns change after the sampled rows. Example 27: Imports large_dataset.csv with guaranteed optimal column types by scanning the entire file first PS C:\\> Import-DbaCsv -Path C:\\temp\\large_dataset.csv -SqlInstance sql001 -Database warehouse -Table FactSales -AutoCreateTable -DetectColumnTypes Imports large_dataset.csv with guaranteed optimal column types by scanning the entire file first. A separate progress bar shows \"Analyzing column types...\" during the detection phase. The final output (Elapsed, RowsPerSecond) reflects only the import time, not the detection overhead. This is slower (reads file twice) but guarantees no import failures due to type mismatches. Example 28: Imports products.csv with type detection from 5,000 rows, using custom date formats for parsing PS C:\\> Import-DbaCsv -Path C:\\temp\\products.csv -SqlInstance sql001 -Database inventory -Table Products -AutoCreateTable -SampleRows 5000 -DateTimeFormats @(\"dd-MMM-yyyy\", \"yyyy/MM/dd\") Imports products.csv with type detection from 5,000 rows, using custom date formats for parsing. Columns containing dates in formats like \"15-Jan-2024\" or \"2024/01/15\" will be detected as datetime2. Example 29: Imports quickload.csv with AutoCreateTable PS C:\\> Import-DbaCsv -Path C:\\temp\\quickload.csv -SqlInstance sql001 -Database tempdb -Table QuickData -AutoCreateTable Imports quickload.csv with AutoCreateTable. After import completes, column sizes are automatically optimized by querying actual max lengths and altering columns from nvarchar(MAX) to padded sizes like nvarchar(16), nvarchar(32), nvarchar(64), etc. The nvarchar type is preserved to avoid any risk of data loss from Unicode conversion. For ASCII->varchar conversion, use -SampleRows or -DetectColumnTypes. Required Parameters -SqlInstance The SQL Server Instance to import data into. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Database Specifies the target database for the CSV import. The database must exist on the SQL Server instance. Use this to direct your data load to the appropriate database, whether it's a staging, ETL, or production database. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -Path Specifies the file path to CSV files for import. Supports single files, multiple files, or pipeline input from Get-ChildItem. Accepts .csv files and compressed .csv.gz files for large datasets with automatic decompression. | Property | Value | | --- | --- | | Alias | Csv,FullPath | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Specifies the destination table name. If omitted, uses the CSV filename as the table name. The 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Specifies the target schema for the table. Defaults to 'dbo' if not specified. If the schema doesn't exist, it will be created automatically when using -AutoCreateTable. This parameter takes precedence over -UseFileNameForSchema. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Truncate Removes all existing data from the destination table before importing. The truncate operation is part of the transaction. Use this for full data refreshes where you want to replace all existing data with the CSV contents. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Delimiter Sets the field separator used in the CSV file. Defaults to comma if not specified. Common values include comma (,), tab (`t), pipe (|), semicolon (;), or space for different export formats from various systems. Multi-character delimiters are fully supported (e.g., \"::\", \"||\", \"\\t\\t\"). | Property | Value | | --- | --- | | Alias | DelimiterChar | | Required | False | | Pipeline | false | | Default Value | , | -SingleColumn Indicates the CSV contains only one column of data without delimiters. Use this for simple lists or single-value imports. Prevents the function from failing when no delimiter is found in the file content. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BatchSize Controls how many rows are sent to SQL Server in each batch during the bulk copy operation. Defaults to 50,000. Larger batches are generally more efficient but use more memory, while smaller batches provide better granular control and error isolation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 50000 | -NotifyAfter Sets how often progress notifications are displayed during the import, measured in rows. Defaults to 50,000. Lower values provide more frequent updates but may slow the import slightly, while higher values reduce overhead for very large files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 50000 | -TableLock Acquires an exclusive table lock for the duration of the import instead of using row-level locks. Improves performance for large imports by reducing lock overhead, but blocks other operations on the table during the import. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CheckConstraints Enforces check constraints, foreign keys, and other table constraints during the import. By default, constraints are not checked for performance. Enable this when data integrity validation is critical, but expect slower import performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FireTriggers Executes INSERT triggers on the destination table during the bulk copy operation. By default, triggers are not fired for performance. Use this when your triggers perform essential business logic like auditing, logging, or cascading updates that must run during import. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepIdentity Preserves identity column values from the CSV instead of generating new ones. By default, the destination assigns new identity values. Use this when migrating data and you need to maintain existing primary key values or referential integrity. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepNulls Preserves NULL values from the CSV instead of replacing them with column default values. Use this when your data intentionally contains NULLs that should be maintained, rather than having them replaced by table defaults. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Column Imports only the specified columns from the CSV file, ignoring all others. Column names must match exactly. Use this to selectively load data when you only need certain fields, reducing import time and storage requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ColumnMap Maps CSV columns to different table column names using a hashtable. Keys are CSV column names, values are table column names. Use this when your CSV headers don't match your table structure or when importing from systems with different naming conventions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -KeepOrdinalOrder Maps columns by position rather than by name matching. The first CSV column goes to the first table column, second to second, etc. Use this when column names don't match but the order is correct, or when dealing with files that have inconsistent header naming. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AutoCreateTable Creates the destination table automatically if it doesn't exist, using nvarchar(max) for all columns. After import, column sizes are automatically optimized based on actual data lengths (nvarchar(MAX) -> nvarchar(16/32/64/etc.)). For proper type inference (int, decimal, datetime2, varchar vs nvarchar), use -SampleRows or -DetectColumnTypes instead. For production use with specific constraints, create tables manually with appropriate data types, indexes, and constraints. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoColumnOptimize Skips the automatic column size optimization that runs after AutoCreateTable imports. By default, AutoCreateTable creates nvarchar(MAX) columns and then shrinks them to fit the imported data. Use this switch when importing multiple CSV files into the same auto-created table, so that later files with longer values are not rejected due to columns being shrunk to fit only the first file's data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoProgress Disables the progress bar display during import to improve performance, especially for very large files. Use this in automated scripts or when maximum import speed is more important than visual progress feedback. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoHeaderRow Treats the first row as data instead of column headers. Use this when your CSV file starts directly with data rows. When enabled, columns are mapped by ordinal position and you'll need to ensure your target table column order matches the CSV. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UseFileNameForSchema Extracts the schema name from the filename using the first period as a delimiter. For example, 'sales.customers.csv' imports to the 'sales' schema. If no period is found, defaults to 'dbo'. The schema will be created if it doesn't exist. This parameter is ignored if -Schema is explicitly specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Quote Specifies the character used to quote fields containing delimiters or special characters. Defaults to double-quote (\"). Change this when your CSV uses different quoting conventions, such as single quotes from certain export tools. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \" | -Escape Specifies the character used to escape quote characters within quoted fields. Defaults to double-quote (\"). Modify this when dealing with CSV files that use different escaping conventions, such as backslash escaping. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \" | -Comment Specifies the character that marks comment lines to be ignored during import. Defaults to hashtag (#). Use this when your CSV files contain comment lines with metadata or instructions that should be skipped. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | # | -TrimmingOption Controls automatic whitespace removal from field values. Options are All, None, UnquotedOnly, or QuotedOnly. Use 'All' to clean up data with inconsistent spacing, or 'None' to preserve exact formatting when whitespace is significant. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | None | | Accepted Values | All,None,UnquotedOnly,QuotedOnly | -BufferSize Sets the internal buffer size in bytes for reading the CSV file. Defaults to 4096 bytes. Increase this value for better performance with very large files, but it will use more memory during the import process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 4096 | -ParseErrorAction Determines how to handle malformed rows during import. 'ThrowException' stops the import, 'AdvanceToNextLine' skips bad rows. Use 'AdvanceToNextLine' for importing data with known quality issues where you want to load as much valid data as possible. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | ThrowException | | Accepted Values | AdvanceToNextLine,ThrowException | -Encoding Specifies the text encoding of the CSV file. Defaults to UTF-8. Change this when dealing with files from legacy systems that use different encodings like ASCII or when dealing with international character sets. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UTF8 | | Accepted Values | 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 'NULL', 'null', or empty strings. Use this when your source system exports NULL values as specific text strings that need to be converted to database NULLs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaxQuotedFieldLength Sets the maximum allowed length in bytes for quoted fields to prevent memory issues with malformed data. Increase this when working with legitimate large text fields, or decrease it to catch data quality issues early. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -SkipEmptyLine Ignores completely empty lines in the CSV file during import. Use this when your source files contain blank lines for formatting that should not create empty rows in your table. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SupportsMultiline Controls whether properly quoted field values may span multiple lines, such as addresses or comments with embedded line breaks. In Strict QuoteMode, RFC 4180 multiline handling is enabled by default. Specify -SupportsMultiline:$false to force single-line parsing, or -SupportsMultiline to enable it explicitly in Lenient mode. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UseColumnDefault Applies table column default values when CSV fields are missing or empty. Use this when your CSV doesn't include all table columns and you want defaults applied rather than NULLs or import failures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoTransaction Disables the automatic transaction wrapper, allowing partial imports to remain committed even if the operation fails. Use this for very large imports where you want to commit data in batches, but be aware that failed imports may leave partial data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MaxDecompressedSize Maximum size in bytes for decompressed data when reading compressed CSV files (.gz, .br, .deflate, .zlib). This protects against decompression bomb attacks. Default is 10GB (10737418240 bytes). Set to 0 for unlimited (not recommended for untrusted files). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 10737418240 | -SkipRows Number of rows to skip at the beginning of the file before reading headers or data. Useful for files with metadata rows before the actual CSV content. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -QuoteMode Controls how quoted fields are parsed. Strict: RFC 4180 compliant parsing (default) Lenient: More forgiving parsing for malformed CSV files with embedded quotes | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Strict | | Accepted Values | Strict,Lenient | -DuplicateHeaderBehavior Controls how duplicate column headers are handled. ThrowException: Throw an error (default) Rename: Rename duplicates (Name_2, Name_3, etc.) UseFirstOccurrence: Keep first, ignore duplicates UseLastOccurrence: Keep last, rename earlier occurrences | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | ThrowException | | Accepted Values | ThrowException,Rename,UseFirstOccurrence,UseLastOccurrence | -MismatchedFieldAction Controls what happens when a row has more or fewer fields than expected. ThrowException: Throw an error (default) PadWithNulls: Pad missing fields with null TruncateExtra: Remove extra fields PadOrTruncate: Both pad and truncate as needed | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | ThrowException | | Accepted Values | ThrowException,PadWithNulls,TruncateExtra,PadOrTruncate | -DistinguishEmptyFromNull When specified, treats empty quoted fields (\"\") as empty strings and unquoted empty fields (,,) as null values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NormalizeQuotes When specified, converts smart/curly quotes (' ' \" \") to standard ASCII quotes before parsing. Useful when importing data exported from Microsoft Word or Excel. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CollectParseErrors When specified, collects parse errors instead of throwing immediately. Use with -MaxParseErrors to limit the number of errors collected. Errors can be retrieved from the reader after import completes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MaxParseErrors Maximum number of parse errors to collect before stopping. Only applies when -CollectParseErrors is specified. Default is 1000. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1000 | -StaticColumns A hashtable of static column names and values to add to every row. Useful for tagging imported data with metadata like source filename or import timestamp. Keys are column names, values are the static values to insert. Example: @{ SourceFile = \"data.csv\"; ImportDate = (Get-Date) } | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DateTimeFormats An array of custom date/time format strings for parsing date columns. Useful when importing data with non-standard date formats (e.g., Oracle's dd-MMM-yyyy). Example: @(\"dd-MMM-yyyy\", \"yyyy/MM/dd\", \"MM-dd-yyyy\") | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Culture The culture name to use for parsing numbers and dates (e.g., \"de-DE\", \"fr-FR\", \"en-US\"). Useful when importing CSV files with locale-specific number formats (e.g., comma as decimal separator). Default is InvariantCulture. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SampleRows Enables smart type detection by sampling the first N rows of the CSV file. When specified, the command analyzes the sample to infer optimal SQL Server column types instead of using nvarchar(MAX) for all columns. This is faster than -DetectColumnTypes but has a small risk if data patterns change after the sampled rows (e.g., row 10001 has a longer string than any in the sample). Implies -AutoCreateTable behavior for type detection. Example: -SampleRows 10000 samples the first 10,000 rows to determine types like int, bigint, decimal(p,s), datetime2, bit, uniqueidentifier, or varchar(n)/nvarchar(n) with appropriate lengths. Unlike plain -AutoCreateTable, this can infer varchar for ASCII-only string data, saving storage space. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -DetectColumnTypes Enables smart type detection by scanning the entire CSV file before import. This guarantees no import failures due to type mismatches but requires reading the file twice (once for analysis, once for import). A separate progress bar is displayed during the type detection phase. The final output (Elapsed, RowsPerSecond) reflects only the import time, not the detection overhead. Implies -AutoCreateTable behavior for type detection. Detected types include: int, bigint, decimal(p,s), datetime2, bit, uniqueidentifier, varchar(n) for ASCII-only strings, and nvarchar(n) when Unicode is detected. This provides optimal storage by using varchar where possible. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Parallel Enables parallel processing for improved performance on large files. When enabled, line reading, parsing, and type conversion are performed in parallel using a producer-consumer pipeline. This can provide 2-4x performance improvement on multi-core systems. Note: Parallel processing is most beneficial for large files (>100K rows) with complex type conversions. For small files, sequential processing may be faster due to lower overhead. When Parallel is used, the progress bar is disabled because the progress callback cannot run in background threads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ThrottleLimit Sets the maximum number of worker threads for parallel processing. Default is 0, which uses the number of logical processors on the system. Set to 1 to effectively disable parallelism while still using the pipeline architecture. Only used when Parallel is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -ParallelBatchSize Sets the number of records to batch before yielding to the consumer during parallel processing. Larger batches reduce synchronization overhead but increase memory usage and latency. Default is 100. Minimum is 1. Only used when Parallel is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 100 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per CSV file imported. Each object contains comprehensive metrics about the import operation. Properties: ComputerName: The computer name of the SQL Server instance where the CSV was imported InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The database name where data was imported Table: The table name where CSV data was loaded Schema: The schema name containing the target table RowsCopied: The total number of rows successfully copied from the CSV file (int64) Elapsed: The elapsed time for the import operation in elapsed time format (automatically formatted as HH:mm:ss.fff) RowsPerSecond: The average import rate calculated as total rows divided by elapsed time in seconds (decimal) Path: The full file system path of the imported CSV file All size and rate metrics are calculated based on the actual import duration, which for type detection operations does not include the time spent scanning the file for column type inference. &nbsp;"
  },
  {
    "name": "Import-DbaPfDataCollectorSetTemplate",
    "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 'Long Running Query' or 'db_ola_health') 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",
    "category": "Utilities",
    "tags": [
      "performance",
      "datacollector",
      "perfcounter"
    ],
    "verb": "Import",
    "popular": false,
    "url": "/Import-DbaPfDataCollectorSetTemplate",
    "popularityRank": 638,
    "synopsis": "Creates Windows Performance Monitor data collector sets with SQL Server-specific performance counters from predefined templates.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Import-DbaPfDataCollectorSetTemplate View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates Windows Performance Monitor data collector sets with SQL Server-specific performance counters from predefined templates. 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 'Long Running Query' or 'db_ola_health') or custom XML template files you specify. Performance 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. Requires local administrator privileges on the target computer when importing data collector sets. See https://msdn.microsoft.com/en-us/library/windows/desktop/aa371952 for more information Syntax Import-DbaPfDataCollectorSetTemplate [[-ComputerName] ] [[-Credential] ] [[-DisplayName] ] [-SchedulesEnabled] [[-RootPath] ] [-Segment] [[-SegmentMaxDuration] ] [[-SegmentMaxSize] ] [[-Subdirectory] ] [[-SubdirectoryFormat] ] [[-SubdirectoryFormatPattern] ] [[-Task] ] [-TaskRunAsSelf] [[-TaskArguments] ] [[-TaskUserTextArguments] ] [-StopOnCompletion] [[-Path] ] [[-Template] ] [[-Instance] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new data collector set named &#39;Long Running Query&#39; from the dbatools repository on the SQL Server... PS C:\\> Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template 'Long Running Query' Creates a new data collector set named 'Long Running Query' from the dbatools repository on the SQL Server sql2017. Example 2: Creates a new data collector set named &quot;New Long Running Query&quot; using the &#39;Long Running Query&#39; template PS C:\\> Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template 'Long Running Query' -DisplayName 'New Long running query' -Confirm Creates a new data collector set named \"New Long Running Query\" using the 'Long Running Query' template. Forces a confirmation if the template exists. Example 3: Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template db_ola_health |... PS C:\\> Get-DbaPfDataCollectorSet -ComputerName sql2017 -Session db_ola_health | Remove-DbaPfDataCollectorSet Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template db_ola_health | Start-DbaPfDataCollectorSet Imports a session if it exists, then recreates it using a template. Example 4: Allows you to select a Session template then import to an instance named sql2017 PS C:\\> Get-DbaPfDataCollectorSetTemplate | Out-GridView -PassThru | Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 Example 5: Creates a new data collector set named &#39;Long Running Query&#39; from the dbatools repository on the SQL Server... PS C:\\> Import-DbaPfDataCollectorSetTemplate -ComputerName sql2017 -Template 'Long Running Query' -Instance SHAREPOINT Creates a new data collector set named 'Long Running Query' from the dbatools repository on the SQL Server sql2017 for both the default and the SHAREPOINT instance. If you'd like to remove counters for the default instance, use Remove-DbaPfDataCollectorCounter. Optional Parameters -ComputerName Specifies the Windows server where the Performance Monitor data collector set will be created. Defaults to the local machine. Use this when monitoring SQL Server instances on remote servers or when centralizing performance monitoring from a management workstation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to servers using alternative credentials. To use: $scred = Get-Credential, then pass $scred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DisplayName Sets the display name for the data collector set as it appears in Performance Monitor. Defaults to the template name. Use this to create meaningful names when deploying multiple collector sets or to distinguish between environments like 'Prod-SQL-Perf' or 'Dev-Query-Analysis'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SchedulesEnabled Enables scheduled data collection for the collector set if defined in the template. When disabled, the collector set must be started manually. Use this switch when you want the collector set to automatically start and stop based on predefined schedules rather than manual intervention. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -RootPath Specifies the base directory where performance log files will be stored. Defaults to %systemdrive%\\PerfLogs\\Admin\\[CollectorSetName]. Change this when you need to store performance logs on a different drive with more space or faster storage for high-frequency data collection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Segment Enables automatic log file segmentation when maximum file size or duration limits are reached during data collection. Use this to prevent single log files from becoming too large and to maintain manageable file sizes for analysis tools and storage management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SegmentMaxDuration Specifies the maximum time duration (in seconds) before a new log file is created during data collection. Requires -Segment to be enabled. Set this to control how long each performance log file covers, which helps with organizing data by time periods for analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -SegmentMaxSize Specifies the maximum size (in bytes) for each performance log file before a new file is created. Requires -Segment to be enabled. Set this to prevent individual log files from consuming excessive disk space and to maintain consistent file sizes for easier management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Subdirectory Specifies a subdirectory name under the root path where log files will be stored for this collector set instance. Use this to organize performance logs by purpose, environment, or time period within your monitoring directory structure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SubdirectoryFormat Controls how Performance Monitor decorates the subdirectory name with timestamp information. Uses numeric flags where 3 includes day/hour formatting. This automatically creates time-stamped subdirectories to organize log files chronologically, making it easier to locate performance data from specific time periods. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 3 | -SubdirectoryFormatPattern Specifies the timestamp format pattern used for decorating subdirectory names. Default is 'yyyyMMdd\\-NNNNNN' (year-month-day-sequence). Customize this pattern when you need specific date/time formatting for your log file organization or to match existing naming conventions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | yyyyMMdd\\-NNNNNN | -Task Specifies a Windows Task Scheduler job name to execute automatically when the data collector set stops or between log segments. Use this to trigger post-processing tasks like data analysis scripts, log file compression, or alerting when performance data collection completes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need consistent security context between data collection and post-processing tasks for file access permissions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -TaskArguments Specifies command-line arguments to pass to the scheduled task when it executes after data collection stops. Use this to pass parameters like log file paths, collection timestamps, or processing options to your post-collection analysis scripts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TaskUserTextArguments Provides replacement text for the {usertext} placeholder variable in task arguments when the scheduled task executes. Use this to dynamically pass environment-specific information like server names, database names, or custom identifiers to your post-processing tasks. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StopOnCompletion Automatically stops the data collector set when all individual data collectors within the set have finished their collection tasks. Use this switch when you want the collector set to terminate cleanly after completing defined collection tasks rather than running indefinitely. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Path Specifies the file path to custom XML template files containing performance counter definitions. Accepts multiple file paths. Use this when you have custom performance monitoring templates or need to import templates from sources other than the built-in dbatools repository. | Property | Value | | --- | --- | | Alias | FullName | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Template Selects predefined performance monitoring templates from the dbatools repository such as 'Long Running Query' or 'db_ola_health'. Press Tab to see available options. Use this for quick deployment of SQL Server-specific performance monitoring without creating custom XML templates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you have multiple SQL Server instances on a server and want to add specific named instances like 'SHAREPOINT' or 'REPORTING' to the monitoring scope. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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 instance detected on the target machine. Default display properties (via Select-DefaultView): ComputerName: The name of the computer where the Data Collector Set is configured Name: The name of the Data Collector Set DisplayName: The user-friendly display name of the collector set Description: Text description of what the collector set monitors State: Current state (Unknown, Disabled, Queued, Ready, Running) Duration: Duration in seconds for which the collector set will run OutputLocation: File system path where collected data is stored LatestOutputLocation: Path to the most recently collected output files RootPath: Root directory path for the collector set configuration SchedulesEnabled: Boolean indicating if schedules are enabled Segment: Segment configuration value for data collection SegmentMaxDuration: Maximum duration in seconds for a collection segment SegmentMaxSize: Maximum size in MB for a collection segment SerialNumber: Serial number or identifier for the collector set Server: Name of the server hosting the collector set StopOnCompletion: Boolean indicating if the collector set stops automatically when complete Subdirectory: Subdirectory path for organizing collector set output SubdirectoryFormat: Format pattern for subdirectory naming SubdirectoryFormatPattern: Detailed format pattern specification Task: Name of the Windows Task Scheduler task associated with the collector set TaskArguments: Command-line arguments passed to the collector set task TaskRunAsSelf: Boolean indicating if the task runs under the specified user account TaskUserTextArguments: User-specified text arguments for the task UserAccount: Windows user account under which the collector set runs *Additional properties available (via Select-Object ):** Keywords: Keywords associated with the collector set for searching/categorizing DescriptionUnresolved: Raw description text before localization/resolution DisplayNameUnresolved: Raw display name before localization/resolution Schedules: Collection of schedule objects for the collector set Xml: Raw XML configuration of the collector set Security: Security descriptor for the collector set DataCollectorSetObject: Boolean indicating the object came from a Data Collector Set COM object TaskObject: Reference to the underlying Task Scheduler COM object Credential: The credentials used to retrieve this collector set &nbsp;"
  },
  {
    "name": "Import-DbaRegServer",
    "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.",
    "category": "Utilities",
    "tags": [
      "registeredserver",
      "cms"
    ],
    "verb": "Import",
    "popular": false,
    "url": "/Import-DbaRegServer",
    "popularityRank": 362,
    "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",
    "windowsOnly": false,
    "fullContent": "Import-DbaRegServer View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Imports registered servers and server groups into SQL Server Central Management Server from XML files, other CMS instances, or custom objects 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. Syntax Import-DbaRegServer [-SqlInstance] [[-SqlCredential] ] [[-Path] ] [[-InputObject] ] [[-Group] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Imports C:\\temp\\corp-regservers.xml to the CMS on sql2012 PS C:\\> Import-DbaRegServer -SqlInstance sql2012 -Path C:\\temp\\corp-regservers.xml Example 2: Imports C:\\temp\\Seattle.xml to Seattle subgroup within the hr group on sql2008 PS C:\\> Import-DbaRegServer -SqlInstance sql2008 -Group hr\\Seattle -Path C:\\temp\\Seattle.xml Example 3: Imports all registered servers from sql2008 and sql2012 to sql2017 PS C:\\> Get-DbaRegServer -SqlInstance sql2008, sql2012 | Import-DbaRegServer -SqlInstance sql2017 Example 4: Imports all registered servers from the hr\\Seattle group on sql2008 to the Seattle group on sql2017 PS C:\\> Get-DbaRegServerGroup -SqlInstance sql2008 -Group hr\\Seattle | Import-DbaRegServer -SqlInstance sql2017 -Group Seattle Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the file path to XML files containing exported registered server configurations from SQL Server Management Studio or Export-DbaRegServer. Use this when migrating CMS configurations between environments or restoring server lists from backup exports. | Property | Value | | --- | --- | | Alias | FullName | | Required | False | | Pipeline | false | | Default Value | | -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. When 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 bulk-loading server inventories. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -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. Use this when you need to organize imported servers into specific groups rather than importing to the root level. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer Returns 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 that did not exist before the import operation). Default display properties (via Select-DefaultView): Name: The display name of the registered server as shown in SSMS Registered Servers ServerName: The actual SQL Server connection string (computer name, IP address, or instance name) Group: The CMS group path (hierarchical, using backslash separators) or null for root-level servers Description: Text description of the registered server Source: Source location of the registration - \"Central Management Servers\", \"Local Server Groups\", or \"Azure Data Studio\" *Additional properties available from the RegisteredServer object (via Select-Object ):* ComputerName: NetBIOS computer name of the CMS instance InstanceName: The SQL Server instance name of the CMS SqlInstance: The full SQL Server instance name of the CMS ParentServer: The parent CMS instance name ConnectionString: The connection string with decrypted password if available SecureConnectionString: The connection string as a SecureString object if password was decrypted Id: Internal identifier for the registered server ServerType: Type of server (DatabaseEngine, AnalysisServices, ReportingServices, etc.) CredentialPersistenceType: Whether credentials are stored Urn: The Uniform Resource Name (URN) for the registered server object All properties from the base RegisteredServer SMO object are accessible using Select-Object . &nbsp;"
  },
  {
    "name": "Import-DbaSpConfigure",
    "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.",
    "category": "Utilities",
    "tags": [
      "spconfig",
      "configure",
      "configuration"
    ],
    "verb": "Import",
    "popular": false,
    "url": "/Import-DbaSpConfigure",
    "popularityRank": 504,
    "synopsis": "Copies sp_configure settings between SQL Server instances or applies settings from a SQL file.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Import-DbaSpConfigure View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Copies sp_configure settings between SQL Server instances or applies settings from a SQL file. 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. Syntax Import-DbaSpConfigure [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Import-DbaSpConfigure [-Source ] [-Destination ] [-SourceSqlCredential ] [-DestinationSqlCredential ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Import-DbaSpConfigure [-SqlInstance ] [-Path ] [-SqlCredential ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Imports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server... PS C:\\> Import-DbaSpConfigure -Source sqlserver -Destination sqlcluster Imports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server using Windows Authentication Example 2: Imports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server... PS C:\\> Import-DbaSpConfigure -Source sqlserver -Destination sqlcluster -Force Imports 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 Example 3: Imports the sp_configure settings from the source server sqlserver and sets them on the sqlcluster server... PS C:\\> Import-DbaSpConfigure -Source sqlserver -Destination sqlcluster -SourceSqlCredential $SourceSqlCredential -DestinationSqlCredential $DestinationSqlCredential Imports 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 $DestinationSqlCredential Example 4: Imports the sp_configure settings from the file .\\spconfig.sql and sets them on the sqlserver server using... PS C:\\> Import-DbaSpConfigure -SqlInstance sqlserver -Path .\\spconfig.sql -SqlCredential $SqlCredential Imports 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 Optional Parameters -Source Source SQL Server instance to copy sp_configure settings from. Requires sysadmin privileges to read configuration values. Use this when migrating settings between servers or standardizing configurations across your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Destination Target SQL Server instance where sp_configure settings will be applied. Requires sysadmin privileges to modify configuration. This server will have its configuration updated to match the source server's settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SourceSqlCredential Credentials for connecting to the source SQL Server instance. Use when Windows authentication is not available. Accepts PowerShell credential objects created with Get-Credential. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instance. Use when Windows authentication is not available. Accepts PowerShell credential objects created with Get-Credential. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlInstance Specifies a SQL Server instance to set up sp_configure values on using a SQL file. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Path to a SQL script file containing sp_configure commands to execute. The file should contain individual sp_configure statements. Use this parameter when applying saved configurations from Export-DbaSpConfigure or custom configuration scripts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Use this SQL credential if you are setting up sp_configure values from a SQL file. Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Bypasses the SQL Server version compatibility check between source and destination instances. By default, major versions must match. Use with caution as some configuration options may not be available or may behave differently across SQL Server versions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.Boolean Returns $true if the sp_configure settings were successfully applied to the destination instance, or $false if the operation failed. When 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 migration process. When 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 configuration import. Note: The function may also display warning messages about configuration options that require SQL Server restart, but these do not affect the boolean return value. &nbsp;"
  },
  {
    "name": "Import-DbatoolsConfig",
    "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.",
    "category": "Utilities",
    "tags": [
      "module"
    ],
    "verb": "Import",
    "popular": false,
    "url": "/Import-DbatoolsConfig",
    "popularityRank": 515,
    "synopsis": "Imports dbatools configuration settings from JSON files or default module paths.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Import-DbatoolsConfig View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Imports dbatools configuration settings from JSON files or default module 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. Syntax Import-DbatoolsConfig -Path [-IncludeFilter ] [-ExcludeFilter ] [-Peek] [-EnableException] [ ] Import-DbatoolsConfig -ModuleName [-ModuleVersion ] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Imports the configuration stored in &#39;.\\config.json&#39; PS C:\\> Import-DbatoolsConfig -Path '.\\config.json' Example 2: Imports all the module specific settings that have been persisted in any of the default file system paths PS C:\\> Import-DbatoolsConfig -ModuleName message Required Parameters -Path Specifies the path to JSON configuration files, web URLs, or raw JSON strings to import settings from. Use this to restore saved dbatools preferences, apply team-standard configurations, or load settings from remote locations. Accepts local file paths, HTTP/HTTPS URLs, or direct JSON content as strings. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -ModuleName Specifies which dbatools module's configuration settings to import from default system locations. Use this to restore module-specific settings that were previously saved using Export-DbatoolsConfig. Common modules include 'message' for logging preferences and 'sql' for connection defaults. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -ModuleVersion Specifies which version of the module configuration schema to load when importing persisted settings. Defaults to version 1, which works for most scenarios unless you're working with legacy configuration exports. Only change this if you're importing settings exported with a different version of dbatools. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1 | -Scope Controls which configuration storage locations to search when importing module settings. Options include FileUserLocal (user profile), FileUserShared (shared user settings), and FileSystem (system-wide). User settings override system settings when the same configuration exists in multiple locations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | FileUserLocal, FileUserShared, FileSystem | -IncludeFilter Specifies wildcard patterns to selectively import only matching configuration items from the source. Use this to import specific settings like 'sql.connection.' for connection-related configs or 'logging.' for logging preferences. Supports PowerShell -like wildcard matching with * and ? characters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeFilter Specifies wildcard patterns to exclude specific configuration items during import. Use this to skip sensitive settings like credentials or environment-specific paths when sharing configurations. Applied after IncludeFilter, allowing you to include a category but exclude specific items within it. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Peek Returns the configuration items that would be imported without actually applying them to your session. Use this to preview configuration changes before applying them, especially when importing from unfamiliar sources. Helpful for validating configuration files and understanding what settings will be modified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Object[] (when -Peek is specified) Returns an array of configuration element objects that would be imported without applying them. Each element has the following properties: FullName (string) - The fully qualified configuration name (e.g., 'sql.connection.timeout') Value (object) - The configuration value to be applied Type (string) - The data type of the configuration value KeepPersisted (boolean) - Boolean indicating if the value should remain persisted across sessions Returns nothing (when -Peek is not specified) When 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 module's internal configuration storage. Note: The function writes status messages to the information stream during import, but these are not part of the formal output. &nbsp;"
  },
  {
    "name": "Import-DbaXESessionTemplate",
    "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.",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Import",
    "popular": false,
    "url": "/Import-DbaXESessionTemplate",
    "popularityRank": 540,
    "synopsis": "Creates Extended Events sessions from XML templates on SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Import-DbaXESessionTemplate View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates Extended Events sessions from XML templates on SQL Server instances 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. Templates 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. The 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. Syntax Import-DbaXESessionTemplate [-SqlInstance] [[-SqlCredential] ] [[-Name] ] [[-Path] ] [[-Template] ] [[-TargetFilePath] ] [[-TargetFileMetadataPath] ] [[-StartUpState] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new XESession named &quot;15 Second IO Error&quot; from the dbatools repository to the SQL Server sql2017 PS C:\\> Import-DbaXESessionTemplate -SqlInstance sql2017 -Template \"15 Second IO Error\" Example 2: Creates a new XESession named &quot;Index Page Splits&quot; from the dbatools repository to the SQL Server sql2017... PS C:\\> Import-DbaXESessionTemplate -SqlInstance sql2017 -Template \"Index Page Splits\" -StartUpState On Creates 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 restart. Example 3: Creates a new XESession named &quot;Query Wait Stats&quot; using the Query Wait Statistics template, then immediately... PS C:\\> Import-DbaXESessionTemplate -SqlInstance sql2017 -Template \"Query Wait Statistics\" -Name \"Query Wait Stats\" | Start-DbaXESession Creates a new XESession named \"Query Wait Stats\" using the Query Wait Statistics template, then immediately starts it. Example 4: Removes a session if it exists, then recreates it using a template PS C:\\> Get-DbaXESession -SqlInstance sql2017 -Session 'Database Health 2014' | Remove-DbaXESession PS C:\\> Import-DbaXESessionTemplate -SqlInstance sql2017 -Template 'Database Health 2014' | Start-DbaXESession Example 5: Allows you to select a Session template then import to an instance named sql2017 PS C:\\> Get-DbaXESessionTemplate | Out-GridView -PassThru | Import-DbaXESessionTemplate -SqlInstance sql2017 Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies a custom name for the Extended Events session being created. When not provided, the session name defaults to the template filename. Use this when you need multiple sessions from the same template or want descriptive names that match your monitoring standards. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the full file path to custom Extended Events session XML template files. Accepts multiple file paths for bulk imports. Use this when importing custom templates you've created or third-party XE session definitions instead of built-in dbatools templates. | Property | Value | | --- | --- | | Alias | FullName | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Template Specifies the name of a built-in Extended Events template from the dbatools repository. Accepts multiple template names for bulk deployment. Use 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 scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TargetFilePath Overrides the default directory for Extended Events trace files (.xel files) in the template. Specify only the directory path, not filenames. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TargetFileMetadataPath Overrides the default directory for Extended Events metadata files (.xem files) in the template. Specify only the directory path, not filenames. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartUpState Controls whether the Extended Events session starts immediately and automatically restarts after SQL Server restarts. Default is Off. Set to \"On\" when you need continuous monitoring that survives server restarts, such as for production performance monitoring or security auditing sessions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Off | | Accepted Values | On,Off | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.XEvent.Session Returns 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 restart. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the Extended Events session Status: Current session status (Running, Stopped, or other state values) StartTime: DateTime when the session was started (null if stopped) AutoStart: Boolean indicating if the session starts automatically on SQL Server restart State: SMO object state (Existing, Creating, Pending, Dropping, etc.) Targets: Target collection for the session (event file, ring buffer, etc.) TargetFile: File path(s) where XE trace data is being written Events: Events configured in the session MaxMemory: Maximum memory in MB allocated to the session MaxEventSize: Maximum size in MB for individual events Additional properties available (from SMO Session object): Parent: Reference to the parent XEStore object Store: Reference to the parent XEStore object Session: Copy of the session name property RemoteTargetFile: UNC paths for remote target files All other standard SMO Session properties accessible via Select-Object All properties from the base SMO XEvent.Session object are accessible even though only default properties are displayed without using Select-Object . &nbsp;"
  },
  {
    "name": "Install-DbaAgentAdminAlert",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "alert"
    ],
    "verb": "Install",
    "popular": false,
    "url": "/Install-DbaAgentAdminAlert",
    "popularityRank": 477,
    "synopsis": "Creates standard SQL Server Agent alerts for critical system errors and disk I/O failures",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Install-DbaAgentAdminAlert View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates standard SQL Server Agent alerts for critical system errors and disk I/O failures 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. The 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. You 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. Syntax Install-DbaAgentAdminAlert [-SqlInstance] [[-SqlCredential] ] [[-Category] ] [[-Database] ] [[-Operator] ] [[-OperatorEmail] ] [[-DelayBetweenResponses] ] [-Disabled] [[-EventDescriptionKeyword] ] [[-EventSource] ] [[-JobId] ] [[-ExcludeSeverity] ] [[-ExcludeMessageId] ] [[-NotificationMessage] ] [[-NotifyMethod] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates alerts for severity 17-25 and messages 823-825 on sql1 PS C:\\> Install-DbaAgentAdminAlert -SqlInstance sql1 Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Category Assigns the alerts to a specific SQL Server Agent alert category for better organization and management. Defaults to 'Uncategorized' if not specified. Use 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't exist, it will be created automatically. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you want to monitor only specific critical databases and avoid noise from test or development databases on the same instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. If not specified and only one operator exists on the instance, that operator will be used automatically. Required for alert notifications to function properly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OperatorEmail Creates a new SQL Server Agent operator with this email address if the specified operator name doesn't exist. Must be used together with the Operator parameter. This allows you to set up both the operator and alerts in a single command when configuring monitoring on a new instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this to avoid flooding your inbox during cascading failures or when the same error occurs multiple times in rapid succession. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when you want to set up the alert infrastructure first and enable specific alerts later after testing or validation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this to create more targeted alerts that focus on specific error conditions within the broader categories of critical system errors. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this to trigger automated response scripts, such as collecting diagnostic information, attempting automatic recovery, or escalating to additional monitoring systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 system problems. Use this when you want to skip certain severities, perhaps because you already have custom alerts configured for them or they're not relevant to your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 corruption issues. Use this when you want to skip certain message IDs, perhaps because you have existing custom alerts for these errors or they don't apply to your storage configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NotificationMessage Customizes the message content sent to operators when an alert fires. If not specified, SQL Server uses the default system-generated message. Use this to include specific instructions, contact information, or troubleshooting steps that help your team respond more effectively to critical errors. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NotifyMethod Specifies how the operator should be notified when the alert fires. Valid options are 'NotifyEmail', 'Pager', 'NetSend', 'NotifyAll', or 'None'. Defaults to 'NotifyAll'. Use 'NotifyEmail' for email-only notifications, 'NotifyAll' to use all configured notification methods for the operator, or 'None' to create alerts without notifications (useful for logging only). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | NotifyAll | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Alert Returns 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 fewer if specific severities or message IDs are excluded via -ExcludeSeverity or -ExcludeMessageId parameters. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) InstanceName: The SQL Server instance name Name: The alert name (e.g., \"Severity 017 - Insufficient Resources\", \"Error Number 823 - Read/Write Error\") Severity: The error severity level being monitored (0 for message ID alerts, 17-25 for severity alerts) MessageId: The error message ID being monitored (0 for severity alerts, 823-825 for message ID alerts) JobName: Name of the SQL Server Agent job executed when alert fires (if -JobId was specified) CategoryName: Name of the alert category (if -Category was specified) DelayBetweenResponses: Minimum seconds between alert notifications (if -DelayBetweenResponses was specified) ID: Unique identifier for the alert within the instance AlertType: Type of alert (Severity or Message ID based) IsEnabled: Boolean indicating if the alert is enabled LastRaised: DateTime when the alert last fired OccurrenceCount: Number of times the alert has fired Additional properties available (from SMO Alert object): CategoryId: Numeric identifier of the alert category CreateDate: DateTime when the alert was created DateLastModified: DateTime when the alert was last modified DatabaseName: Name of specific database alert is restricted to (if -Database was specified) Urn: The Uniform Resource Name of the alert object State: SMO object state (Existing, Creating, Pending, Dropping, etc.) Notifications: DataTable containing notification settings for operators EventSource: Event source filter if specified EventDescriptionKeyword: Event description keyword filter if specified NotifyMethod: Notification method configured for the alert All properties from the base SMO Alert object are accessible using Select-Object * even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Install-DbaDarlingData",
    "description": "Downloads, extracts and installs Erik Darling's 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",
    "category": "Utilities",
    "tags": [
      "community",
      "erik darling",
      "darlingdata"
    ],
    "verb": "Install",
    "popular": false,
    "url": "/Install-DbaDarlingData",
    "popularityRank": 96,
    "synopsis": "Downloads and installs Erik Darling's performance monitoring stored procedures",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Install-DbaDarlingData View Source Ant Green (@ant_green) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Downloads and installs Erik Darling's performance monitoring stored procedures Description Downloads, extracts and installs Erik Darling's 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. DarlingData links: https://www.erikdarling.com https://github.com/erikdarlingdata/DarlingData Syntax Install-DbaDarlingData [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Branch] ] [[-Procedure] ] [[-LocalFile] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Logs into server1 with Windows authentication and then installs all of Erik&#39;s scripts in the master database PS C:\\> Install-DbaDarlingData -SqlInstance server1 -Database master Example 2: Logs into server1\\instance1 with Windows authentication and then installs all of Erik&#39;s scripts in the DBA... PS C:\\> Install-DbaDarlingData -SqlInstance server1\\instance1 -Database DBA Logs into server1\\instance1 with Windows authentication and then installs all of Erik's scripts in the DBA database. Example 3: Logs into server1\\instance1 with SQL authentication and then installs all of Erik&#39;s scripts in the master... PS C:\\> Install-DbaDarlingData -SqlInstance server1\\instance1 -Database master -SqlCredential $cred Logs into server1\\instance1 with SQL authentication and then installs all of Erik's scripts in the master database. Example 4: Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs... PS C:\\> Install-DbaDarlingData -SqlInstance sql2016\\standardrtm, sql2016\\sqlexpress, sql2014 Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs al of Erik's scripts in the master database. Example 5: Installs the dev branch version of Erik&#39;s scripts in the master database on sql2016 instance PS C:\\> Install-DbaDarlingData -SqlInstance sql2016 -Branch dev Example 6: Logs into server1\\instance1 with Windows authentication and then installs sp_HumanEvents and... PS C:\\> Install-DbaDarlingData -SqlInstance server1\\instance1 -Database DBA -Procedure Human, Pressure Logs into server1\\instance1 with Windows authentication and then installs sp_HumanEvents and sp_PressureDetector of Erik's scripts in the DBA database. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target database where Erik Darling's performance monitoring stored procedures will be installed. Commonly set to master, DBA, or a dedicated administrative database where diagnostic procedures are centralized. The database must already exist on the target instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | master | -Branch Specifies which branch of the DarlingData repository to install from. Use 'main' for the latest stable release or 'dev' for experimental features and bug fixes. The dev branch may contain newer procedures or fixes not yet available in the main branch. Allowed values: main (default) dev | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | main | | Accepted Values | main,dev | -Procedure Specifies which specific performance monitoring procedures to install instead of the complete collection. Use this when you only need particular diagnostic tools or want to avoid installing procedures you don't use. Each procedure addresses different performance areas: HumanEvents for extended events analysis, PressureDetector for memory pressure monitoring, QuickieStore for Query Store analysis. Allowed Values or Combination of Values: All (default, to install all procedures) HumanEvents (to install sp_HumanEvents) PressureDetector (to install sp_PressureDetector) QuickieStore (to install sp_QuickieStore) HumanEventsBlockViewer (to install sp_HumanEventsBlockViewer) LogHunter (to install sp_LogHunter) HealthParser (to install sp_HealthParser) IndexCleanup (to install sp_IndexCleanup) PerfCheck (to install sp_PerfCheck) The following shorthands are allowed, ordered as above: Human, Pressure, Quickie, Block, Log, Health, Index, Perf. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | All | | Accepted Values | 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. Use this when internet access is restricted, when you need to install a specific version, or when you have a pre-downloaded copy. The file must be the official zip distribution from the DarlingData repository maintainers. If this parameter is not specified, the latest version will be downloaded and installed from https://github.com/erikdarlingdata/DarlingData | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Forces a fresh download of the DarlingData procedures even if a cached version already exists locally. Use this when you need to ensure you have the absolute latest version or when troubleshooting installation issues. Without this switch, the function uses the cached version if available to improve performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts to confirm actions | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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 procedures, only scripts matching those procedures are processed and returned. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The target database where scripts are installed Name: The base name of the script file (without extension) Status: Installation status - 'Installed' (newly created), 'Updated' (already existed and was overwritten), 'Skipped' (version incompatible like sp_QuickieStore on SQL Server < 2016), or 'Error' (script execution failed) &nbsp;"
  },
  {
    "name": "Install-DbaFirstResponderKit",
    "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't 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",
    "category": "Utilities",
    "tags": [
      "community",
      "firstresponderkit"
    ],
    "verb": "Install",
    "popular": false,
    "url": "/Install-DbaFirstResponderKit",
    "popularityRank": 104,
    "synopsis": "Downloads and installs Brent Ozar's First Responder Kit diagnostic stored procedures.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Install-DbaFirstResponderKit View Source Tara Kizer, Brent Ozar Unlimited (brentozar.com) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Downloads and installs Brent Ozar's First Responder Kit diagnostic stored procedures. 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. This 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't supported on older SQL Server versions. Perfect for DBAs who need standardized diagnostic tools across multiple SQL Server instances without manually downloading and deploying scripts. First Responder Kit links: http://FirstResponderKit.org https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit Syntax Install-DbaFirstResponderKit [-SqlInstance] [[-SqlCredential] ] [[-Branch] ] [[-Database] ] [[-LocalFile] ] [[-OnlyScript] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Logs into server1 with Windows authentication and then installs the FRK in the master database PS C:\\> Install-DbaFirstResponderKit -SqlInstance server1 -Database master Example 2: Logs into server1\\instance1 with Windows authentication and then installs the FRK in the DBA database PS C:\\> Install-DbaFirstResponderKit -SqlInstance server1\\instance1 -Database DBA Example 3: Logs into server1\\instance1 with SQL authentication and then installs the FRK in the master database PS C:\\> Install-DbaFirstResponderKit -SqlInstance server1\\instance1 -Database master -SqlCredential $cred Example 4: Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs... PS C:\\> Install-DbaFirstResponderKit -SqlInstance sql2016\\standardrtm, sql2016\\sqlexpress, sql2014 Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs the FRK in the master database. Example 5: Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs... PS C:\\> $servers = \"sql2016\\standardrtm\", \"sql2016\\sqlexpress\", \"sql2014\" PS C:\\> $servers | Install-DbaFirstResponderKit Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs the FRK in the master database. Example 6: Installs the dev branch version of the FRK in the master database on sql2016 instance PS C:\\> Install-DbaFirstResponderKit -SqlInstance sql2016 -Branch dev Example 7: Installs only the procedures sp_Blitz and sp_BlitzWho and the table SqlServerVersions by running the... PS C:\\> Install-DbaFirstResponderKit -SqlInstance sql2016 -OnlyScript sp_Blitz.sql, sp_BlitzWho.sql, SqlServerVersions.sql Installs only the procedures sp_Blitz and sp_BlitzWho and the table SqlServerVersions by running the corresponding scripts. Example 8: Installs the First Responder Kit using the official install script PS C:\\> Install-DbaFirstResponderKit -SqlInstance sql2016 -OnlyScript Install-All-Scripts.sql Example 9: Installs the First Responder Kit using the official install script for Azure SQL Database PS C:\\> Install-DbaFirstResponderKit -SqlInstance sql-server-001.database.windows.net -OnlyScript Install-Azure.sql Example 10: Uninstalls the First Responder Kit by running the official uninstall script PS C:\\> Install-DbaFirstResponderKit -SqlInstance sql2016 -OnlyScript Uninstall.sql Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Branch Specifies which GitHub branch of the First Responder Kit to download and install. Defaults to 'main' for the stable release. Use 'dev' to install the development branch when you need the latest features or bug fixes that haven't been released yet. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | main | | Accepted Values | main,dev | -Database Specifies the target database where the First Responder Kit stored procedures will be installed. Defaults to master. Consider using a dedicated DBA or utility database instead of master for better organization and maintenance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | master | -LocalFile Specifies the path to a local zip file containing the First Responder Kit scripts instead of downloading from GitHub. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OnlyScript Specifies specific script files to install instead of the entire First Responder Kit. Accepts multiple script names and wildcards. Use 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 remove the toolkit. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this when you want to ensure you have the absolute latest version or when the cached version may be corrupted. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts to confirm actions | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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 specified scripts are processed and returned. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The target database where scripts are installed Name: The base name of the script file (without extension) Status: Installation status - 'Installed' (newly created), 'Updated' (already existed and was overwritten), 'Skipped' (version incompatible like sp_BlitzQueryStore on SQL Server < 2016 or sp_BlitzInMemoryOLTP on SQL Server < 2014), or 'Error' (script execution failed) &nbsp;"
  },
  {
    "name": "Install-DbaInstance",
    "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 'commands.initialize-credssp.bypass' value to $true.\nTo be able to configure CredSSP, the command needs to be run in an elevated PowerShell session.",
    "category": "Server Management",
    "tags": [
      "deployment",
      "install"
    ],
    "verb": "Install",
    "popular": true,
    "url": "/Install-DbaInstance",
    "popularityRank": 22,
    "synopsis": "Automates SQL Server instance installation across local and remote computers with customizable configuration.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Install-DbaInstance View Source Reitse Eskens (@2meterDBA), Kirill Kravtsov (@nvarscar) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Automates SQL Server instance installation across local and remote computers with customizable configuration. 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. The 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. Key automation features include: Generates secure SA passwords for mixed authentication mode installations Automatically grants sysadmin rights to your account or specified administrators Configures tempdb file counts based on server CPU cores for optimal performance Handles service account credentials using native PowerShell credential objects Manages installation media location detection across network and local paths Performs prerequisite validation including pending reboot detection Supports parallel installation across multiple servers with throttling controls Configures TCP port settings post-installation when specified Advanced configuration capabilities: Import existing Configuration.ini files or build configurations from scratch Override any SQL Server setup parameter using the -Configuration hashtable Support for specialized installations like failover cluster instances Enable instant file initialization (perform volume maintenance tasks) automatically Slipstream updates during installation using -UpdateSourcePath Install specific feature combinations using templates (Default, All) or individual components Authentication and credential management: Automatically configures CredSSP authentication for network-based installations when needed Supports various authentication protocols (Kerberos, NTLM, Basic) with fallback options Handles domain service accounts, managed service accounts (MSAs), and local accounts Manages distinct service credentials for Database Engine, SQL Agent, Analysis Services, Integration Services, and other components Installation media requirements: Requires extracted SQL Server installation media accessible to target servers Supports both local and network-based installation media repositories Automatically locates appropriate setup.exe files based on specified SQL Server version Falls back to Evaluation edition if no Product ID is provided in configuration Remote execution considerations: Requires elevated privileges on target computers for SQL Server installation Automatically handles CredSSP configuration when installing from network shares Supports custom authentication protocols and credential delegation scenarios Can optionally restart target computers automatically when required by installation prerequisites Note that the downloaded installation media must be extracted and available to the server where the installation runs. NOTE: If no ProductID (PID) is found in the configuration files/parameters, Evaluation version is going to be installed. When using CredSSP authentication, this function will try to configure CredSSP authentication for PowerShell Remoting sessions. If this is not desired (e.g.: CredSSP authentication is managed externally, or is already configured appropriately,) it can be disabled by setting the dbatools configuration option 'commands.initialize-credssp.bypass' value to $true. To be able to configure CredSSP, the command needs to be run in an elevated PowerShell session. Syntax Install-DbaInstance [[-SqlInstance] ] [-Version] [[-InstanceName] ] [[-SaCredential] ] [[-Credential] ] [[-Authentication] ] [[-ConfigurationFile] ] [[-Configuration] ] [[-Path] ] [[-Feature] ] [[-AuthenticationMode] ] [[-InstancePath] ] [[-DataPath] ] [[-LogPath] ] [[-TempPath] ] [[-BackupPath] ] [[-UpdateSourcePath] ] [[-AdminAccount] ] [[-ASAdminAccount] ] [[-Port] ] [[-Throttle] ] [[-ProductID] ] [[-AsCollation] ] [[-SqlCollation] ] [[-EngineCredential] ] [[-AgentCredential] ] [[-ASCredential] ] [[-ISCredential] ] [[-RSCredential] ] [[-FTCredential] ] [[-PBEngineCredential] ] [[-SaveConfiguration] ] [-PerformVolumeMaintenanceTasks] [-Restart] [-NoPendingRenameCheck] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Install a default SQL Server instance and run the installation enabling all features with default settings PS C:\\> Install-DbaInstance -Version 2017 -Feature All Install a default SQL Server instance and run the installation enabling all features with default settings. Automatically generates configuration.ini Example 2: Install a named SQL Server instance named sqlexpress on sql2017, and a default instance on server01 PS C:\\> Install-DbaInstance -SqlInstance sql2017\\sqlexpress, server01 -Version 2017 -Feature Default Install a named SQL Server instance named sqlexpress on sql2017, and a default instance on server01. Automatically generates configuration.ini. Default features will be installed. Example 3: Install a default named SQL Server instance on the remote machine, sql2017 and use the local configuration.ini PS C:\\> Install-DbaInstance -Version 2008R2 -SqlInstance sql2017 -ConfigurationFile C:\\temp\\configuration.ini Example 4: Run the installation locally with default settings apart from the application volume, this will be redirected... PS C:\\> Install-DbaInstance -Version 2017 -InstancePath G:\\SQLServer -UpdateSourcePath '\\\\my\\updates' Run the installation locally with default settings apart from the application volume, this will be redirected to G:\\SQLServer. The installation procedure would search for SQL Server updates in \\\\my\\updates and slipstream them into the installation. Example 5: Install SQL Server 2016 instance into D:\\Root drive, set default data folder as E: and default logs folder as... PS C:\\> $svcAcc = Get-Credential MyDomain\\SvcSqlServer PS C:\\> Install-DbaInstance -Version 2016 -InstancePath D:\\Root -DataPath E: -LogPath L: -PerformVolumeMaintenanceTasks -EngineCredential $svcAcc Install SQL Server 2016 instance into D:\\Root drive, set default data folder as E: and default logs folder as L:. Perform volume maintenance tasks permission is granted. MyDomain\\SvcSqlServer is used as a service account for SqlServer. Example 6: The same as the last example except MyDomain\\SvcSqlServer is now a Managed Service Account (MSA) PS C:\\> $svcAcc = [PSCredential]::new(\"MyDomain\\SvcSqlServer$\", [SecureString]::new()) PS C:\\> Install-DbaInstance -Version 2016 -InstancePath D:\\Root -DataPath E: -LogPath L: -PerformVolumeMaintenanceTasks -EngineCredential $svcAcc Example 7: Run the installation locally with default settings overriding the value of specific configuration items PS C:\\> $config = @{ >> AGTSVCSTARTUPTYPE = \"Manual\" >> BROWSERSVCSTARTUPTYPE = \"Manual\" >> FILESTREAMLEVEL = 1 >> } PS C:\\> Install-DbaInstance -SqlInstance localhost\\v2017:1337 -Version 2017 -SqlCollation Latin1_General_CI_AS -Configuration $config Run the installation locally with default settings overriding the value of specific configuration items. Instance name will be defined as 'v2017'; TCP port will be changed to 1337 after installation. Example 8: Install SQL Server 2022 with Database Engine and Analysis Services features PS C:\\> $svcAcc = Get-Credential MyDomain\\SvcSqlServer PS C:\\> Install-DbaInstance -Version 2022 -Feature Engine,AnalysisServices -AdminAccount \"AD\\MSSQLAdmins\" -ASAdminAccount \"AD\\SSASAdmins\" -EngineCredential $svcAcc -ASCredential $svcAcc Install SQL Server 2022 with Database Engine and Analysis Services features. Grants sysadmin rights to AD\\MSSQLAdmins on the Database Engine and administrator rights to AD\\SSASAdmins on Analysis Services. Uses MyDomain\\SvcSqlServer as the service account for both services. Required Parameters -Version Specifies the SQL Server version to install using the year-based identifier. Valid values are 2008, 2008R2, 2012, 2014, 2016, 2017, 2019, 2022, and 2025. This parameter determines which setup.exe file to locate in the installation media and configures version-specific features like tempdb file optimization (SQL 2016+). | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | | Accepted Values | 2008,2008R2,2012,2014,2016,2017,2019,2022,2025 | Optional Parameters -SqlInstance The target computer and, optionally, a new instance name and a port number. Use one of the following generic formats: Server1 Server2\\Instance1 Server1\\Alpha:1533, Server2\\Omega:1566 \"ServerName\\NewInstanceName,1534\" You can also define instance name and port using -InstanceName and -Port parameters. | Property | Value | | --- | --- | | Alias | ComputerName | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -InstanceName Specifies the name for the new SQL Server instance, overriding any instance name in the SqlInstance parameter. Use 'MSSQLSERVER' for the default instance or a custom name for named instances. Named instances enable multiple SQL Server installations on the same server and affect service names, registry keys, and connection strings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SaCredential Specifies the password for the sa account when AuthenticationMode is set to Mixed. If not provided with Mixed mode, a random 128-character password is automatically generated and returned in the output. Only required when you want to set a specific sa password instead of using the auto-generated one. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Windows Credential with permission to log on to the remote server. Must be specified for any remote connection if SQL Server installation media is located on a network folder. Authentication will default to CredSSP if -Credential is used. For CredSSP see also additional information in DESCRIPTION. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Authentication Specifies the PowerShell remoting authentication protocol for connecting to remote servers during installation. Defaults to CredSSP when -Credential is provided to handle network share access and avoid double-hop authentication issues. Use 'Kerberos' in domain environments where CredSSP is restricted, or 'Basic' for workgroup scenarios. When installing from network shares, CredSSP is typically required to pass credentials through to the file server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @('Credssp', 'Default')[$null -eq $Credential] | | Accepted Values | Default,Basic,Negotiate,NegotiateWithImplicitCredential,Credssp,Digest,Kerberos | -ConfigurationFile Path to an existing SQL Server Configuration.ini file to use for the installation. Use 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. The function will read and apply all settings from this file, overriding any conflicting parameters. | Property | Value | | --- | --- | | Alias | FilePath | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Configuration A hashtable containing SQL Server setup configuration parameters that override function defaults. Use this for advanced scenarios like setting custom startup types, enabling specific features, or configuring failover cluster instances. Each key-value pair becomes a parameter in the Configuration.ini file, allowing full control over the installation process. When ACTION is specified, only minimal defaults are set, requiring you to provide all necessary configuration items for that specific installation type. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory containing extracted SQL Server installation media, which will be scanned recursively for the appropriate setup.exe. Can be a local path or network share accessible from target servers during remote installations. The path must contain the extracted ISO contents or downloaded installer files, not the ISO file itself. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -Name 'Path.SQLServerSetup') | -Feature Specifies which SQL Server components to install, either as individual features or using predefined templates. 'Default' installs Engine, Replication, FullText, and Tools for typical database server setups. 'All' installs every available feature for the specified version. Choose specific features like 'Engine', 'AnalysisServices', 'ReportingServices', or 'IntegrationServices' for targeted installations based on your requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Default | | Accepted Values | 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). Windows mode is more secure and recommended for domain environments, while Mixed mode is required for applications that need SQL logins. When using Mixed mode, ensure you provide a strong SaCredential or allow the function to generate a secure random password. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Windows | | Accepted Values | Windows,Mixed | -InstancePath Specifies the root directory where SQL Server instance files will be installed, including program files, system databases, and logs. Defaults to the standard program files location unless you need to install on a different drive for capacity or performance reasons. This path becomes the base for all instance-specific directories unless individual paths are specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DataPath Specifies the default directory for user database data files (.mdf and .ndf). Used as the default location when creating new databases if no explicit path is provided in CREATE DATABASE statements. Consider placing this on high-performance storage separate from logs for optimal I/O performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LogPath Specifies the default directory for user database transaction log files (.ldf). Used as the default location for transaction logs when creating new databases. Best practice is to place logs on separate storage from data files to optimize write performance and enable better backup strategies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TempPath Specifies the directory for tempdb database files, which handle temporary objects and internal SQL Server operations. Consider placing tempdb on fast storage (SSD) separate from user databases since it's heavily used for sorts, joins, and temporary tables. For SQL 2016+, the function automatically configures multiple tempdb data files based on CPU core count. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BackupPath Specifies the default directory for database backup files when no explicit path is provided in BACKUP commands. This location should have sufficient space for your backup retention strategy and be accessible to your backup software. Consider network accessibility if you plan to backup to shared storage or use backup software that requires UNC paths. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -UpdateSourcePath Specifies the directory containing SQL Server updates (service packs, cumulative updates) to apply during installation. Enables slipstream installation to avoid separate patching steps after the base installation completes. The path should contain the update executable files compatible with the SQL Server version being installed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AdminAccount Specifies one or more Windows accounts to grant sysadmin privileges on the new SQL Server instance. Defaults to the current user or the account specified in the Credential parameter. Use domain\\\\username format for domain accounts or computername\\\\username for local accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ASAdminAccount Specifies one or more Windows accounts to grant administrator privileges on Analysis Services. Required when installing Analysis Services feature. At least one administrator account must be specified. Use domain\\\\username format for domain accounts or computername\\\\username for local accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Port Specifies the TCP port number for SQL Server after installation, overriding the default port 1433. The function configures the port post-installation since SQL Server setup doesn't directly support custom ports. Use non-standard ports for security through obscurity or when running multiple instances that need distinct ports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Throttle Specifies the maximum number of concurrent SQL Server installations when targeting multiple servers. Controls resource usage and network bandwidth by limiting parallel operations. Consider your network capacity, installation media server performance, and available system resources when adjusting from the default of 50. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 50 | -ProductID Specifies the product license key (PID) to install a licensed edition of SQL Server instead of Evaluation edition. Required only when the installation media doesn't include an embedded license key. Without a valid ProductID, the installation defaults to a time-limited Evaluation edition that expires after 180 days. | Property | Value | | --- | --- | | Alias | PID | | Required | False | | Pipeline | false | | Default Value | | -AsCollation Specifies the collation for Analysis Services, determining sort order and character comparison rules for SSAS databases. Defaults to Latin1_General_CI_AS if not specified. Choose a collation that matches your data locale and case sensitivity requirements for dimensional and tabular models. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCollation Specifies the server-level collation for the Database Engine, affecting sort order, case sensitivity, and accent sensitivity for all databases. Defaults to the Windows locale setting if not specified. Choose carefully as changing server collation after installation requires rebuilding system databases and can affect application compatibility. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EngineCredential Specifies the Windows account to run the SQL Server Database Engine service. Use domain service accounts for network access, Managed Service Accounts (MSAs) for automated password management, or local accounts for standalone servers. The account needs specific Windows privileges like 'Log on as a service' and permissions to the installation directories. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AgentCredential Specifies the Windows account to run the SQL Server Agent service, which manages scheduled jobs, alerts, and replication. Typically uses the same account as the Database Engine for simplicity, but can be separate for security isolation. Requires permissions to execute job steps, access network resources for backup jobs, and interact with other SQL Server instances for replication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ASCredential Specifies the Windows account to run the Analysis Services (SSAS) service for OLAP cubes and tabular models. The account needs permissions to data sources, file system access for processing, and network connectivity for distributed queries. Consider using a dedicated service account when SSAS requires different security contexts than the Database Engine. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ISCredential Specifies the Windows account to run the Integration Services (SSIS) service for ETL package execution and management. The account needs permissions to source and destination systems, file shares for package storage, and SQL Server databases for logging and configuration. Use a service account with broad permissions since SSIS packages often access multiple systems and data sources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RSCredential Specifies the Windows account to run the Reporting Services (SSRS) service for report generation and delivery. The account needs permissions to the report server database, data sources used in reports, and network resources for email delivery. Consider network connectivity requirements when reports access remote data sources or when using email subscriptions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FTCredential Specifies the Windows account to run the Full-Text Filter Daemon service for indexing and searching text content in databases. The account needs permissions to database files and temporary directories used during full-text indexing operations. Usually runs under a low-privilege account since it only processes text extraction and indexing without requiring broad system access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PBEngineCredential Specifies the Windows account to run the PolyBase Engine service for distributed queries against Hadoop, Azure Blob Storage, and other external data sources. The account needs network access to external systems and permissions to temporary directories for data processing. Required when installing PolyBase features for big data integration and external table functionality. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SaveConfiguration Specifies a path to save the generated Configuration.ini file for future reference or reuse. Without this parameter, the configuration file is created in a temporary location and not preserved after installation. Useful for documenting installation settings, troubleshooting, or replicating installations across multiple servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PerformVolumeMaintenanceTasks Grants the SQL Server service account 'Perform volume maintenance tasks' privilege to enable instant file initialization. Allows SQL Server to skip zero-initialization of data files, significantly reducing the time for database creation, restore operations, and auto-growth events. Only affects data files; transaction log files are always zero-initialized for transaction integrity. | Property | Value | | --- | --- | | Alias | InstantFileInitialization,IFI | | Required | False | | Pipeline | false | | Default Value | False | -Restart Automatically restarts target computers when required by Windows updates, pending file operations, or installation prerequisites. Use this during maintenance windows when automatic restarts are acceptable. Without this parameter, installations will fail if pending restarts are detected, requiring manual intervention. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoPendingRenameCheck Skips the check for pending file rename operations when validating reboot requirements. Use this when you know pending renames won't affect the SQL Server installation or when working with systems that show false positives for pending renames. Generally safer to allow the default validation unless you have specific reasons to bypass this safety check. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -Name 'OS.PendingRename' -Fallback $false) | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance installed, providing detailed installation results and status information for each target computer. Default display properties (via Select-DefaultView): ComputerName: The target computer where SQL Server was installed InstanceName: The SQL Server instance name that was installed Version: The SQL Server version installed (e.g., 14.0 for SQL Server 2017) Port: The TCP port configured for the instance after installation (nullable int, null if default 1433) Successful: Boolean indicating if the installation completed successfully (True/False) Restarted: Boolean indicating if the computer was restarted during installation (True/False) Installer: The full path to the SQL Server setup.exe file used for installation ExitCode: The exit code returned by setup.exe (nullable int; 0 = success, 3010 = reboot required, other values = failure) LogFile: The full path to the installation Summary.txt log file on the target computer Notes: Array of strings containing installation warnings, errors, or post-installation action notes Additional properties available: SACredential: The SA account credential provided if mixed-mode authentication was configured Configuration: The hashtable of SQL Server configuration settings used for installation ExitMessage: Detailed exit message text extracted from the installation summary log Log: Full contents of the installation Summary.txt file as array of strings, includes detailed setup diagnostics ConfigurationFile: Path to the ConfigurationFile.ini used during installation on the target computer When multiple instances are specified via -SqlInstance, one object is returned per instance. When -Throttle limits parallelism, installation objects are returned as each instance completes. Examine the Successful and ExitCode properties to determine installation outcome; ExitMessage and Log properties contain detailed diagnostic information for troubleshooting failed installations. &nbsp;"
  },
  {
    "name": "Install-DbaMaintenanceSolution",
    "description": "Deploys Ola Hallengren's 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.\n\nThe Maintenance Solution is compatible with SQL Server 2017 and later.\nFor earlier versions, please use the version of Ola Hallengren's scripts that corresponds to your SQL Server version.\nYou can find the appropriate version of the scripts at https://ola.hallengren.com/downloads.html.",
    "category": "Utilities",
    "tags": [
      "community",
      "olahallengren"
    ],
    "verb": "Install",
    "popular": true,
    "url": "/Install-DbaMaintenanceSolution",
    "popularityRank": 43,
    "synopsis": "Installs Ola Hallengren's Maintenance Solution stored procedures and optional SQL Agent jobs for automated database maintenance",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Install-DbaMaintenanceSolution View Source Viorel Ciucu, cviorel.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Installs Ola Hallengren's Maintenance Solution stored procedures and optional SQL Agent jobs for automated database maintenance Description Deploys Ola Hallengren's 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. The Maintenance Solution is compatible with SQL Server 2017 and later. For earlier versions, please use the version of Ola Hallengren's scripts that corresponds to your SQL Server version. You can find the appropriate version of the scripts at https://ola.hallengren.com/downloads.html. Syntax Install-DbaMaintenanceSolution [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-BackupLocation] ] [[-CleanupTime] ] [[-OutputFileDirectory] ] [-ReplaceExisting] [-LogToTable] [[-Solution] ] [-InstallJobs] [[-AutoScheduleJobs] ] [[-StartTime] ] [[-LocalFile] ] [-Force] [-InstallParallel] [-ChangeBackupType] [[-Compress] ] [-CopyOnly] [[-Verify] ] [[-CheckSum] ] [[-ModificationLevel] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Installs Ola Hallengren&#39;s Solution objects on RES14224 in the DBA database PS C:\\> Install-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -InstallJobs -CleanupTime 72 Installs Ola Hallengren's Solution objects on RES14224 in the DBA database. Backups will default to the default Backup Directory. If the Maintenance Solution already exists, the script will be halted. Example 2: This will create the Ola Hallengren&#39;s Solution objects PS C:\\> Install-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -InstallJobs -BackupLocation \"Z:\\SQLBackup\" -CleanupTime 72 This will create the Ola Hallengren's Solution objects. Existing objects are not affected in any way. Example 3: Installs Maintenance Solution to myserver in database PS C:\\> $params = @{ >> SqlInstance = 'MyServer' >> Database = 'maintenance' >> ReplaceExisting = $true >> InstallJobs = $true >> LogToTable = $true >> BackupLocation = 'C:\\Data\\Backup' >> CleanupTime = 65 >> Verbose = $true >> } >> Install-DbaMaintenanceSolution @params Installs Maintenance Solution to myserver in database. Adds Agent Jobs, and if any currently exist, they'll be replaced. Since the `LogToTable` switch is enabled, the CommandLog table will be dropped and recreated also. If the tables relating to `InstallParallel` are present, they will not be dropped. Example 4: This will drop and then recreate the Ola Hallengren&#39;s Solution objects The cleanup script will drop and... PS C:\\> $params = @{ >> SqlInstance = 'RES14224' >> Database = 'DBA' >> InstallJobs = $true >> BackupLocation = 'Z:\\SQLBackup' >> CleanupTime = 72 >> ReplaceExisting = $true >> } PS C:\\> Install-DbaMaintenanceSolution @params This will drop and then recreate the Ola Hallengren's Solution objects The cleanup script will drop and recreate: STORED PROCEDURE [dbo].[CommandExecute] STORED PROCEDURE [dbo].[DatabaseBackup] STORED PROCEDURE [dbo].[DatabaseIntegrityCheck] STORED PROCEDURE [dbo].[IndexOptimize] The tables will not be dropped as the `LogToTable` and `InstallParallel` switches are not enabled. [dbo].[CommandLog] [dbo].[Queue] [dbo].[QueueDatabase] The following SQL Agent jobs will be deleted: 'Output File Cleanup' 'IndexOptimize - USER_DATABASES' 'sp_delete_backuphistory' 'DatabaseBackup - USER_DATABASES - LOG' 'DatabaseBackup - SYSTEM_DATABASES - FULL' 'DatabaseBackup - USER_DATABASES - FULL' 'sp_purge_jobhistory' 'DatabaseIntegrityCheck - SYSTEM_DATABASES' 'CommandLog Cleanup' 'DatabaseIntegrityCheck - USER_DATABASES' 'DatabaseBackup - USER_DATABASES - DIFF' Example 5: This will create the Queue and QueueDatabase tables for uses when manually changing jobs to use the... PS C:\\> Install-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA -InstallParallel This will create the Queue and QueueDatabase tables for uses when manually changing jobs to use the @DatabasesInParallel = 'Y' flag Example 6: This will create the Ola Hallengren&#39;s Solution objects and the SQL Agent Jobs PS C:\\> $params = @{ >> SqlInstance = \"localhost\" >> InstallJobs = $true >> CleanupTime = 720 >> AutoScheduleJobs = \"WeeklyFull\" >> } >> Install-DbaMaintenanceSolution @params This will create the Ola Hallengren's Solution objects and the SQL Agent Jobs. WeeklyFull will create weekly full, daily differential and 15 minute log backups of _user_ databases. _System_ databases will be backed up daily. Databases will be backed up to the default location for the instance, and backups will be deleted after 720 hours (30 days). See https://github.com/dataplat/dbatools/pull/8911 for details on job schedules. Example 7: This will create the Ola Hallengren&#39;s Solution objects and the SQL Agent Jobs PS C:\\> $params = @{ >> SqlInstance = \"localhost\" >> InstallJobs = $true >> CleanupTime = 720 >> AutoScheduleJobs = \"DailyFull\", \"HourlyLog\" >> BackupLocation = \"\\\\sql\\backups\" >> StartTime = \"231500\" >> } PS C:\\> Install-DbaMaintenanceSolution @params This will create the Ola Hallengren's Solution objects and the SQL Agent Jobs. The 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. System databases will be backed up at 1:15 am, two hours after the user databases. Databases will be backed up to a fileshare, and the backups will be deleted after 720 hours (30 days). See https://blog.netnerds.net/2023/05/install-dbamaintenancesolution-now-supports-auto-scheduling/ for more information. Example 8: Installs Ola Hallengren&#39;s Solution with backup jobs that include automatic backup type conversion... PS C:\\> $params = @{ >> SqlInstance = \"localhost\" >> Database = \"DBAMaintenance\" >> InstallJobs = $true >> BackupLocation = \"D:\\SQLBackups\" >> CleanupTime = 168 >> ChangeBackupType = $true >> Compress = \"ForceOn\" >> Verify = \"ForceOn\" >> CheckSum = \"ForceOn\" >> } PS C:\\> Install-DbaMaintenanceSolution @params Installs Ola Hallengren's Solution with backup jobs that include automatic backup type conversion, compression, verification, and checksum validation. The ChangeBackupType parameter ensures differential and log backups automatically become full backups if a full backup is missing. Backups are compressed, verified after creation, and validated with checksums for maximum data integrity. Required Parameters -SqlInstance The target SQL Server instance onto which the Maintenance Solution will be installed. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database where Ola Hallengren's maintenance solution objects will be installed. Defaults to master. Consider using a dedicated DBA or maintenance database instead of master to keep system databases clean and simplify backup strategies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | master | -BackupLocation Sets the root directory path where backup files will be stored by the maintenance jobs. Defaults to the instance's default backup location. Specify this when you need backups in a specific location for storage policies, network shares, or disk space management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CleanupTime Defines retention period in hours before backup files are automatically deleted by cleanup jobs. Only used when InstallJobs is specified. Common values: 168 hours (1 week), 720 hours (30 days), or 2160 hours (90 days). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -OutputFileDirectory Sets the directory path where SQL Agent jobs will write their output log files during maintenance operations. Use this to centralize job output logs for monitoring and troubleshooting maintenance activities. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ReplaceExisting Forces replacement of existing Ola Hallengren objects including stored procedures and SQL Agent jobs. Use this when upgrading to newer versions of the maintenance solution or when previous installations need to be refreshed. CommandLog and Queue tables are only dropped when LogToTable or InstallParallel switches are also specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LogToTable Enables command logging to the CommandLog table for tracking maintenance operation history and performance. Essential for monitoring backup completion times, index maintenance duration, and troubleshooting failed operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Solution Determines which maintenance components to install: All, Backup, IntegrityCheck, or IndexOptimize. Use specific components when you only need certain maintenance functions or want to install different parts on different servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | All | | Accepted Values | All,Backup,IntegrityCheck,IndexOptimize | -InstallJobs Creates pre-configured SQL Agent jobs for automated execution of backup, integrity check, and index maintenance tasks. Without this switch, only the stored procedures are installed and must be scheduled manually or called from custom jobs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AutoScheduleJobs Automatically creates optimized job schedules for backup operations when InstallJobs is specified. Valid values: WeeklyFull, DailyFull, NoDiff, FifteenMinuteLog, HourlyLog. Specify exactly one full backup cadence, WeeklyFull or DailyFull, and optionally combine it with NoDiff, FifteenMinuteLog, or HourlyLog. WeeklyFull creates weekly full backups, daily differentials, and 15-minute log backups. DailyFull skips differentials. Use HourlyLog for less frequent transaction log backups. System databases are always backed up daily regardless of user database schedule. Automatically resolves schedule conflicts by adjusting start times. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | WeeklyFull,DailyFull,NoDiff,FifteenMinuteLog,HourlyLog | -StartTime Sets the preferred start time for automatically scheduled jobs in HHMMSS format. Defaults to 011500 (1:15 AM). The system automatically adjusts this time if conflicts exist with other scheduled jobs. Choose off-peak hours to minimize impact on production workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 011500 | -LocalFile Specifies path to a local zip file containing Ola Hallengren's maintenance solution instead of downloading from GitHub. Use this in environments without internet access or when you need to install a specific version for consistency across multiple servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Forces fresh download of the maintenance solution from GitHub, bypassing any locally cached version. Use this to ensure you're installing the latest version when the cache might contain an older release. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InstallParallel Creates Queue and QueueDatabase tables required for parallel execution of maintenance operations across multiple databases. Enable this when you have many databases and want to run maintenance tasks concurrently to reduce overall completion time. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ChangeBackupType Enables automatic backup type conversion when a full backup is missing. When enabled, differential backups automatically become full backups, and log backups become full or differential backups as appropriate. Only applies when InstallJobs is specified. This ensures backup chains remain valid even if scheduled full backups fail or are missed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Compress Controls backup compression in job commands. Valid values: Default, ForceOn, ForceOff, Remove. Default: does not include @Compress in job text, so the SQL Server instance's compression setting applies. ForceOn: explicitly sets @Compress = 'Y' in job commands. ForceOff: explicitly sets @Compress = 'N' in job commands. Remove: removes @Compress from job commands if present. Only applies when InstallJobs is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Default | | Accepted Values | Default,ForceOn,ForceOff,Remove | -CopyOnly Creates copy-only backups that do not affect the normal backup sequence. Copy-only backups do not break the differential backup chain and are ideal for ad-hoc backups, backup verification, or sending backups to external systems without impacting regular backup schedules. Only applies when InstallJobs is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Verify Controls backup verification in job commands. Valid values: Default, ForceOn, ForceOff, Remove. Default: uses Ola's default, which includes @Verify = 'Y' in job commands. ForceOn: explicitly sets @Verify = 'Y' in job commands. ForceOff: explicitly sets @Verify = 'N' in job commands. Remove: removes @Verify from job commands, letting the stored procedure's built-in default apply. Only applies when InstallJobs is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Default | | Accepted Values | Default,ForceOn,ForceOff,Remove | -CheckSum Controls checksum validation in job commands. Valid values: Default, ForceOn, ForceOff, Remove. Default: uses Ola's default, which includes @Checksum = 'Y' in job commands. ForceOn: explicitly sets @Checksum = 'Y' in job commands. ForceOff: explicitly sets @Checksum = 'N' in job commands. Remove: removes @Checksum from job commands, letting the stored procedure's built-in default apply. Only applies when InstallJobs is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Default | | Accepted Values | Default,ForceOn,ForceOff,Remove | -ModificationLevel Specifies minimum modification percentage required before ChangeBackupType converts a differential backup to full backup. Valid range: 0-100. Use this with ChangeBackupType to control when backup type changes occur based on data modification levels. Only applies when InstallJobs is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance where the maintenance solution was installed. Each object contains installation result information. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Results: Status of the installation (\"Success\" or \"Failed\") Only returns output when installation actually executes (not during WhatIf). When using -WhatIf, no output is generated. &nbsp;"
  },
  {
    "name": "Install-DbaMultiTool",
    "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/",
    "category": "Utilities",
    "tags": [
      "community",
      "dbamultitool"
    ],
    "verb": "Install",
    "popular": false,
    "url": "/Install-DbaMultiTool",
    "popularityRank": 102,
    "synopsis": "Installs five essential T-SQL stored procedures for database documentation, index optimization, and administrative tasks.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Install-DbaMultiTool View Source John McCall (@lowlydba), lowlydba.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Installs five essential T-SQL stored procedures for database documentation, index optimization, and administrative tasks. 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. The installed procedures include: â€¢ sp_helpme - Enhanced version of sp_help that provides detailed object information â€¢ sp_doc - Generates comprehensive database documentation â€¢ sp_sizeoptimiser - Analyzes and recommends optimal database file sizing â€¢ sp_estindex - Estimates potential storage savings from index compression â€¢ sp_help_revlogin - Creates scripts to recreate logins with their original SIDs and passwords These 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. DBA MultiTool links: https://dba-multitool.org https://github.com/LowlyDBA/dba-multitool/ Syntax Install-DbaMultiTool [-SqlInstance] [[-SqlCredential] ] [[-Branch] ] [[-Database] ] [[-LocalFile] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Logs into server1 with Windows authentication and then installs the DBA MultiTool in the main database PS C:\\> Install-DbaMultiTool -SqlInstance server1 -Database main Example 2: Logs into server1\\instance1 with Windows authentication and then installs the DBA MultiTool in the DBA... PS C:\\> Install-DbaMultiTool -SqlInstance server1\\instance1 -Database DBA Logs into server1\\instance1 with Windows authentication and then installs the DBA MultiTool in the DBA database. Example 3: Logs into server1\\instance1 with SQL authentication and then installs the DBA MultiTool in the main database PS C:\\> Install-DbaMultiTool -SqlInstance server1\\instance1 -Database main -SqlCredential $cred Example 4: Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs... PS C:\\> Install-DbaMultiTool -SqlInstance sql2016\\standardrtm, sql2016\\sqlexpress, sql2014 Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs the DBA MultiTool in the main database. Example 5: Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs... PS C:\\> $servers = \"sql2016\\standardrtm\", \"sql2016\\sqlexpress\", \"sql2014\" PS C:\\> $servers | Install-DbaMultiTool Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs the DBA MultiTool in the main database. Example 6: Installs the development branch version of the DBA MultiTool in the main database on sql2016 instance PS C:\\> Install-DbaMultiTool -SqlInstance sql2016 -Branch development Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Branch Specifies which branch of the DBA MultiTool repository to download and install. Defaults to 'main' for stable releases. Use 'development' only when you need to test upcoming features or bug fixes before they are officially released. The development branch may contain untested code and should not be used in production environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | main | | Accepted Values | main,development | -Database Specifies the target database where the five DBA MultiTool stored procedures will be installed. Defaults to 'master' database if not specified. Choose a dedicated DBA or utility database to keep administrative procedures organized and separate from application databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | master | -LocalFile Specifies the path to a local zip file containing the DBA MultiTool scripts instead of downloading from GitHub. Use 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. The file must be the official zip distribution from the DBA MultiTool maintainers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Forces a fresh download of the DBA MultiTool from GitHub, ignoring any locally cached version. Use this when you need to ensure you have the absolute latest version or when troubleshooting installation issues with cached files. Without this switch, the function will use the cached version if it exists to improve performance and reduce network usage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts to confirm actions. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per stored procedure installed, providing installation details and status. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The target database where the stored procedures were installed Name: The name of the installed stored procedure (sp_helpme, sp_doc, sp_sizeoptimiser, sp_estindex, or sp_help_revlogin) Status: The installation status - \"Installed\" for newly installed procedures, \"Updated\" for procedures that were updated, or \"Error\" if the installation failed &nbsp;"
  },
  {
    "name": "Install-DbaSqlPackage",
    "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's 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.",
    "category": "Advanced Features",
    "tags": [
      "deployment",
      "install"
    ],
    "verb": "Install",
    "popular": false,
    "url": "/Install-DbaSqlPackage",
    "popularityRank": 696,
    "synopsis": "Installs Microsoft SqlPackage utility required for database deployment and DACPAC operations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Install-DbaSqlPackage View Source Chrissy LeMaire and Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Installs Microsoft SqlPackage utility required for database deployment and DACPAC operations 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. SqlPackage is Microsoft's 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. Cross-platform support: Windows: Supports both ZIP (portable) and MSI installation methods Linux/macOS: Supports ZIP installation method only By 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. For AllUsers (LocalMachine) scope on Windows, you can use the MSI installer which requires administrative privileges and provides system-wide access. Writes to dbatools data directory by default for CurrentUser scope. Syntax Install-DbaSqlPackage [[-Path] ] [[-Scope] ] [[-Type] ] [[-LocalFile] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Downloads SqlPackage ZIP and extracts it to the dbatools directory for the current user PS C:\\> Install-DbaSqlPackage Example 2: Downloads and installs SqlPackage MSI for all users (requires administrative privileges) PS C:\\> Install-DbaSqlPackage -Scope AllUsers -Type Msi Example 3: Downloads SqlPackage ZIP and extracts it to C:\\SqlPackage PS C:\\> Install-DbaSqlPackage -Path C:\\SqlPackage Example 4: Installs SqlPackage from the local ZIP file PS C:\\> Install-DbaSqlPackage -LocalFile C:\\temp\\sqlpackage.zip Optional Parameters -Path Specifies the custom directory path where SqlPackage will be extracted or installed. Use this when you need SqlPackage in a specific location for CI/CD pipelines, shared tools directories, or portable deployments. If not specified, defaults to the dbatools data directory for CurrentUser scope or system location for AllUsers scope. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Scope Controls whether SqlPackage is installed for the current user only or system-wide for all users. Use CurrentUser (default) for personal use or when you lack admin rights. Use AllUsers for shared servers where multiple DBAs need access to SqlPackage. AllUsers requires administrative privileges on Windows and installs to Program Files via MSI or /usr/local/sqlpackage on Unix systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | CurrentUser | | Accepted Values | CurrentUser,AllUsers | -Type Determines the installation method for SqlPackage deployment. Use Zip (default) for portable installations that don't require admin rights and work on all platforms. Use Msi for Windows system-wide installations with proper registry integration. MSI installations require AllUsers scope and administrative privileges but provide better integration with Windows software management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Zip | | Accepted Values | Zip,Msi | -LocalFile Specifies the path to a pre-downloaded SqlPackage installation file (MSI or ZIP format). Use this in air-gapped environments or when you've already downloaded SqlPackage for offline installation. Useful for corporate environments where direct internet downloads are restricted or when installing the same version across multiple servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Forces re-download and reinstallation of SqlPackage even if it already exists in the target location. Use this when you need to update to the latest version, fix a corrupted installation, or ensure you have a clean SqlPackage deployment. Without this switch, the function will skip installation if SqlPackage is already detected in the destination path. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns installation details when SqlPackage is successfully installed. If 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. Properties: Name: The executable name - \"sqlpackage\" on Unix platforms, \"SqlPackage.exe\" on Windows Path: The full file path to the installed SqlPackage executable Installed: Boolean value of $true indicating successful installation &nbsp;"
  },
  {
    "name": "Install-DbaSqlWatch",
    "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/",
    "category": "Utilities",
    "tags": [
      "community",
      "sqlwatch"
    ],
    "verb": "Install",
    "popular": true,
    "url": "/Install-DbaSqlWatch",
    "popularityRank": 45,
    "synopsis": "Installs or updates SqlWatch monitoring solution on SQL Server instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Install-DbaSqlWatch View Source Ken K (github.com/koglerk) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Installs or updates SqlWatch monitoring solution on SQL Server instances. 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. This 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. The 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. More information: https://sqlwatch.io/ Syntax Install-DbaSqlWatch [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-LocalFile] ] [-PreRelease] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Logs into server1 with Windows authentication and then installs SqlWatch in the SQLWATCH database PS C:\\> Install-DbaSqlWatch -SqlInstance server1 Example 2: Logs into server1\\instance1 with Windows authentication and then installs SqlWatch in the DBA database PS C:\\> Install-DbaSqlWatch -SqlInstance server1\\instance1 -Database DBA Example 3: Logs into server1\\instance1 with SQL authentication and then installs SqlWatch in the DBA database PS C:\\> Install-DbaSqlWatch -SqlInstance server1\\instance1 -Database DBA -SqlCredential $cred Example 4: Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs... PS C:\\> Install-DbaSqlWatch -SqlInstance sql2016\\standardrtm, sql2016\\sqlexpress, sql2014 Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs SqlWatch in the SQLWATCH database. Example 5: $servers | Install-DbaSqlWatch Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows... PS C:\\> $servers = \"sql2016\\standardrtm\", \"sql2016\\sqlexpress\", \"sql2014\" $servers | Install-DbaSqlWatch Logs into sql2016\\standardrtm, sql2016\\sqlexpress and sql2014 with Windows authentication and then installs SqlWatch in the SQLWATCH database. Required Parameters -SqlInstance SQL Server name or SMO object representing the SQL Server to connect to. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target database where SqlWatch objects will be created and performance data will be stored. Defaults to SQLWATCH. Use this when you want to install SqlWatch into an existing database alongside other monitoring tools or when following specific naming conventions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when you have offline environments, want to control the specific version being deployed, or need to install from a pre-approved software repository. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PreRelease Downloads and installs the latest pre-release (beta) version of SqlWatch instead of the stable release branch. Use this when you need to test new features or bug fixes that haven't been released yet, but avoid in production environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Forces re-download of SqlWatch from GitHub even if a cached copy already exists locally in the dbatools data directory. Use this when you need to ensure you have the absolute latest version or when troubleshooting installation issues with potentially corrupted cached files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts to confirm actions | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance where SqlWatch is installed or updated. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name in computer\\instance format Database: The target database where SqlWatch was installed or updated Status: The deployment status extracted from DACPAC publication results DashboardPath: The full local file system path to the SqlWatch Dashboard directory for web UI access &nbsp;"
  },
  {
    "name": "Install-DbaWhoIsActive",
    "description": "Installs Adam Machanic's 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",
    "category": "Utilities",
    "tags": [
      "community",
      "whoisactive"
    ],
    "verb": "Install",
    "popular": false,
    "url": "/Install-DbaWhoIsActive",
    "popularityRank": 123,
    "synopsis": "Downloads and installs sp_WhoIsActive stored procedure for real-time SQL Server session monitoring",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Install-DbaWhoIsActive View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Downloads and installs sp_WhoIsActive stored procedure for real-time SQL Server session monitoring Description Installs Adam Machanic's 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. The 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. This 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. For more information about sp_WhoIsActive, visit http://whoisactive.com and http://sqlblog.com/blogs/adam_machanic/archive/tags/who+is+active/default.aspx Please consider donating to Adam if you find this stored procedure helpful: http://tinyurl.com/WhoIsActiveDonate Syntax Install-DbaWhoIsActive [-SqlInstance] [-SqlCredential ] [-LocalFile ] [-Database ] [-EnableException] [-Force] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Downloads sp_WhoisActive from the internet and installs to sqlserver2014a&#39;s master database PS C:\\> Install-DbaWhoIsActive -SqlInstance sqlserver2014a -Database master Downloads sp_WhoisActive from the internet and installs to sqlserver2014a's master database. Connects to SQL Server using Windows Authentication. Example 2: Pops up a dialog box asking which database on sqlserver2014a you want to install the procedure into PS C:\\> Install-DbaWhoIsActive -SqlInstance sqlserver2014a -SqlCredential $cred Pops up a dialog box asking which database on sqlserver2014a you want to install the procedure into. Connects to SQL Server using SQL Authentication. Example 3: Installs sp_WhoisActive to sqlserver2014a&#39;s master database from the local file sp_WhoIsActive.sql PS C:\\> Install-DbaWhoIsActive -SqlInstance sqlserver2014a -Database master -LocalFile c:\\SQLAdmin\\sp_WhoIsActive.sql Installs sp_WhoisActive to sqlserver2014a's master database from the local file sp_WhoIsActive.sql. You can download this file from https://github.com/amachanic/sp_whoisactive/blob/master/sp_WhoIsActive.sql Example 4: Installs sp_WhoisActive to sqlserver2014a&#39;s master database from the local file sp_whoisactive-12.00.zip PS C:\\> Install-DbaWhoIsActive -SqlInstance sqlserver2014a -Database master -LocalFile c:\\SQLAdmin\\sp_whoisactive-12.00.zip Installs sp_WhoisActive to sqlserver2014a's master database from the local file sp_whoisactive-12.00.zip. You can download this file from https://github.com/amachanic/sp_whoisactive/releases Example 5: Installs sp_WhoisActive to all servers within CMS PS C:\\> $instances = Get-DbaRegServer sqlserver PS C:\\> Install-DbaWhoIsActive -SqlInstance $instances -Database master Required Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2005 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when your SQL Server instances don't have internet access, when you need to deploy a specific version, or when you have customized the procedure. If not specified, the function automatically downloads the latest version from the official GitHub repository. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database where sp_WhoIsActive will be installed. Defaults to master database if not specified in interactive mode. Installing in master makes the procedure available server-wide, while installing in a user database limits access to that database only. When running unattended or in scripts, this parameter is mandatory to avoid interactive prompts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Forces a fresh download of sp_WhoIsActive from GitHub, bypassing any locally cached version. Use this when you need to ensure you have the absolute latest version or when troubleshooting installation issues with cached files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance where sp_WhoIsActive was installed or updated. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database where sp_WhoIsActive was installed Name: Always 'sp_WhoisActive', the name of the installed stored procedure Version: The version of sp_WhoIsActive that was installed (extracted from the procedure source code) Status: String indicating 'Installed' for new installations or 'Updated' if the procedure already existed &nbsp;"
  },
  {
    "name": "Invoke-DbaAdvancedInstall",
    "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.",
    "category": "Utilities",
    "tags": [
      "deployment",
      "install",
      "patching"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaAdvancedInstall",
    "popularityRank": 168,
    "synopsis": "Executes SQL Server installation on a single computer with automated restart handling.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Invoke-DbaAdvancedInstall View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Executes SQL Server installation on a single computer with automated restart handling. 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. Syntax Invoke-DbaAdvancedInstall [[-ComputerName] ] [[-InstanceName] ] [[-Port] ] [[-InstallationPath] ] [[-ConfigurationPath] ] [[-ArgumentList] ] [[-Version] ] [[-Configuration] ] [[-Restart] ] [[-PerformVolumeMaintenanceTasks] ] [[-SaveConfiguration] ] [[-Authentication] ] [[-Credential] ] [[-SaCredential] ] [-NoPendingRenameCheck] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Invokes update actions on SQL1 after restarting it PS C:\\> Invoke-DbaAdvancedUpdate -ComputerName SQL1 -Action $actions Optional Parameters -ComputerName Specifies the target computer where SQL Server will be installed. Can be a hostname, FQDN, or IP address for remote installations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InstanceName Specifies the name for the SQL Server instance being installed. Use 'MSSQLSERVER' for the default instance or provide a custom name for named instances. This parameter is used for post-installation configuration like port changes and service restarts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Port Sets the TCP port for the SQL Server instance after installation completes. Use this when you need a specific port for firewall rules or application connectivity requirements. The service will be automatically restarted to apply the new port setting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InstallationPath Specifies the full path to the SQL Server setup.exe file. This should point to the setup.exe in your SQL Server installation media or extracted ISO. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ConfigurationPath Specifies the path to the SQL Server configuration file (Configuration.ini) on the local machine. This file contains all installation settings and will be copied to the target computer during remote installations. Generate this file using SQL Server Installation Center or create it manually with your desired settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ArgumentList Provides additional command-line arguments to pass directly to setup.exe. Use this for installation options not covered by other parameters, such as /IACCEPTSQLSERVERLICENSETERMS. These arguments supplement the configuration file settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Version Specifies the SQL Server version being installed using the canonical version number. Examples: 10.50 for SQL Server 2008 R2, 11.0 for SQL Server 2012, 13.0 for SQL Server 2016. This helps the function locate installation logs and perform version-specific operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Configuration A hashtable with custom configuration items that you want to use during the installation. Overrides all other parameters. For example, to define a custom server collation you can use the following parameter: PS> Install-DbaInstance -Version 2017 -Configuration @{ SQLCOLLATION = 'Latin1_General_BIN' } Full 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 | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Restart Automatically restarts the target computer when required by the SQL Server installation and waits for it to come back online. Essential for multi-instance installations since most SQL Server components require a restart to complete installation. Without this parameter, you must manually restart the computer when installation exit code 3010 is returned. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -PerformVolumeMaintenanceTasks Grants the SQL Server service account the 'Perform Volume Maintenance Tasks' privilege after installation. This enables instant file initialization, significantly improving database file creation and growth performance. Recommended for production environments where large databases are created or restored frequently. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SaveConfiguration Specifies a path where the installation configuration file will be saved for future reference. Use this to preserve your installation settings for documentation or to replicate the same configuration on other servers. The temporary configuration file is normally deleted after installation completes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Authentication Specifies the authentication protocol for PowerShell remoting to the target computer. CredSSP is used by default when credentials are provided to handle network share access during installation. Change to Kerberos or Negotiate if your environment restricts CredSSP usage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Credssp | | Accepted Values | Default,Basic,Negotiate,NegotiateWithImplicitCredential,Credssp,Digest,Kerberos | -Credential Windows Credential with permission to log on to the remote server. Must be specified for any remote connection if installation media is located on a network folder. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SaCredential Provides the sa account password when installing SQL Server with mixed mode authentication. Pass a PSCredential object with 'sa' as the username and your desired password. Required only when your configuration file specifies mixed mode authentication (SECURITYMODE=SQL). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoPendingRenameCheck Skips the check for pending file rename operations when determining if a reboot is required. Use this switch if you encounter false positive reboot requirements due to pending renames that don't affect SQL Server installation. Only disable this check if you're certain no critical system files are waiting to be renamed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object with detailed installation results and status information. Default display properties (via Select-DefaultView): ComputerName: The target computer where SQL Server was installed InstanceName: The SQL Server instance name Version: The SQL Server version being installed Port: The TCP port configured for the instance (nullable int) Successful: Boolean indicating if the installation completed successfully Restarted: Boolean indicating if the computer was restarted during installation Installer: The path to the SQL Server setup.exe file used ExitCode: The exit code returned by setup.exe (nullable int, 0 = success, 3010 = reboot required) LogFile: The full path to the installation Summary.txt log file Notes: Array of messages about installation warnings, errors, or post-installation actions Additional properties available: SACredential: The SA credential provided (if mixed-mode authentication was used) Configuration: The hashtable of configuration settings used for installation ExitMessage: Detailed exit message extracted from the installation summary Log: Full contents of the installation Summary.txt file (array of strings) ConfigurationFile: Path to the ConfigurationFile.ini used during installation &nbsp;"
  },
  {
    "name": "Invoke-DbaAdvancedRestore",
    "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't 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't 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.",
    "category": "Backup & Restore",
    "tags": [
      "restore",
      "backup"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaAdvancedRestore",
    "popularityRank": 142,
    "synopsis": "Executes database restores from processed BackupHistory objects with advanced customization options",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaAdvancedRestore View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Executes database restores from processed BackupHistory objects with advanced customization options 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't handled by the standard Restore-DbaDatabase command. The typical pipeline flow is: Get-DbaBackupInformation | Select-DbaBackupInformation | Format-DbaBackupInformation | Test-DbaBackupInformation | Invoke-DbaAdvancedRestore This 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. Most 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't available in the simplified commands. Always validate your BackupHistory objects with Test-DbaBackupInformation before using this function to ensure the restore chain is logically consistent. Syntax Invoke-DbaAdvancedRestore [-BackupHistory] [[-SqlInstance] ] [[-SqlCredential] ] [-OutputScriptOnly] [-VerifyOnly] [[-RestoreTime] ] [[-StandbyDirectory] ] [-NoRecovery] [[-MaxTransferSize] ] [[-BlockSize] ] [[-BufferCount] ] [-Continue] [[-StorageCredential] ] [-WithReplace] [-KeepReplication] [-KeepCDC] [-ErrorBrokerConversations] [[-PageRestore] ] [[-ExecuteAs] ] [-StopBefore] [[-StopMark] ] [[-StopAfterDate] ] [[-StopAtLsn] ] [-Checksum] [-Restart] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Will restore all the backups in the BackupHistory object according to the transformations it contains PS C:\\> $BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance Example 2: First generates just the T-SQL restore scripts so they can be sanity checked, and then if they are good... PS C:\\> $BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance -OutputScriptOnly PS C:\\> $BackupHistory | Invoke-DbaAdvancedRestore -SqlInstance MyInstance First generates just the T-SQL restore scripts so they can be sanity checked, and then if they are good perform the full restore. By reusing the BackupHistory object there is no need to rescan all the backup files again Required Parameters -BackupHistory Processed BackupHistory objects from the dbatools restore pipeline containing backup file metadata and restore instructions. Typically comes from Format-DbaBackupInformation after running Get-DbaBackupInformation and Select-DbaBackupInformation. Each object contains the backup file paths, database name, file relocations, and sequencing information needed for the restore operation. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlInstance The SqlInstance to which the backups should be restored | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OutputScriptOnly Generates T-SQL RESTORE scripts without executing them, allowing you to review the commands before running. Useful for validating complex restores, creating deployment scripts, or troubleshooting restore logic. The generated scripts can be saved and executed manually or through other automation tools. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -VerifyOnly Performs RESTORE VERIFYONLY operations to check backup file integrity without actually restoring the database. Use this to validate backup files are readable and not corrupted before attempting a full restore. Particularly valuable when testing backup files from different environments or after transferring backup files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -RestoreTime Specifies the exact point-in-time for log restore operations when performing point-in-time recovery. Use this for recovering to a specific moment before data corruption or unwanted changes occurred. Must be within the timeframe covered by your transaction log backups and should match the value used in earlier pipeline stages. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-Date).AddDays(2) | -StandbyDirectory Directory path where SQL Server creates standby files for read-only access during restore operations. Puts the database in standby mode, allowing read-only queries while maintaining the ability to apply additional transaction log restores. Commonly used for log shipping warm standby servers or when you need to query data during a staged restore process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoRecovery Leaves the database in RESTORING state after the operation, allowing additional transaction log restores to be applied. Essential for point-in-time recovery scenarios where you need to apply multiple transaction log backups sequentially. The database remains inaccessible until a final restore operation is performed WITH RECOVERY. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MaxTransferSize Sets the maximum amount of data transferred between SQL Server and backup devices in each read operation. Specify in bytes as a multiple of 64KB to optimize restore performance for large databases or slow storage. Higher values can improve performance but use more memory; typically ranges from 64KB to 4MB depending on your system. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BlockSize Physical block size used for backup device I/O operations, must be 512, 1024, 2048, 4096, 8192, 16384, 32768, or 65536 bytes. Should match the block size used when the backup was created to avoid performance issues. Most backups use the default 64KB unless created with specific block size requirements for tape devices or storage optimization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BufferCount Number of I/O buffers SQL Server uses during the restore operation to improve throughput. Higher buffer counts can speed up restores for large databases, especially when reading from multiple backup files. Typically ranges from 2 to 64 buffers depending on available memory and restore performance requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Continue Continues a previously started restore sequence where the database is already in RESTORING or STANDBY state. Use this when applying additional transaction log backups to a database that was restored WITH NORECOVERY. Automatically enables WithReplace to allow the operation on existing database objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -StorageCredential Name of the SQL Server credential object required to access backup files stored in Azure Blob Storage or S3-compatible object storage. The credential must already exist on the target SQL Server instance with proper access keys for the storage account. For Azure: The credential must contain valid Azure storage account keys or SAS tokens. For S3: The credential must use Identity = 'S3 Access Key' and Secret = 'AccessKeyID:SecretKeyID'. Requires SQL Server 2022 or higher. | Property | Value | | --- | --- | | Alias | AzureCredential,S3Credential | | Required | False | | Pipeline | false | | Default Value | | -WithReplace Allows the restore operation to overwrite an existing database with the same name. Without this parameter, the restore will fail if a database with the target name already exists on the instance. Commonly used during database migrations, refresh operations, or when restoring over development/test databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepReplication Preserves replication settings when restoring a database that was part of a replication topology. Use this when restoring a replicated database to maintain publisher, subscriber, or distributor configurations. Without this parameter, replication metadata is removed during the restore process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepCDC Preserves Change Data Capture (CDC) configuration and metadata during database restore operations. Essential when restoring databases where CDC is actively capturing data changes for auditing or ETL processes. Cannot be combined with NoRecovery or StandbyDirectory parameters as CDC requires the database to be fully recovered. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ErrorBrokerConversations Ends all conversations in the database with an error message when restoring, using the ERROR_BROKER_CONVERSATIONS option. Use this when you want to clean up Service Broker conversations that may be left in an inconsistent state after a restore. Only applied during the final restore step (WITH RECOVERY), not during intermediate log restores. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -PageRestore Array of page objects from Get-DbaSuspectPage specifying corrupted pages to restore using page-level restore. Use this for targeted repair of specific corrupted pages without restoring the entire database. Each object should contain FileId and PageID properties identifying the exact pages needing restoration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExecuteAs SQL Server login name to impersonate during the restore operation, affecting database ownership. When specified, the restore runs under this login context, making them the database owner. Typically used to ensure specific ownership patterns or when the current login lacks sufficient permissions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StopBefore Stops the restore operation just before the specified StopMark or StopAtLsn rather than after it. Use this when you need to exclude a particular marked transaction or LSN from the restored database. Only effective when used in combination with the StopMark or StopAtLsn parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -StopMark Named transaction mark in the transaction log where the restore operation should stop. Use this for precise point-in-time recovery to a specific marked transaction, typically created with BEGIN TRAN WITH MARK. Provides more granular control than timestamp-based recovery for critical business operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StopAfterDate DateTime value specifying that only StopMark occurrences after this date should be considered for restore termination. Use this when the same mark name appears multiple times in your transaction log backups. Ensures the restore stops at the correct instance of the mark when identical mark names exist at different times. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StopAtLsn Log Sequence Number (LSN) in the transaction log at which to stop the restore operation. Use this for precise point-in-time recovery to an exact LSN, which provides more granular control than timestamp-based recovery. Accepts either the numeric restore format used by SQL Server or the colon-delimited format returned by sys.fn_dblog. Combine with -StopBefore to stop just before the specified LSN. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Checksum Enables backup checksum verification during restore operations. Forces the restore to verify backup checksums and fail if checksums are not present. Use this to ensure backup files contain checksums and validate them during restore, following backup best practices. Without this parameter, SQL Server verifies checksums if present but doesn't fail if checksums are missing. With this parameter, the operation fails if checksums are not present in the backup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Restart Instructs the restore operation to restart an interrupted restore sequence. Use this when a previous restore operation was interrupted due to a reboot, service failure, or other system event. Allows resuming large transaction log restores that were partially completed before interruption. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (default operation) Returns one object per backup file processed in the restore sequence, containing comprehensive restore operation details and status. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance where the restore occurred InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) BackupFile: Comma-separated list of backup file paths processed in this restore operation BackupFilesCount: Number of backup files included in the restore operation (int) BackupSize: Total size of backup files; dbasize object convertible to Bytes, KB, MB, GB, TB CompressedBackupSize: Compressed size of backup files if available in backup metadata Database: The name of the database being restored Owner: The database owner, typically the login that performed the restore DatabaseRestoreTime: Total elapsed time for the complete database restore operation (TimeSpan) FileRestoreTime: Elapsed time for the current backup file restore (TimeSpan) NoRecovery: Boolean indicating if the database was left in RESTORING state for log restore sequences RestoreComplete: Boolean indicating if the restore operation completed successfully RestoredFile: Comma-separated list of logical file names restored to the database RestoredFilesCount: Number of files restored in the database (int) Script: The T-SQL RESTORE script executed or generated (populated when actual T-SQL is run or when OutputScriptOnly is used) RestoreDirectory: Directory path(s) where the restored database files are located on the target server WithReplace: Boolean indicating if the restore was performed with the REPLACE option to overwrite existing database Additional properties available: DatabaseName: Alternate property containing the database name (duplicate of Database) DatabaseOwner: Alternate property containing the database owner (duplicate of Owner) BackupSizeMB: Backup size expressed in megabytes (double) CompressedBackupSizeMB: Compressed backup size expressed in megabytes (double) RestoredFileFull: Full physical paths of all restored files separated by commas BackupStartTime: DateTime when the backup operation started BackupEndTime: DateTime when the backup operation completed RestoreTargetTime: Target point-in-time for log recovery operations, or string \"Latest\" if restoring to current time BackupFileRaw: Raw array of all backup file paths without string conversion ExitError: Any exception object that occurred during restoration KeepReplication: Boolean indicating if replication settings were preserved during restore SACredential: The SA credential passed (if applicable) System.String (when -VerifyOnly is specified) Returns verification result strings: \"Verify successful\" or \"Verify failed\" System.String (when -OutputScriptOnly is specified) Returns 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. &nbsp;"
  },
  {
    "name": "Invoke-DbaAdvancedUpdate",
    "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.",
    "category": "Utilities",
    "tags": [
      "deployment",
      "install",
      "patching",
      "update"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaAdvancedUpdate",
    "popularityRank": 222,
    "synopsis": "Installs SQL Server updates and patches on remote computers with automatic restart management",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Invoke-DbaAdvancedUpdate View Source Kirill Kravtsov (@nvarscar) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Installs SQL Server updates and patches on remote computers with automatic restart management 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. Syntax Invoke-DbaAdvancedUpdate [[-ComputerName] ] [[-Action] ] [[-Restart] ] [[-Authentication] ] [[-Credential] ] [[-ExtractPath] ] [[-ArgumentList] ] [-NoPendingRenameCheck] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Invokes update actions on SQL1 after restarting it PS C:\\> Invoke-DbaAdvancedUpdate -ComputerName SQL1 -Action $actions Example 2: Extracts required files to the specific location &quot;C:\\temp&quot; PS C:\\> Invoke-DbaAdvancedUpdate -ComputerName SQL1 -Action $actions -ExtractPath C:\\temp Extracts required files to the specific location \"C:\\temp\". Invokes update actions on SQL1 after restarting it. Optional Parameters -ComputerName Specifies the remote computer where SQL Server updates will be installed. This function handles the actual installation process after Update-DbaInstance creates the action plan. Must have WinRM enabled and accessible for remote operations including file extraction and system restarts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Action Contains the update action plan objects created by Update-DbaInstance with details for each KB to install. Each action includes properties like TargetLevel, KB number, Installer path, MajorVersion, Build, and InstanceName. Multiple actions can be processed sequentially to chain-install several updates with automatic restarts between each. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Restart Automatically restarts the target computer after successful patch installation and waits for it to come back online. Required for installing multiple patches in sequence, as each SQL Server update typically requires a system restart to complete. Also handles pre-installation restarts when pending reboots are detected before beginning the update process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Authentication Specifies the WinRM authentication protocol for remote connections to the target computer. Defaults to CredSSP when credentials are provided to handle network share access and avoid double-hop authentication issues. Use Default authentication only for local operations, as network-based update repositories require credential delegation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Credssp | | Accepted Values | Default,Basic,Negotiate,NegotiateWithImplicitCredential,Credssp,Digest,Kerberos | -Credential Windows Credential with permission to log on to the remote server. Must be specified for any remote connection if update Repository is located on a network folder. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExtractPath Specifies the directory path where update files will be extracted on the target computer. If not specified, automatically selects the drive with the most free space for extraction. Use this when you need to control extraction location for space management or security requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ArgumentList Additional command-line arguments passed to the SQL Server setup.exe during installation. Commonly used for setup customization like \"/SkipRules=RebootRequiredCheck\" to bypass reboot validation or \"/Q\" for quiet mode. Arguments are automatically combined with required parameters like /quiet, /allinstances or /instancename, and /IAcceptSQLServerLicenseTerms. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoPendingRenameCheck Skips the pending file rename check when determining if a system restart is required before installation. Use this when the pending rename detection produces false positives that prevent updates from proceeding. The function will still check other restart conditions like registry entries and exit codes from previous installations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per action processed, with the following properties: TargetLevel: The target SQL Server patch level that was installed KB: The KB number of the patch that was applied Installer: Path to the KB installer file that was used MajorVersion: The major version of SQL Server (e.g., 2019, 2022) Build: The specific build number of the installation InstanceName: Name of the SQL Server instance targeted, or null if all instances were updated Successful: Boolean indicating whether the update installation completed successfully Restarted: Boolean indicating whether the computer was restarted as part of this update ExitCode: The exit code returned by the SQL Server setup.exe program ExtractPath: The directory path where update files were extracted on the target computer Log: The output log from the setup.exe installation process Notes: Array of error messages, warnings, or status notes encountered during installation &nbsp;"
  },
  {
    "name": "Invoke-DbaAgFailover",
    "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't 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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaAgFailover",
    "popularityRank": 59,
    "synopsis": "Performs manual failover of an availability group to make the target instance the new primary replica.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaAgFailover View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Performs manual failover of an availability group to make the target instance the new primary replica. 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. By 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't been synchronized to the target replica. This 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. Syntax Invoke-DbaAgFailover [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-InputObject] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Safely (no potential data loss) fails over the SharePoint AG to sql2017 PS C:\\> Invoke-DbaAgFailover -SqlInstance sql2017 -AvailabilityGroup SharePoint Safely (no potential data loss) fails over the SharePoint AG to sql2017. Prompts for confirmation. Example 2: Safely (no potential data loss) fails over the selected availability groups to sql2017 PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2017 | Out-GridView -Passthru | Invoke-DbaAgFailover -Confirm:$false Safely (no potential data loss) fails over the selected availability groups to sql2017. Does not prompt for confirmation. Example 3: Forcefully (with potential data loss) fails over the SharePoint AG to sql2017 PS C:\\> Invoke-DbaAgFailover -SqlInstance sql2017 -AvailabilityGroup SharePoint -Force Forcefully (with potential data loss) fails over the SharePoint AG to sql2017. Prompts for confirmation. Optional Parameters -SqlInstance The SQL Server instance. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies the name(s) of the availability groups to failover on the target instance. Accepts multiple availability group names. Use this when you need to failover specific availability groups rather than all groups on the instance. Required when using SqlInstance parameter to identify which availability groups should be failed over. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations. Use this approach when you want to filter or select specific availability groups before failover. Allows for more complex scenarios like failing over multiple groups across different instances in a single operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Force Performs a forced failover that allows potential data loss by not waiting for transaction synchronization. Use this during disaster recovery scenarios when the primary replica is unavailable and you need immediate failover. Without this switch, the function performs a safe failover that waits for all committed transactions to synchronize, preventing data loss. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityGroup Returns one AvailabilityGroup object per availability group that was failed over. The object reflects the new state after the failover operation completes. Default properties visible when displayed: Name: The name of the availability group PrimaryReplicaServerName: The server hosting the primary replica after failover LocalReplicaRole: The role of the local replica (Primary or Secondary) AutomatedBackupPreference: Preference for which replicas perform backups (Primary, Secondary, etc.) FailureConditionLevel: The condition level that triggers automatic failover HealthCheckTimeout: The health check interval in milliseconds BasicAvailabilityGroup: Boolean indicating if this is a basic (Enterprise-only) availability group ClusterType: The cluster type used (WSFC, External, or None) Additional properties available from the SMO AvailabilityGroup object: ID: Unique identifier for the availability group UniqueId: The globally unique identifier for the availability group AvailabilityReplicas: Collection of all replica objects in the availability group AvailabilityDatabases: Collection of databases participating in the availability group AvailabilityGroupListeners: Collection of listener endpoints configured for the availability group DatabaseReplicaStates: Collection of database states across all replicas RequiredSynchronizedSecondariesToCommit: Number of secondaries that must be synchronized before commit Use Select-Object * to access all SMO properties available on the AvailabilityGroup object. &nbsp;"
  },
  {
    "name": "Invoke-DbaBalanceDataFiles",
    "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's 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't 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\nWhen the -TargetFileGroup parameter is specified, indexes can be moved from their current filegroup\nto the specified target filegroup regardless of how many data files the current filegroup contains.\nThis allows consolidating or migrating data between filegroups.\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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "filemanagement",
      "file",
      "utility"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaBalanceDataFiles",
    "popularityRank": 353,
    "synopsis": "Re-balance data between data files",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaBalanceDataFiles View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Re-balance data between data files 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's about the same size. You may want to balance the data between all the data files. The function will check the server version and edition to see if the it allows for online index rebuilds. If the server does support it, it will try to rebuild the index online. If the server doesn't support it, it will rebuild the index offline. Be carefull though, this can cause downtime The tables must have a clustered index to be able to balance out the data. The function does NOT yet support heaps. The function will also check if the file groups are subject to balance out. A file group would have at least have 2 data files and should be writable. If a table is within such a file group it will be subject for processing. If not the table will be skipped. When the -TargetFileGroup parameter is specified, indexes can be moved from their current filegroup to the specified target filegroup regardless of how many data files the current filegroup contains. This allows consolidating or migrating data between filegroups. Note: this command does not perform a disk space check for non-Windows machines so make sure you have enough space on the disk. Syntax Invoke-DbaBalanceDataFiles [-SqlCredential ] [-Database ] [-Table ] [-TargetFileGroup ] [-RebuildOffline] [-EnableException] [-Force] [-WhatIf] [-Confirm] [ ] Invoke-DbaBalanceDataFiles -SqlInstance [-SqlCredential ] [-Database ] [-Table ] [-TargetFileGroup ] [-RebuildOffline] [-EnableException] [-Force] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: This command will distribute the data in database db1 on instance sql1 PS C:\\> Invoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 Example 2: This command will distribute the data in database db1 on instance sql1 PS C:\\> Invoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 | Select-Object -ExpandProperty DataFilesEnd Example 3: This command will distribute the data for only the tables table1,table2 and table5 PS C:\\> Invoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 -Table table1,table2,table5 Example 4: This command will consider the fact that there might be a SQL Server edition that does not support online... PS C:\\> Invoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 -RebuildOffline This command will consider the fact that there might be a SQL Server edition that does not support online rebuilds of indexes. By supplying this parameter you give permission to do the rebuilds offline if the edition does not support it. Example 5: This command will rebuild all clustered indexes into the SECONDARY filegroup, moving data from whatever... PS C:\\> Invoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 -TargetFileGroup \"SECONDARY\" This command will rebuild all clustered indexes into the SECONDARY filegroup, moving data from whatever filegroup each table currently resides in. Example 6: This command will rebuild the clustered indexes of table1 and table2 offline, moving them into the SECONDARY... PS C:\\> Invoke-DbaBalanceDataFiles -SqlInstance sql1 -Database db1 -Table table1,table2 -TargetFileGroup \"SECONDARY\" -RebuildOffline This command will rebuild the clustered indexes of table1 and table2 offline, moving them into the SECONDARY filegroup. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to balance data files for. Only databases with multiple data files can be balanced. This parameter is required since the function needs specific databases to process for data file balancing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. When omitted, all eligible tables in the database will be processed. Use this to target specific large tables that need data redistribution. | Property | Value | | --- | --- | | Alias | Tables | | Required | False | | Pipeline | false | | Default Value | | -TargetFileGroup The name of the filegroup to rebuild indexes into. When specified, indexes can be moved from their current filegroup to the target filegroup, regardless of how many data files the current filegroup contains. When not specified, the function only processes tables in filegroups with at least 2 data files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RebuildOffline Forces all clustered index rebuilds to occur offline, which redistributes data between files but blocks table access during the operation. Use this switch when you need to balance data files but can accept downtime, or when working with SQL Server editions that don't support online index operations (Standard, Express, Web). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Bypasses the disk space validation check that ensures sufficient free space exists before balancing data files. Use this when you're confident about available disk space or when working with non-Windows SQL Server instances where disk space checks may not work properly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database processed with data file balancing results. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database that was balanced Start: DateTime when the data file balancing operation started End: DateTime when the data file balancing operation completed Elapsed: The elapsed time formatted as HH:mm:ss Success: Boolean indicating if the data file balancing was successful Unsuccessful: Comma-separated list of table names that could not be balanced (empty string if all successful) DataFilesStart: Array of file objects before balancing, each containing ID, LogicalName, PhysicalName, Size, UsedSpace, AvailableSpace DataFilesEnd: Array of file objects after balancing, each containing ID, LogicalName, PhysicalName, Size, UsedSpace, AvailableSpace &nbsp;"
  },
  {
    "name": "Invoke-DbaCycleErrorLog",
    "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.",
    "category": "Server Management",
    "tags": [
      "instance",
      "errorlog",
      "logging"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaCycleErrorLog",
    "popularityRank": 577,
    "synopsis": "Cycles the current SQL Server error log and/or SQL Agent error log to start fresh log files",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaCycleErrorLog View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Cycles the current SQL Server error log and/or SQL Agent error log to start fresh log files 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. Syntax Invoke-DbaCycleErrorLog [-SqlInstance] [[-SqlCredential] ] [[-Type] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Cycles the current error log for the SQL Server Agent on SQL Server instance sql2016 PS C:\\> Invoke-DbaCycleErrorLog -SqlInstance sql2016 -Type agent Example 2: Cycles the current error log for the SQL Server instance on SQL Server instance sql2016 PS C:\\> Invoke-DbaCycleErrorLog -SqlInstance sql2016 -Type instance Example 3: Cycles the current error log for both SQL Server instance and SQL Server Agent on SQL Server instance sql2016 PS C:\\> Invoke-DbaCycleErrorLog -SqlInstance sql2016 Required Parameters -SqlInstance The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies which error log to cycle: 'instance' for SQL Server instance log, 'agent' for SQL Agent log. When omitted, cycles both logs simultaneously which is the typical maintenance approach. Use specific values when you need to manage log sizes independently or troubleshoot specific services. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | instance,agent | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per instance processed with error log cycling results. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) LogType: String array of log types that were cycled (contains 'instance', 'agent', or both) IsSuccessful: Boolean indicating if the error log cycling was successful Notes: Exception object if operation failed, null if successful &nbsp;"
  },
  {
    "name": "Invoke-DbaDbAzSqlTip",
    "description": "Executes Microsoft's 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.",
    "category": "Database Operations",
    "tags": [
      "azure",
      "database"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbAzSqlTip",
    "popularityRank": 0,
    "synopsis": "Executes Microsoft's Azure SQL performance recommendations script against Azure SQL Database instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbAzSqlTip View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Executes Microsoft's Azure SQL performance recommendations script against Azure SQL Database instances. Description Executes Microsoft's 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. The 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. By 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. Syntax Invoke-DbaDbAzSqlTip [-SqlInstance] [[-SqlCredential] ] [[-AzureDomain] ] [[-Tenant] ] [[-LocalFile] ] [[-Database] ] [[-ExcludeDatabase] ] [-AllUserDatabases] [-ReturnAllTips] [-Compat100] [[-StatementTimeout] ] [-EnableException] [-Force] [ ] &nbsp; Examples &nbsp; Example 1: Runs the Azure SQL Tips script against the dbatools1.database.windows.net using the specified credentials for... PS C:\\> Invoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -Database ImportantDb Runs the Azure SQL Tips script against the dbatools1.database.windows.net using the specified credentials for the ImportantDb. Example 2: Runs the Azure SQL Tips script against the dbatools1.database.windows.net using the specified credentials for... PS C:\\> Invoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -Database ImportantDb -ReturnAllTips Runs the Azure SQL Tips script against the dbatools1.database.windows.net using the specified credentials for the ImportantDb and will return all the tips regardless of database state. Example 3: Runs the Azure SQL Tips script that is available locally at &#39;C:\\temp\\get-sqldb-tips.sql&#39; against the... PS C:\\> Invoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -Database ImportantDb -LocalFile 'C:\\temp\\get-sqldb-tips.sql' Runs the Azure SQL Tips script that is available locally at 'C:\\temp\\get-sqldb-tips.sql' against the dbatools1.database.windows.net using the specified credentials for the ImportantDb and will return all the tips regardless of database state. Example 4: Runs the Azure SQL Tips script against all the databases on the dbatools1.database.windows.net using the... PS C:\\> Invoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -ExcludeDatabase TestDb Runs the Azure SQL Tips script against all the databases on the dbatools1.database.windows.net using the specified credentials except for TestDb. Example 5: Runs the Azure SQL Tips script against all the databases on the dbatools1.database.windows.net using the... PS C:\\> Invoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -AllUserDatabases Runs the Azure SQL Tips script against all the databases on the dbatools1.database.windows.net using the specified credentials. Example 6: Enter Azure AD username\\password into Get-Credential, and then Invoke-DbaDbAzSqlTip will runs the Azure SQL... PS C:\\> $cred = Get-Credential PS C:\\> Invoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential $cred -Database ImportantDb Enter Azure AD username\\password into Get-Credential, and then Invoke-DbaDbAzSqlTip will runs the Azure SQL Tips script against the ImportantDb database on the dbatools1.database.windows.net server using Azure AD. Example 7: Run the Azure SQL Tips script against the ImportantDb database on the dbatools1.database.windows.net server... PS C:\\> Invoke-DbaDbAzSqlTip -SqlInstance dbatools1.database.windows.net -SqlCredential (Get-Credential) -Database ImportantDb -Tenant GUID-GUID-GUID Run the Azure SQL Tips script against the ImportantDb database on the dbatools1.database.windows.net server specifying the Azure Tenant Id. Required Parameters -SqlInstance The target Azure SQL instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). SQL Server Authentication and Azure Active Directory are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AzureDomain Specifies the Azure SQL domain for connection. Defaults to database.windows.net for standard Azure SQL Database instances. Use this when connecting to Azure SQL instances in sovereign clouds like Azure Government (.usgovcloudapi.net) or Azure China (.chinacloudapi.cn). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | database.windows.net | -Tenant Specifies the Azure AD tenant ID (GUID) for authentication to Azure SQL Database. Required when using Azure Active Directory authentication with multi-tenant applications or when the default tenant cannot be determined automatically. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LocalFile Specifies the path to a local copy of the Azure SQL Tips script files instead of downloading from GitHub. Use this when you need to run a specific version, work in environments without internet access, or have customized the tips script for your organization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which Azure SQL databases to analyze for performance recommendations. Use this when you want to target specific databases rather than analyzing all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which Azure SQL databases to skip when running performance analysis. Use this with -AllUserDatabases to exclude specific databases like development or test environments from the tips analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllUserDatabases Analyzes all user databases on the Azure SQL instance for performance recommendations. Excludes the master database and automatically discovers all other databases, making it ideal for comprehensive performance audits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ReturnAllTips Returns all available performance tips regardless of current database state or configuration. By default, the script only shows relevant tips based on your database's current settings and usage patterns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Compat100 Uses a specialized version of the tips script designed for databases running compatibility level 100 (SQL Server 2008). Only use this when analyzing legacy Azure SQL databases that cannot be upgraded to newer compatibility levels. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -StatementTimeout Sets the query timeout in minutes for the Azure SQL Tips analysis script. Increase this value when analyzing large databases or instances with heavy workloads that may cause the default timeout to be exceeded. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Forces a fresh download of the Azure SQL Tips script from GitHub, bypassing any locally cached version. Use this when you want to ensure you're running the latest version or when troubleshooting issues with cached files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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, and supporting information. Properties: ComputerName: The computer name of the Azure SQL instance InstanceName: The Azure SQL instance name SqlInstance: The full Azure SQL instance name (typically servername.database.windows.net) Database: The name of the database analyzed for the tip tip_id: Unique identifier for the specific performance recommendation description: Text description of the performance optimization being recommended confidence_percent: Confidence level percentage (0-100) indicating how likely the recommendation is applicable to the analyzed database additional_info_url: URL to Microsoft documentation or additional resources explaining the tip in detail details: Additional context or detailed explanation specific to the tip &nbsp;"
  },
  {
    "name": "Invoke-DbaDbccDropCleanBuffer",
    "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",
    "category": "Utilities",
    "tags": [
      "dbcc"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbccDropCleanBuffer",
    "popularityRank": 645,
    "synopsis": "Clears SQL Server buffer pool cache and columnstore object pool for performance testing",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbccDropCleanBuffer View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Clears SQL Server buffer pool cache and columnstore object pool for performance testing 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. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-dropcleanbuffers-transact-sql Syntax Invoke-DbaDbccDropCleanBuffer [-SqlInstance] [[-SqlCredential] ] [-NoInformationalMessages] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Runs the command DBCC DROPCLEANBUFFERS against the instance SqlServer2017 using Windows Authentication PS C:\\> Invoke-DbaDbccDropCleanBuffer -SqlInstance SqlServer2017 Example 2: Runs the command DBCC DROPCLEANBUFFERS WITH NO_INFOMSGS against the instance SqlServer2017 using Windows... PS C:\\> Invoke-DbaDbccDropCleanBuffer -SqlInstance SqlServer2017 -NoInformationalMessages Runs the command DBCC DROPCLEANBUFFERS WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication Example 3: Displays what will happen if command DBCC DROPCLEANBUFFERS is called against Sql1 and Sql2/sqlexpress PS C:\\> 'Sql1','Sql2/sqlexpress' | Invoke-DbaDbccDropCleanBuffer -WhatIf Example 4: Connects using sqladmin credential and executes command DBCC DROPCLEANBUFFERS for instance Server1 PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Invoke-DbaDbccDropCleanBuffer -SqlInstance Server1 -SqlCredential $cred Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoInformationalMessages Suppresses informational messages from the DBCC DROPCLEANBUFFERS command output. Use this when running automated scripts where you only want to capture errors or when you need cleaner output for logging purposes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance executed against. Each object contains the command executed and its output from the DBCC DROPCLEANBUFFERS statement. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Cmd: The DBCC command that was executed (e.g., \"DBCC DROPCLEANBUFFERS\" or \"DBCC DROPCLEANBUFFERS WITH NO_INFOMSGS\") Output: The message output from executing the DBCC DROPCLEANBUFFERS command, if any &nbsp;"
  },
  {
    "name": "Invoke-DbaDbccFreeCache",
    "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",
    "category": "Utilities",
    "tags": [
      "dbcc"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbccFreeCache",
    "popularityRank": 557,
    "synopsis": "Clears SQL Server memory caches using DBCC commands to resolve performance issues and free memory",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbccFreeCache View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Clears SQL Server memory caches using DBCC commands to resolve performance issues and free memory 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. Supports three cache-clearing operations: DBCC FREEPROCCACHE: Clears procedure cache (all plans or specific plan handles/resource pools) DBCC FREESESSIONCACHE: Clears distributed query connection cache for linked servers DBCC FREESYSTEMCACHE: Clears system caches like token cache and ring buffers Use 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. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freeproccache-transact-sql https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freesessioncache-transact-sql https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-freesystemcache-transact-sql Syntax Invoke-DbaDbccFreeCache [-SqlInstance] [[-SqlCredential] ] [[-Operation] ] [[-InputValue] ] [-NoInformationalMessages] [-MarkInUseForRemoval] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Runs the command DBCC FREEPROCCACHE against the instance SqlServer2017 using Windows Authentication PS C:\\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE Example 2: Runs the command DBCC FREESESSIONCACHE WITH NO_INFOMSGS against the instance SqlServer2017 using Windows... PS C:\\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESESSIONCACHE -NoInformationalMessages Runs the command DBCC FREESESSIONCACHE WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication Example 3: Runs the command DBCC FREESYSTEMCACHE WITH NO_INFOMSGS against the instance SqlServer2017 using Windows... PS C:\\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -NoInformationalMessages Runs the command DBCC FREESYSTEMCACHE WITH NO_INFOMSGS against the instance SqlServer2017 using Windows Authentication Example 4: Remove a specific plan with plan_handle 0x060006001ECA270EC0215D05000000000000000000000000 from the cache via... PS C:\\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE -InputValue 0x060006001ECA270EC0215D05000000000000000000000000 Remove a specific plan with plan_handle 0x060006001ECA270EC0215D05000000000000000000000000 from the cache via the command DBCC FREEPROCCACHE(0x060006001ECA270EC0215D05000000000000000000000000) against the instance SqlServer2017 using Windows Authentication Example 5: Runs the command DBCC FREEPROCCACHE(&#39;default&#39;) against the instance SqlServer2017 using Windows Authentication PS C:\\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREEPROCCACHE -InputValue default Runs the command DBCC FREEPROCCACHE('default') against the instance SqlServer2017 using Windows Authentication. This clears all cache entries associated with a resource pool 'default'. Example 6: Runs the command DBCC FREESYSTEMCACHE (&#39;ALL&#39;, default) against the instance SqlServer2017 using Windows... PS C:\\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -InputValue default Runs the command DBCC FREESYSTEMCACHE ('ALL', default) against the instance SqlServer2017 using Windows Authentication. This will clean all the caches with entries specific to the resource pool named \"default\". Example 7: Runs the command DBCC FREESYSTEMCACHE (&#39;ALL&#39;, default) WITH MARK_IN_USE_FOR_REMOVAL against the instance... PS C:\\> Invoke-DbaDbccFreeCache -SqlInstance SqlServer2017 -Operation FREESYSTEMCACHE -InputValue default -MarkInUseForRemoval Runs the command DBCC FREESYSTEMCACHE ('ALL', default) WITH MARK_IN_USE_FOR_REMOVAL against the instance SqlServer2017 using Windows Authentication. This will to release entries once the entries become unused for all the caches with entries specific to the resource pool named \"default\". Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Operation Specifies which cache clearing operation to perform: FreeProcCache, FreeSessionCache, or FreeSystemCache. Use FreeProcCache to resolve parameter sniffing or clear inefficient query plans, FreeSessionCache to clear linked server connections, or FreeSystemCache to clear authentication tokens and system-level caches. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | FreeProcCache | | Accepted Values | FreeProcCache,FreeSessionCache,FreeSystemCache | -InputValue Specifies a target value to limit the cache clearing operation instead of clearing all cache entries. For 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 to clear only that pool's cache entries. When omitted, clears all entries for the specified operation which is the typical DBA use case. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoInformationalMessages Suppresses informational messages returned by the DBCC commands. Use this in scripts or automated processes where you only want to capture errors and warnings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MarkInUseForRemoval Marks currently active cache entries for removal once they become unused, rather than waiting for them to be released. Only applies to FreeSystemCache operations and helps ensure memory is freed more aggressively on systems under memory pressure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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. Properties: ComputerName: The computer name of the SQL Server instance where the cache was cleared InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Operation: The cache clearing operation executed (FreeProcCache, FreeSessionCache, or FreeSystemCache) Cmd: The complete DBCC command that was executed (e.g., \"DBCC FREEPROCCACHE WITH NO_INFOMSGS\") Output: The informational messages or output returned by the DBCC command; $null if -NoInformationalMessages was specified &nbsp;"
  },
  {
    "name": "Invoke-DbaDbClone",
    "description": "Creates schema-only database clones using SQL Server's 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/",
    "category": "Utilities",
    "tags": [
      "statistics",
      "performance",
      "clone"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbClone",
    "popularityRank": 178,
    "synopsis": "Creates lightweight database clones containing schema and statistics but no table data",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbClone View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates lightweight database clones containing schema and statistics but no table data Description Creates schema-only database clones using SQL Server's DBCC CLONEDATABASE command. The cloned database contains all database objects (tables, indexes, views, procedures) and statistics, but no actual table data. This 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. Read more: https://sqlperformance.com/2016/08/sql-statistics/expanding-dbcc-clonedatabase https://support.microsoft.com/en-us/help/3177838/how-to-use-dbcc-clonedatabase-to-generate-a-schema-and-statistics-only Thanks to Microsoft Tiger Team for the code and idea https://github.com/Microsoft/tigertoolbox/ Syntax Invoke-DbaDbClone [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-InputObject] ] [[-CloneDatabase] ] [-ExcludeStatistics] [-ExcludeQueryStore] [-UpdateStatistics] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Clones mydb to myclone on sql2016 PS C:\\> Invoke-DbaDbClone -SqlInstance sql2016 -Database mydb -CloneDatabase myclone Example 2: Updates the statistics of mydb then clones to myclone and myclone2 PS C:\\> Get-DbaDatabase -SqlInstance sql2016 -Database mydb | Invoke-DbaDbClone -CloneDatabase myclone, myclone2 -UpdateStatistics Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the source database(s) to clone from the SQL Server instance. Accepts multiple database names for batch operations. Use this when connecting directly to an instance rather than piping database objects from Get-DbaDatabase. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase through the pipeline, allowing for filtered operations. This method provides more flexibility than the Database parameter for complex database selection scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -CloneDatabase Specifies the name(s) for the new cloned database(s). If not provided, defaults to adding '_clone' suffix to the source database name. Each clone must have a unique name on the target instance and cannot already exist. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeStatistics Excludes table and index statistics from the cloned database, creating only the schema structure without statistical metadata. Use 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+. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeQueryStore Excludes Query Store data from the cloned database, preventing historical query execution data from being copied. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UpdateStatistics Updates column store index statistics in the source database before cloning using Microsoft Tiger Team methodology. Use this when working with column store indexes to ensure the clone contains current statistical information for accurate query plan generation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Database Returns 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 returned per clone created. Default display properties (via Select-DefaultView from Get-DbaDatabase): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the cloned database Status: Current database status (Normal, Offline, Recovering, etc.) IsAccessible: Boolean indicating if the database is currently accessible RecoveryModel: Database recovery model (Full, Simple, or BulkLogged) LogReuseWaitStatus: Status of transaction log reuse Size: Database size in megabytes Owner: Database owner login name Collation: Database collation setting Encrypted: Boolean indicating if Transparent Data Encryption (TDE) is enabled *Additional properties available from the SMO Database object using Select-Object :** CreateDate: DateTime when the database was created LastFullBackup: DateTime of the most recent full backup LastDiffBackup: DateTime of the most recent differential backup LastLogBackup: DateTime of the most recent transaction log backup DatabaseEngineEdition: Edition of SQL Server (Enterprise, Standard, Express, etc.) ID: Database ID assigned by SQL Server And many other SMO Database properties (see https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.management.smo.database) &nbsp;"
  },
  {
    "name": "Invoke-DbaDbDataGenerator",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "datageneration"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbDataGenerator",
    "popularityRank": 376,
    "synopsis": "Generates realistic test data for SQL Server database tables using configuration-driven rules",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbDataGenerator View Source Sander Stad (@sqlstad, sqlstad.nl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates realistic test data for SQL Server database tables using configuration-driven rules 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. Syntax Invoke-DbaDbDataGenerator [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [-FilePath] [[-Locale] ] [[-CharacterString] ] [[-Table] ] [[-Column] ] [[-ExcludeTable] ] [[-ExcludeColumn] ] [[-MaxValue] ] [-ExactLength] [[-ModulusFactor] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Apply the data generation configuration from the file &quot;sqldb1.db1.tables.json&quot; to the db1 database on sqldb2 PS C:\\> Invoke-DbaDbDataGenerator -SqlInstance sqldb2 -Database DB1 -FilePath C:\\temp\\sqldb1.db1.tables.json Apply the data generation configuration from the file \"sqldb1.db1.tables.json\" to the db1 database on sqldb2. Prompt for confirmation for each table. Required Parameters -FilePath Path to the JSON configuration file that defines data generation rules for tables and columns. Accepts local file paths or HTTP URLs. This file specifies which tables to populate, how many rows to generate, and the data generation rules for each column. | Property | Value | | --- | --- | | Alias | Path,FullName | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to generate data for. If not provided, uses database names from the configuration file. Use this to limit data generation to specific databases when your config file covers multiple databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Locale Sets the locale for generating culture-specific fake data like names, addresses, and phone numbers. Defaults to 'en' for English. Change this when you need realistic data for specific regions, such as 'de' for German or 'fr' for French test data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | en | -CharacterString Defines the character set used for generating random string values. Defaults to alphanumeric characters. Customize this when you need specific character patterns for testing, such as restricting to only uppercase letters or including special characters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 | -Table Limits data generation to specific tables only, overriding the full table list in the configuration file. Useful when you need to populate just certain tables for testing or during incremental development work. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Column Restricts data generation to specific columns within the processed tables. Use this to generate data for only certain columns during testing or when troubleshooting specific column configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeTable Skips specific tables even if they're included in the configuration file. Use this to temporarily exclude problematic tables during testing or when you want to process most tables but skip a few. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeColumn Skips specific columns even if they're included in the configuration file. Helpful when troubleshooting column-specific issues or when you want to exclude sensitive columns temporarily. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaxValue Overrides the maximum length for string columns, ignoring the data type's natural limits. Lower data type limits still take precedence. Useful for testing with shorter strings or when you need consistent string lengths across different environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -ExactLength Forces generated strings to match the exact length of existing data in the column. Use this when you need to preserve string length patterns for testing applications that expect specific data formats. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ModulusFactor Controls how frequently nullable columns receive NULL values by using modulus calculation. Default is every 10th row gets NULL. Adjust this to increase or decrease NULL frequency in your test data to match realistic data distribution patterns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 10 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per table that had data generated, providing a summary of the data generation operation. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database where data was generated Schema: The schema name containing the table Table: The name of the table that was populated with generated data Columns: Array of column names that received generated data Rows: Integer count of rows generated and inserted into the table Elapsed: TimeSpan of the time taken to generate and insert data (formatted as prettytimespan for display) Status: String indicating the result of the operation - \"Done\" for successful completion &nbsp;"
  },
  {
    "name": "Invoke-DbaDbDataMasking",
    "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",
    "category": "Data Operations",
    "tags": [
      "masking",
      "datamasking"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbDataMasking",
    "popularityRank": 124,
    "synopsis": "Replaces sensitive production data with randomized values using configurable masking rules",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbDataMasking View Source Sander Stad (@sqlstad, sqlstad.nl) , Chrissy LeMaire (@cl, netnerds.net) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Replaces sensitive production data with randomized values using configurable masking rules 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. The 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. Use 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. Note that the following column and data types are not currently supported: Identity ForeignKey Computed Hierarchyid Geography Geometry Xml Syntax Invoke-DbaDbDataMasking [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [-FilePath] [[-Locale] ] [[-CharacterString] ] [[-Table] ] [[-Column] ] [[-ExcludeTable] ] [[-ExcludeColumn] ] [[-MaxValue] ] [[-ModulusFactor] ] [-ExactLength] [[-CommandTimeout] ] [[-BatchSize] ] [[-Retry] ] [[-DictionaryFilePath] ] [[-DictionaryExportPath] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Apply the data masking configuration from the file &quot;sqldb1.db1.tables.json&quot; to the db1 database on sqldb2 PS C:\\> Invoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -FilePath C:\\Temp\\sqldb1.db1.tables.json Apply the data masking configuration from the file \"sqldb1.db1.tables.json\" to the db1 database on sqldb2. Prompt for confirmation for each table. Example 2: Apply the data masking configuration from the file &quot;sqldb1.db1.tables.json&quot; to the db1 database on sqldb2 PS C:\\> Get-ChildItem -Path C:\\Temp\\sqldb1.db1.tables.json | Invoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -Confirm:$false Apply the data masking configuration from the file \"sqldb1.db1.tables.json\" to the db1 database on sqldb2. Do not prompt for confirmation. Example 3: $file | Invoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -Confirm:$false Create the data masking... PS C:\\> New-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Path C:\\Temp\\clone -OutVariable file $file | Invoke-DbaDbDataMasking -SqlInstance SQLDB2 -Database DB1 -Confirm:$false Create the data masking configuration file \"sqldb1.db1.tables.json\", then use it to mask the db1 database on sqldb2. Do not prompt for confirmation. Example 4: See what would happen if you the data masking configuration from the file &quot;sqldb1.db1.tables.json&quot; to the db1... PS C:\\> Get-ChildItem -Path C:\\Temp\\sqldb1.db1.tables.json | Invoke-DbaDbDataMasking -SqlInstance SQLDB2, sqldb3 -Database DB1 -Confirm:$false See 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. Required Parameters -FilePath Path to the JSON configuration file that defines masking rules for tables and columns. Accepts pipeline input from New-DbaDbMaskingConfig. This file specifies which columns to mask, what type of fake data to generate, and handles relationships between tables to maintain referential integrity. | Property | Value | | --- | --- | | Alias | Path,FullName | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to mask on the target instance. Accepts wildcards for pattern matching. If omitted, uses the database name from the configuration file. Essential for targeting specific databases when the same config applies to multiple environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Locale Sets the locale for generating culture-specific fake data like names, addresses, and phone numbers. Defaults to 'en' (English). Change this when masking data for specific regions to ensure realistic replacement values that match your target environment's cultural context. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | en | -CharacterString Defines the character set used when generating random strings for masked data. Defaults to alphanumeric characters. Customize this to match your application's validation rules, such as excluding certain characters that might cause issues with your systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 | -Table Limits masking to specific tables within the configuration file. Accepts wildcards for pattern matching. Use this when you need to mask only certain tables during testing or phased rollouts, rather than processing all tables defined in the config. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Column Restricts masking to specific columns within the selected tables. Accepts wildcards for pattern matching. Useful for testing individual column masks or when you need to re-mask specific columns without affecting others. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeTable Skips masking for specified tables even if they're defined in the configuration file. Accepts wildcards. Use this to temporarily exclude problematic tables during troubleshooting or when certain tables need to remain unchanged in specific environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeColumn Skips masking for specified columns even if they're defined in the configuration file. Accepts wildcards. Helpful for excluding columns that are part of unique indexes or when specific columns need to remain unchanged during testing phases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaxValue Overrides the maximum length for generated string values, useful for testing with shorter data than production allows. The smaller value between this parameter and the column's actual maximum length will be used. Primarily useful for development and testing scenarios rather than production masking. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Adjust this to match your production data's NULL distribution patterns, ensuring masked data maintains realistic null value frequency. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -ExactLength Forces masked string values to match the exact length of the original data. For example, 'Smith' becomes exactly 5 random characters. Enable this when your applications have strict validation rules that depend on consistent field lengths or when maintaining data formatting is critical. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CommandTimeout Sets the timeout in seconds for SQL commands during the masking process. Default is 300 seconds (5 minutes). Increase this value when masking large tables or when working with slower storage systems to prevent timeout errors during long-running operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BatchSize Number of rows processed in each batch during the masking operation. Default is 1000 rows per batch. Adjust based on your system's memory and transaction log capacity. Smaller batches reduce memory usage but may slow processing, while larger batches improve performance but require more resources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Retry Maximum number of attempts to generate unique values when tables have unique constraints. Default is 1000 retries. Increase this when masking tables with many unique indexes or when the range of possible values is limited, preventing failure due to constraint violations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -DictionaryFilePath Path to CSV files containing deterministic value mappings for consistent masking across multiple runs or environments. Use this when you need the same original values to always map to the same masked values, maintaining referential integrity across related systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DictionaryExportPath Directory path where deterministic value mapping files will be exported after masking. Files are named [computername]_[instancename]_[database]_Dictionary.csv. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per table that was processed by the masking operation. Each object contains the results of masking that specific table. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database where masking was performed Schema: The schema name of the masked table Table: The name of the masked table Columns: Array of column names that were masked Rows: Integer count of rows that were masked in the table Elapsed: TimeSpan object showing how long the masking operation took for this table Status: String indicating if masking was \"Successful\" or \"Failed\" for this table &nbsp;"
  },
  {
    "name": "Invoke-DbaDbDbccCheckConstraint",
    "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't 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",
    "category": "Utilities",
    "tags": [
      "dbcc"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbDbccCheckConstraint",
    "popularityRank": 510,
    "synopsis": "Validates constraint integrity by checking for constraint violations in SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbDbccCheckConstraint View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates constraint integrity by checking for constraint violations in SQL Server databases 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't meet constraint requirements, including the table, constraint name, and violating data criteria. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkconstraints-transact-sql Syntax Invoke-DbaDbDbccCheckConstraint [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Object] ] [-AllConstraints] [-AllErrorMessages] [-NoInformationalMessages] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Runs the command DBCC CHECKCONSTRAINTS to check all enabled constraints on all tables for all databases for... PS C:\\> Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 Runs the command DBCC CHECKCONSTRAINTS to check all enabled constraints on all tables for all databases for the instance SqlServer2017. Connect using Windows Authentication Example 2: Connect to instance SqlServer2017 using Windows Authentication and run the command DBCC CHECKCONSTRAINTS to... PS C:\\> Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB Connect to instance SqlServer2017 using Windows Authentication and run the command DBCC CHECKCONSTRAINTS to check all enabled constraints on all tables in the CurrentDB database. Example 3: Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC... PS C:\\> Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB -Object Sometable Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKCONSTRAINTS(SometableId) to check all enabled constraints in the table. Example 4: Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC... PS C:\\> Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -Database CurrentDB -Object ConstraintId Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKCONSTRAINTS(ConstraintId) to check the constraint with constraint_id = ConstraintId. Example 5: Connects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Invoke-DbaDbDbccCheckConstraint -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Object TableId -AllConstraints -AllErrorMessages -NoInformationalMessages Connects 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 disabled constraints on the table with able_id = TableId. Returns all rows that violate constraints. Example 6: Displays what will happen if command DBCC CHECKCONSTRAINTS is called against all databases on Sql1 and... PS C:\\> 'Sql1','Sql2/sqlexpress' | Invoke-DbaDbDbccCheckConstraint -WhatIf Displays what will happen if command DBCC CHECKCONSTRAINTS is called against all databases on Sql1 and Sql2/sqlexpress. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for constraint violations. Accepts multiple database names and supports wildcards for pattern matching. If 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Object Specifies the table or constraint to check for violations. Accepts either table names, constraint names, or their numeric IDs. When targeting a table, all enabled constraints on that table are validated. When targeting a specific constraint, only that constraint is checked. Use this when you need to focus on a specific table after bulk data operations or when investigating a known problematic constraint. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllConstraints Forces checking of both enabled and disabled constraints on the specified table or all tables in the database. By 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 operations. Has no effect when checking a specific constraint by name or ID. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AllErrorMessages Returns all constraint violation rows instead of limiting output to the first 200 violations per constraint. Use this when you need a complete inventory of data quality issues, especially after bulk imports or when preparing comprehensive data cleanup reports. Be cautious with large tables as this can generate extensive output. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoInformationalMessages Suppresses informational messages like \"DBCC execution completed\" and processing status updates. Use this when automating constraint checks in scripts where you only want to capture actual constraint violations, not DBCC status messages. Helpful for cleaner output when processing multiple databases or integrating results into monitoring systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database when no constraint violations are found, or one object per violating row when violations are detected. When no violations exist (Path 1): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: Name of the database that was checked Cmd: The DBCC CHECKCONSTRAINTS command that was executed Output: DBCC informational or status messages, or null if no messages Table: Always null when no violations found Constraint: Always null when no violations found Where: Always null when no violations found When constraint violations are found (Path 2): Returns one object per violating row with the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: Name of the database containing the violation Cmd: The DBCC CHECKCONSTRAINTS command that was executed Output: String containing previous output information Table: Name of the table containing the violating row Constraint: Name of the constraint that was violated Where: The WHERE clause or criteria identifying the violating row &nbsp;"
  },
  {
    "name": "Invoke-DbaDbDbccCleanTable",
    "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't 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 'dbo.TableName') 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",
    "category": "Utilities",
    "tags": [
      "dbcc"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbDbccCleanTable",
    "popularityRank": 523,
    "synopsis": "Reclaims disk space from dropped variable-length columns in tables and indexed views",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbDbccCleanTable View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Reclaims disk space from dropped variable-length columns in tables and indexed views 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. When you drop variable-length columns, SQL Server doesn't 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. The function accepts either table names (like 'dbo.TableName') 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. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-cleantable-transact-sql Syntax Invoke-DbaDbDbccCleanTable [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Object] ] [[-BatchSize] ] [-NoInformationalMessages] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC... PS C:\\> Invoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -Database CurrentDB -Object 'dbo.SomeTable' Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CLEANTABLE('CurrentDB', 'dbo.SomeTable') to reclaim space after variable-length columns have been dropped. Example 2: Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC... PS C:\\> Invoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -Database CurrentDB -Object 34636372 -BatchSize 5000 Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC CLEANTABLE('CurrentDB', 34636372, 5000) to reclaim space from table with Table_Id = 34636372 after variable-length columns have been dropped. Example 3: Connects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Invoke-DbaDbDbccCleanTable -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Object 'dbo.SomeTable' -NoInformationalMessages Connects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC CLEANTABLE('CurrentDB', 'dbo.SomeTable') WITH NO_INFOMSGS to reclaim space after variable-length columns have been dropped. Example 4: Runs the command DBCC CLEANTABLE(&#39;DatabaseName&#39;, &#39;dbo.SomeTable&#39;, 5000) against all databases on Sql1 and... PS C:\\> 'Sql1','Sql2/sqlexpress' | Invoke-DbaDbDbccCleanTable -Object 'dbo.SomeTable' -BatchSize 5000 Runs the command DBCC CLEANTABLE('DatabaseName', 'dbo.SomeTable', 5000) against all databases on Sql1 and Sql2/sqlexpress. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to include in the clean table operation. Accepts multiple database names. When omitted, the operation runs against all accessible databases on the instance. Use this to target specific databases where you know variable-length columns have been dropped recently. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Object Specifies the table or indexed view names to clean, or their object IDs for more precise targeting. Accepts schema-qualified names like 'dbo.TableName' or numeric object IDs like 34636372. This parameter is required since DBCC CLEANTABLE must target specific objects, not entire databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BatchSize Controls how many rows are processed per transaction during the clean operation. Use smaller batch sizes (like 5000-10000) on production systems to reduce lock duration and transaction log impact. When omitted, processes the entire table in a single transaction which is faster but holds locks longer. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -NoInformationalMessages Suppresses informational messages from the DBCC CLEANTABLE output, showing only errors and warnings. Use this in automated scripts or when processing multiple tables to reduce console output volume. Equivalent to adding WITH NO_INFOMSGS to the DBCC command. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per table or indexed view being cleaned across all specified databases. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: Name of the database containing the object being cleaned Object: The table or indexed view name or object ID specified for cleaning Cmd: The DBCC CLEANTABLE command that was executed Output: DBCC output messages, informational status, or null if operation completed silently &nbsp;"
  },
  {
    "name": "Invoke-DbaDbDbccUpdateUsage",
    "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",
    "category": "Advanced Features",
    "tags": [
      "dbcc"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbDbccUpdateUsage",
    "popularityRank": 528,
    "synopsis": "Corrects page and row count inaccuracies in SQL Server catalog views using DBCC UPDATEUSAGE",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbDbccUpdateUsage View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Corrects page and row count inaccuracies in SQL Server catalog views using DBCC UPDATEUSAGE 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. This 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. Common 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. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-updateusage-transact-sql Syntax Invoke-DbaDbDbccUpdateUsage [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Table] ] [[-Index] ] [-NoInformationalMessages] [-CountRows] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Runs the command DBCC UPDATEUSAGE to update the page or row counts or both for all objects in all databases... PS C:\\> Invoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 Runs 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 Example 2: Runs the command DBCC UPDATEUSAGE to update the page or row counts or both for all objects in the CurrentDB... PS C:\\> Invoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -Database CurrentDB Runs 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 Example 3: Connects to CurrentDB on instance SqlServer2017 using Windows Authentication and runs the command DBCC... PS C:\\> Invoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -Database CurrentDB -Table Sometable Connects 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. Example 4: Connects to CurrentDB on instance SqlServer2017 using sqladmin credential and runs the command DBCC... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Invoke-DbaDbDbccUpdateUsage -SqlInstance SqlServer2017 -SqlCredential $cred -Database CurrentDB -Table 'SometableId -Index IndexName -NoInformationalMessages -CountRows Connects 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. Example 5: Displays what will happen if command DBCC UPDATEUSAGE is called against all databases on Sql1 and... PS C:\\> 'Sql1','Sql2/sqlexpress' | Invoke-DbaDbDbccUpdateUsage -WhatIf Displays what will happen if command DBCC UPDATEUSAGE is called against all databases on Sql1 and Sql2/sqlexpress. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to update usage statistics for. Accepts database names or IDs. When omitted, DBCC UPDATEUSAGE runs against all accessible databases on the instance. Use this to target specific databases when you know which ones have inaccurate space usage reports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Specifies a single table or indexed view to update usage statistics for. Accepts table names or object IDs. When omitted, DBCC UPDATEUSAGE processes all tables and indexed views in the specified database(s). Use this when sp_spaceused reports incorrect sizes for a specific table after bulk operations or index maintenance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Index Specifies a single index to update usage statistics for. Accepts index names or index IDs. Requires the Table parameter to be specified and updates statistics only for that specific index. Use this for targeted correction when you know a particular index has inaccurate metadata after rebuilds or reorganization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoInformationalMessages Suppresses informational messages during DBCC UPDATEUSAGE execution using the NO_INFOMSGS option. Use this in automated scripts or when processing many objects to reduce output volume and focus on actual problems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CountRows Forces DBCC UPDATEUSAGE to recalculate and update row counts in addition to page counts using the COUNT_ROWS option. Use this when sp_spaceused shows incorrect row counts, typically after bulk insert/delete operations or database restores. Note that this option increases execution time as SQL Server must physically count all rows in affected tables. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per result row returned by the DBCC UPDATEUSAGE command executed against each database. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The database name where DBCC UPDATEUSAGE was executed Cmd: The complete DBCC UPDATEUSAGE command that was executed Output: The raw output message(s) from the DBCC command; usually informational messages about pages and rows updated &nbsp;"
  },
  {
    "name": "Invoke-DbaDbDecryptObject",
    "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'Get-DbaSpConfigure -SqlInstance [yourinstance] -ConfigName RemoteDacConnectionsEnabled'\nThe ConfiguredValue should be 1.\n\nThe local DAC connection is enabled by default.\n\nTo enable remote DAC connections, use:\n'Set-DbaSpConfigure -SqlInstance [yourinstance] -ConfigName RemoteDacConnectionsEnabled -Value 1'\nIn some cases you may need to restart the SQL Server instance after enabling this setting.",
    "category": "Security",
    "tags": [
      "encryption",
      "decrypt",
      "utility"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbDecryptObject",
    "popularityRank": 434,
    "synopsis": "Decrypts encrypted stored procedures, functions, views, and triggers using Dedicated Admin Connection (DAC)",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbDecryptObject View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Decrypts encrypted stored procedures, functions, views, and triggers using Dedicated Admin Connection (DAC) 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. This 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. The command outputs results to the console by default, with an option to export all decrypted objects to organized .sql files in a folder structure. To 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. You can check the remote DAC connection with: 'Get-DbaSpConfigure -SqlInstance [yourinstance] -ConfigName RemoteDacConnectionsEnabled' The ConfiguredValue should be 1. The local DAC connection is enabled by default. To enable remote DAC connections, use: 'Set-DbaSpConfigure -SqlInstance [yourinstance] -ConfigName RemoteDacConnectionsEnabled -Value 1' In some cases you may need to restart the SQL Server instance after enabling this setting. Syntax Invoke-DbaDbDecryptObject [-SqlInstance] [[-SqlCredential] ] [-Database] [[-ObjectName] ] [[-EncodingType] ] [[-ExportDestination] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Decrypt object &quot;Function1&quot; in DB1 of instance SQLDB1 and output the data to the user PS C:\\> Invoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1 Example 2: Decrypt object &quot;Function1&quot; in DB1 of instance SQLDB1 and output the data to the folder &quot;C:\\temp\\decrypt&quot; PS C:\\> Invoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1 -ExportDestination C:\\temp\\decrypt Example 3: Decrypt all objects in DB1 of instance SQLDB1 and output the data to the folder &quot;C:\\temp\\decrypt&quot; PS C:\\> Invoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ExportDestination C:\\temp\\decrypt Example 4: Decrypt objects &quot;Function1&quot; and &quot;Function2&quot; and output the data to the user PS C:\\> Invoke-DbaDbDecryptObject -SqlInstance SQLDB1 -Database DB1 -ObjectName Function1, Function2 Example 5: Decrypt objects &quot;Function1&quot; and &quot;Function2&quot; and output the data to the user using a pipeline for the instance PS C:\\> \"SQLDB1\" | Invoke-DbaDbDecryptObject -Database DB1 -ObjectName Function1, Function2 Required Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Database Specifies which databases contain the encrypted objects you want to decrypt. Accepts multiple database names. Use this to target specific databases instead of searching across all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ObjectName Specifies the names of encrypted objects to decrypt (stored procedures, functions, views, or triggers). Accepts multiple object names. When 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EncodingType Determines the text encoding used during the XOR decryption process to convert binary data back to readable T-SQL code. Defaults to ASCII. Use UTF8 when dealing with databases that contain Unicode characters in object definitions or when ASCII decryption produces garbled text. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | ASCII | | Accepted Values | ASCII,UTF8 | -ExportDestination Specifies the folder path where decrypted T-SQL scripts will be saved as individual .sql files. When 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 only. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per encrypted database object that is successfully decrypted. If no encrypted objects are found, nothing is returned. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database containing the encrypted object Type: The type of database object (StoredProcedure, UserDefinedFunction, View, or Trigger) Schema: The schema name containing the object Name: The object name FullName: The fully qualified name in schema.name format Script: The decrypted T-SQL source code of the object OutputFile: The file path where the script was exported; null if -ExportDestination was not specified and results were displayed in console only &nbsp;"
  },
  {
    "name": "Invoke-DbaDbLogShipping",
    "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.",
    "category": "Utilities",
    "tags": [
      "logshipping"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbLogShipping",
    "popularityRank": 75,
    "synopsis": "Invoke-DbaDbLogShipping sets up log shipping for one or more databases",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Invoke-DbaDbLogShipping View Source Sander Stad (@sqlstad), sqlstad.nl + Claude (Azure blob storage support) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Invoke-DbaDbLogShipping sets up log shipping for one or more databases Description Invoke-DbaDbLogShipping helps to easily set up log shipping for one or more databases. This 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. There are some settings that cannot be made by the function and they need to be prepared before the function is executed. The following settings need to be made before log shipping can be initiated: Backup destination (the folder and the privileges) Copy destination (the folder and the privileges) Privileges Make sure your agent service on both the primary and the secondary instance is an Active Directory account. Also have the credentials ready to set the folder permissions Network share The backup destination needs to be shared and have the share privileges of FULL CONTROL to Everyone. NTFS permissions The backup destination must have at least read/write permissions for the primary instance agent account. The backup destination must have at least read permissions for the secondary instance agent account. The copy destination must have at least read/write permission for the secondary instance agent account. Syntax Invoke-DbaDbLogShipping [-SourceSqlInstance] [-DestinationSqlInstance] [[-SourceSqlCredential] ] [[-SourceCredential] ] [[-DestinationSqlCredential] ] [[-DestinationCredential] ] [-Database] [[-SharedPath] ] [[-LocalPath] ] [[-AzureBaseUrl] ] [[-AzureCredential] ] [[-BackupJob] ] [[-BackupRetention] ] [[-BackupSchedule] ] [-BackupScheduleDisabled] [[-BackupScheduleFrequencyType] ] [[-BackupScheduleFrequencyInterval] ] [[-BackupScheduleFrequencySubdayType] ] [[-BackupScheduleFrequencySubdayInterval] ] [[-BackupScheduleFrequencyRelativeInterval] ] [[-BackupScheduleFrequencyRecurrenceFactor] ] [[-BackupScheduleStartDate] ] [[-BackupScheduleEndDate] ] [[-BackupScheduleStartTime] ] [[-BackupScheduleEndTime] ] [[-BackupThreshold] ] [-CompressBackup] [[-CopyDestinationFolder] ] [[-CopyJob] ] [[-CopyRetention] ] [[-CopySchedule] ] [-CopyScheduleDisabled] [[-CopyScheduleFrequencyType] ] [[-CopyScheduleFrequencyInterval] ] [[-CopyScheduleFrequencySubdayType] ] [[-CopyScheduleFrequencySubdayInterval] ] [[-CopyScheduleFrequencyRelativeInterval] ] [[-CopyScheduleFrequencyRecurrenceFactor] ] [[-CopyScheduleStartDate] ] [[-CopyScheduleEndDate] ] [[-CopyScheduleStartTime] ] [[-CopyScheduleEndTime] ] [-DisconnectUsers] [[-FullBackupPath] ] [-GenerateFullBackup] [[-HistoryRetention] ] [-NoRecovery] [-NoInitialization] [[-PrimaryMonitorServer] ] [[-PrimaryMonitorCredential] ] [[-PrimaryMonitorServerSecurityMode] ] [-PrimaryThresholdAlertEnabled] [[-RestoreDataFolder] ] [[-RestoreLogFolder] ] [[-RestoreDelay] ] [[-RestoreAlertThreshold] ] [[-RestoreJob] ] [[-RestoreRetention] ] [[-RestoreSchedule] ] [-RestoreScheduleDisabled] [[-RestoreScheduleFrequencyType] ] [[-RestoreScheduleFrequencyInterval] ] [[-RestoreScheduleFrequencySubdayType] ] [[-RestoreScheduleFrequencySubdayInterval] ] [[-RestoreScheduleFrequencyRelativeInterval] ] [[-RestoreScheduleFrequencyRecurrenceFactor] ] [[-RestoreScheduleStartDate] ] [[-RestoreScheduleEndDate] ] [[-RestoreScheduleStartTime] ] [[-RestoreScheduleEndTime] ] [[-RestoreThreshold] ] [[-SecondaryDatabasePrefix] ] [[-SecondaryDatabaseSuffix] ] [[-SecondaryMonitorServer] ] [[-SecondaryMonitorCredential] ] [[-SecondaryMonitorServerSecurityMode] ] [-SecondaryThresholdAlertEnabled] [-Standby] [[-StandbyDirectory] ] [-UseExistingFullBackup] [[-UseBackupFolder] ] [-IgnoreFileChecks] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets up log shipping for database &quot;db1&quot; with the backup path to a network share allowing local backups PS C:\\> $params = @{ >> SourceSqlInstance = 'sql1' >> DestinationSqlInstance = 'sql2' >> Database = 'db1' >> SharedPath= '\\\\sql1\\logshipping' >> LocalPath= 'D:\\Data\\logshipping' >> BackupScheduleFrequencyType = 'daily' >> BackupScheduleFrequencyInterval = 1 >> CompressBackup = $true >> CopyScheduleFrequencyType = 'daily' >> CopyScheduleFrequencyInterval = 1 >> GenerateFullBackup = $true >> RestoreScheduleFrequencyType = 'daily' >> RestoreScheduleFrequencyInterval = 1 >> SecondaryDatabaseSuffix = 'LS' >> CopyDestinationFolder = '\\\\sql2\\logshippingdest' >> Force = $true >> } >> PS C:\\> Invoke-DbaDbLogShipping @params Sets up log shipping for database \"db1\" with the backup path to a network share allowing local backups. It creates daily schedules for the backup, copy and restore job with all the defaults to be executed every 15 minutes daily. The secondary database will be called \"db1_LS\". Example 2: Sets up log shipping with all defaults except that a backup file is generated PS C:\\> $params = @{ >> SourceSqlInstance = 'sql1' >> DestinationSqlInstance = 'sql2' >> Database = 'db1' >> SharedPath= '\\\\sql1\\logshipping' >> GenerateFullBackup = $true >> Force = $true >> } >> PS C:\\> Invoke-DbaDbLogShipping @params Sets up log shipping with all defaults except that a backup file is generated. The 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 \"logshipping\" i.e. \"D:\\SQLBackup\\Logshiping\". Example 3: Sets up log shipping for database &quot;db1&quot; to Azure blob storage using SAS token authentication PS C:\\> # First, create the SAS credential on both instances PS C:\\> $azureUrl = \"https://mystorageaccount.blob.core.windows.net/logshipping\" PS C:\\> $cred = Get-Credential -Message \"Paste SAS token (without leading ?) in password field\" -UserName \"SHARED ACCESS SIGNATURE\" PS C:\\> $splatCred = @{ >> SqlInstance = \"sql1\", \"sql2\" >> Name = $azureUrl >> Identity = $cred.UserName >> SecurePassword = $cred.Password >> } PS C:\\> New-DbaCredential @splatCred PS C:\\> PS C:\\> # Then set up log shipping PS C:\\> $splatLogShipping = @{ >> SourceSqlInstance = \"sql1\" >> DestinationSqlInstance = \"sql2\" >> Database = \"db1\" >> AzureBaseUrl = $azureUrl >> BackupScheduleFrequencyType = \"daily\" >> BackupScheduleFrequencyInterval = 1 >> RestoreScheduleFrequencyType = \"daily\" >> RestoreScheduleFrequencyInterval = 1 >> GenerateFullBackup = $true >> Force = $true >> } PS C:\\> Invoke-DbaDbLogShipping @splatLogShipping Required Parameters -SourceSqlInstance Source SQL Server instance which contains the databases to be log shipped. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | SourceServerInstance,SourceSqlServerSqlServer,Source | | Required | True | | Pipeline | false | | Default Value | | -DestinationSqlInstance Destination SQL Server instance which contains the databases to be log shipped. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | DestinationServerInstance,DestinationSqlServer,Destination | | Required | True | | Pipeline | false | | Default Value | | -Database Specifies which database(s) to configure for log shipping. The database must be in FULL recovery model. Use this to target specific databases rather than setting up log shipping for all databases on the source instance. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SourceSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SourceCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SharedPath Specifies the network share path where transaction log backup files will be stored. Must be in UNC format (\\\\server\\\\share). The function automatically creates a subdirectory for each database under this path. Both source and destination instances need access to this location. Mutually exclusive with AzureBaseUrl parameter. | Property | Value | | --- | --- | | Alias | BackupNetworkPath | | Required | False | | Pipeline | false | | Default Value | | -LocalPath Sets the local backup path on the source server when different from the shared path. Use this when the source server accesses the backup location via a local path but other servers need to access it via the network share. Not applicable when using Azure blob storage (AzureBaseUrl). | Property | Value | | --- | --- | | Alias | BackupLocalPath | | Required | False | | Pipeline | false | | Default Value | | -AzureBaseUrl Specifies the Azure blob storage container URL where transaction log backups will be stored. Format: https://storageaccount.blob.core.windows.net/container/ When specified, traditional file-based copy jobs are skipped as backups go directly to Azure blob storage. Mutually exclusive with SharedPath parameter. Requires SQL Server 2012 or later. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. The credential must exist on both source and destination SQL Server instances before setting up log shipping. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BackupJob Specifies the prefix for the SQL Agent backup job name that performs transaction log backups. The database name is automatically appended to create the full job name. Defaults to 'LSBackup_' if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BackupRetention Sets how long backup files are retained before deletion, specified in minutes. Defaults to 4320 minutes (72 hours). Consider storage capacity and recovery requirements when setting this value. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BackupSchedule Name of the backup schedule created for the backup job. The parameter works as a prefix where the name of the database will be added to the backup job schedule name. Default is \"LSBackupSchedule_[databasename]\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BackupScheduleDisabled Creates the backup job schedule in a disabled state, preventing automatic execution. Use this when you want to manually control when log shipping backup jobs start running. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BackupScheduleFrequencyType Controls how often the backup job runs. Accepts 'Daily' (most common), 'AgentStart', or 'IdleComputer'. Daily scheduling allows for regular transaction log backups to maintain the log shipping chain. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Daily,Weekly,AgentStart,IdleComputer | -BackupScheduleFrequencyInterval The number of type periods to occur between each execution of the backup job. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BackupScheduleFrequencySubdayType Specifies the units for the sub-day FrequencyInterval. Allowed values are \"Time\", \"Seconds\", \"Minutes\", \"Hours\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Time,Seconds,Minutes,Hours | -BackupScheduleFrequencySubdayInterval Specifies the interval between backup job executions within a day when using Minutes, Seconds, or Hours frequency. For example, setting 15 with FrequencySubdayType of 'Minutes' creates backups every 15 minutes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BackupScheduleFrequencyRelativeInterval A job's occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BackupScheduleStartDate The date on which execution of a job can begin. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BackupScheduleEndDate The date on which execution of a job can stop. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BackupScheduleStartTime The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock. Example: '010000' for 01:00:00 AM. Example: '140000' for 02:00:00 PM. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BackupScheduleEndTime The time on any day to end execution of a job. Format HHMMSS / 24 hour clock. Example: '010000' for 01:00:00 AM. Example: '140000' for 02:00:00 PM. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BackupThreshold Sets the alert threshold in minutes for detecting backup delays. An alert is raised if no backup occurs within this timeframe. Defaults to 60 minutes. Use shorter intervals for critical databases requiring frequent log backups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -CompressBackup Enables backup compression for transaction log backups to reduce file size and network transfer time. Only available on SQL Server 2008 and later. Uses server default compression setting if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CopyDestinationFolder Specifies the destination folder path where backup files are copied on the secondary server. The function creates a database-specific subdirectory under this path. Defaults to the secondary server's backup directory if not provided. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CopyJob Name of the copy job that will be created in the SQL Server agent. The parameter works as a prefix where the name of the database will be added to the copy job name. The default is \"LSBackup_[databasename]\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CopyRetention The copy retention period in minutes. Default is 4320 / 72 hours | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -CopySchedule Name of the backup schedule created for the copy job. The parameter works as a prefix where the name of the database will be added to the copy job schedule name. Default is \"LSCopy_[DestinationServerName]_[DatabaseName]\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CopyScheduleDisabled Parameter to set the copy schedule to disabled upon creation. By default the schedule is enabled. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CopyScheduleFrequencyType A value indicating when a job is to be executed. Allowed values are \"Daily\", \"AgentStart\", \"IdleComputer\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Daily,Weekly,AgentStart,IdleComputer | -CopyScheduleFrequencyInterval The number of type periods to occur between each execution of the copy job. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CopyScheduleFrequencySubdayType Specifies the units for the subday FrequencyInterval. Allowed values are \"Time\", \"Seconds\", \"Minutes\", \"Hours\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Time,Seconds,Minutes,Hours | -CopyScheduleFrequencySubdayInterval The number of subday type periods to occur between each execution of the copy job. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -CopyScheduleFrequencyRelativeInterval A job's occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -CopyScheduleStartDate The date on which execution of a job can begin. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CopyScheduleEndDate The date on which execution of a job can stop. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CopyScheduleStartTime The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock. Example: '010000' for 01:00:00 AM. Example: '140000' for 02:00:00 PM. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CopyScheduleEndTime The time on any day to end execution of a job. Format HHMMSS / 24 hour clock. Example: '010000' for 01:00:00 AM. Example: '140000' for 02:00:00 PM. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DisconnectUsers Forces disconnection of users from the secondary database during transaction log restore operations. Use this with standby mode when you need to ensure restores complete successfully despite active connections. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FullBackupPath Specifies the path to an existing full database backup to initialize the secondary database. Use this when you have a recent backup available and want to avoid creating a new full backup for initialization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -GenerateFullBackup Creates a new full backup of the source database and restores it to initialize the secondary database. Use this when no existing backup is available or when you want to ensure the secondary starts with the most current data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -HistoryRetention Sets how long log shipping history information is kept in the monitor server, specified in minutes. Defaults to 14420 minutes (approximately 10 days). Longer retention provides more historical data for troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -NoRecovery Keeps the secondary database in NORECOVERY mode, making it unavailable for read access but ready for continuous log restores. This is the default mode and maintains the fastest restore performance for log shipping. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoInitialization Skips secondary database initialization, assuming the database already exists in NORECOVERY mode on the destination. Use this when you have manually restored the database or used a different method to initialize it. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -PrimaryMonitorServer Specifies the SQL Server instance that monitors the primary server's log shipping operations. Defaults to the source instance itself. Use a dedicated monitor server in production environments for centralized monitoring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PrimaryMonitorCredential Allows you to login to enter a secure credential. Only needs to be used when the PrimaryMonitorServerSecurityMode is 0 or \"sqlserver\" To use: $scred = Get-Credential, then pass $scred object to the -PrimaryMonitorCredential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PrimaryMonitorServerSecurityMode The security mode used to connect to the monitor server for the primary server. Allowed values are 0, \"sqlserver\", 1, \"windows\" The default is 1 or Windows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 0,sqlserver,1,windows | -PrimaryThresholdAlertEnabled Enables the Threshold alert for the primary database | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -RestoreDataFolder Sets the destination folder for database data files during secondary database initialization. Only used with GenerateFullBackup or UseExistingFullBackup. Defaults to the secondary instance's default data directory if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestoreLogFolder Sets the destination folder for database log files during secondary database initialization. Only used with GenerateFullBackup or UseExistingFullBackup. Defaults to the secondary instance's default log directory if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestoreDelay Introduces a delay in minutes before applying transaction log restores on the secondary database. Defaults to 0 (no delay). Use this to create a time buffer for recovering from accidental data changes on the primary. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RestoreAlertThreshold Sets the alert threshold in minutes for detecting restore operation delays on the secondary database. An alert is generated if no restore occurs within this timeframe. Defaults to 45 minutes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RestoreJob Name of the restore job that will be created in the SQL Server agent. The parameter works as a prefix where the name of the database will be added to the restore job name. The default is \"LSRestore_[databasename]\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestoreRetention The backup retention period in minutes. Default is 4320 / 72 hours | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RestoreSchedule Name of the backup schedule created for the restore job. The parameter works as a prefix where the name of the database will be added to the restore job schedule name. Default is \"LSRestore_[DestinationServerName]_[DatabaseName]\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestoreScheduleDisabled Parameter to set the restore schedule to disabled upon creation. By default the schedule is enabled. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -RestoreScheduleFrequencyType A value indicating when a job is to be executed. Allowed values are \"Daily\", \"AgentStart\", \"IdleComputer\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Daily,Weekly,AgentStart,IdleComputer | -RestoreScheduleFrequencyInterval The number of type periods to occur between each execution of the restore job. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestoreScheduleFrequencySubdayType Specifies the units for the subday FrequencyInterval. Allowed values are \"Time\", \"Seconds\", \"Minutes\", \"Hours\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Time,Seconds,Minutes,Hours | -RestoreScheduleFrequencySubdayInterval The number of subday type periods to occur between each execution of the restore job. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RestoreScheduleFrequencyRelativeInterval A job's occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RestoreScheduleStartDate The date on which execution of a job can begin. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestoreScheduleEndDate The date on which execution of a job can stop. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestoreScheduleStartTime The time on any day to begin execution of a job. Format HHMMSS / 24 hour clock. Example: '010000' for 01:00:00 AM. Example: '140000' for 02:00:00 PM. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestoreScheduleEndTime The time on any day to end execution of a job. Format HHMMSS / 24 hour clock. Example: '010000' for 01:00:00 AM. Example: '140000' for 02:00:00 PM. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestoreThreshold Specifies the maximum time in minutes allowed between restore operations before triggering an alert. Defaults to 45 minutes. Set this based on your RTO requirements and backup frequency. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -SecondaryDatabasePrefix Adds a prefix to the secondary database name to distinguish it from the primary database. Useful when the secondary database resides on the same instance as the primary or for naming conventions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecondaryDatabaseSuffix Adds a suffix to the secondary database name to distinguish it from the primary database. Common suffixes include '_LS' for log shipping or '_DR' for disaster recovery. Automatically applied when source and destination are the same instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecondaryMonitorServer Is the name of the monitor server for the secondary server. Defaults to monitor on the instance provided via DestinationSqlInstance param. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecondaryMonitorCredential Allows you to login to enter a secure credential. Only needs to be used when the SecondaryMonitorServerSecurityMode is 0 or \"sqlserver\" To use: $scred = Get-Credential, then pass $scred object to the -SecondaryMonitorCredential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecondaryMonitorServerSecurityMode The security mode used to connect to the monitor server for the secondary server. Allowed values are 0, \"sqlserver\", 1, \"windows\" The default is 1 or Windows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 0,sqlserver,1,windows | -SecondaryThresholdAlertEnabled Enables the Threshold alert for the secondary database | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Standby Places the secondary database in STANDBY mode, allowing read-only access for reporting purposes. Users are disconnected during log restores. Alternative to NORECOVERY mode when you need read access to secondary data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -StandbyDirectory Specifies the directory where standby files (.tuf) are created when using STANDBY mode. Required when using the Standby parameter. These files contain uncommitted transactions that are temporarily backed out during restore operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -UseExistingFullBackup Uses the most recent full backup from backup history to initialize the secondary database. The function automatically locates and uses the latest full backup of the source database for initialization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UseBackupFolder Specifies a folder containing backup files (full and/or differential) to initialize the secondary database. The function processes all backup files in the folder to bring the secondary database up to the latest available point in time. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IgnoreFileChecks Skips path validation checks before backup operations. Use this when SQL Server cannot verify that the backup path exists, for example when the network share is created just before the backup and there is latency in the path becoming visible to SQL Server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Bypasses confirmations and applies default values for missing parameters like copy destination folder. Also removes existing schedules with the same name and sets automatic database suffix when source and destination instances are identical. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database that was configured for log shipping, containing setup results and status information. Properties: PrimaryInstance: The full SQL Server instance name (computer\\instance) of the primary/source server SecondaryInstance: The full SQL Server instance name (computer\\instance) of the secondary/destination server PrimaryDatabase: Name of the database on the primary instance that was configured for log shipping SecondaryDatabase: Name of the database on the secondary instance (may have prefix/suffix applied) Result: Setup status for this database configuration - \"Success\" if all log shipping components were created successfully, \"Failed\" if any step failed Comment: Additional information about the setup result, typically populated with error details when Result is \"Failed\" &nbsp;"
  },
  {
    "name": "Invoke-DbaDbLogShipRecovery",
    "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't 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.",
    "category": "Utilities",
    "tags": [
      "logshipping"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbLogShipRecovery",
    "popularityRank": 235,
    "synopsis": "Brings log shipped secondary databases online for disaster recovery or planned migration scenarios",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbLogShipRecovery View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Brings log shipped secondary databases online for disaster recovery or planned migration scenarios 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. The 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. Next, it runs the log shipping restore job to apply any remaining transaction log backups that haven't been restored yet. Both the copy and restore jobs are monitored until completion, then disabled to prevent them from running again. Finally, 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. By 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. All operations are tracked through the msdb database log shipping tables to ensure consistency and proper sequencing of the recovery steps. Syntax Invoke-DbaDbLogShipRecovery [[-SqlInstance] ] [[-Database] ] [[-SqlCredential] ] [-NoRecovery] [-EnableException] [-Force] [[-InputObject] ] [[-Delay] ] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Recovers all the databases on the instance that are enabled for log shipping PS C:\\> Invoke-DbaDbLogShipRecovery -SqlInstance server1 -Force Example 2: Recovers all the databases on the instance that are enabled for log shipping using a credential PS C:\\> Invoke-DbaDbLogShipRecovery -SqlInstance server1 -SqlCredential $cred -Verbose -Force Example 3: Recovers the database &quot;db_logship&quot; to a normal status PS C:\\> Invoke-DbaDbLogShipRecovery -SqlInstance server1 -database db_logship -Verbose Example 4: Recovers the database db1, db2, db3, db4 to a normal status PS C:\\> db1, db2, db3, db4 | Invoke-DbaDbLogShipRecovery -SqlInstance server1 -Verbose Example 5: Shows what would happen if the command were executed PS C:\\> Invoke-DbaDbLogShipRecovery -SqlInstance server1 -Force -WhatIf Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the log-shipped secondary databases to recover. Accepts multiple database names and wildcards for pattern matching. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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 read-write operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use 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 -Database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Particularly useful when you need to recover databases based on specific criteria like database state or properties rather than just database names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 5 | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database recovered, containing the outcome and status of the log shipping recovery operation. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the log shipped secondary database that was recovered RecoverResult: The final result of the recovery operation - either \"Success\" or \"Failed\" Comment: Additional details about the recovery operation or error message if the recovery failed &nbsp;"
  },
  {
    "name": "Invoke-DbaDbMirrorFailover",
    "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.",
    "category": "Utilities",
    "tags": [
      "mirroring",
      "mirror",
      "ha"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbMirrorFailover",
    "popularityRank": 467,
    "synopsis": "Fails over database mirroring configurations to the mirror server",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbMirrorFailover View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Fails over database mirroring configurations to the mirror server 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. Syntax Invoke-DbaDbMirrorFailover [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-InputObject] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Fails over the pubs database on sql2016 PS C:\\> Invoke-DbaDbMirrorFailover -SqlInstance sql2016 -Database pubs Fails over the pubs database on sql2016. Prompts for confirmation. Example 2: Forces the failover of the pubs database on sql2016 and allows data loss PS C:\\> Get-DbaDatabase -SqlInstance sql2016 -Database pubs | Invoke-DbaDbMirrorFailover -Force -Confirm:$false Forces the failover of the pubs database on sql2016 and allows data loss. Does not prompt for confirmation. Optional Parameters -SqlInstance SQL Server name or SMO object representing the primary SQL Server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which mirrored databases to fail over to their mirror partners. Accepts multiple database names. Use this when you need to fail over specific databases rather than piping database objects from Get-DbaDatabase. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase through the pipeline for failover operations. This enables you to filter databases using Get-DbaDatabase and pipe the results directly to perform failovers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Force Forces an immediate failover that allows data loss, primarily for asynchronous mirroring or emergency situations. Without this switch, the function performs a safe synchronous failover by setting safety to Full before failing over. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Database Returns 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 new role (now the principal server). Default properties visible: Name: Database name Status: Current database status Owner: Database owner login RecoveryModel: Database recovery model (typically Full for mirrored databases) Size: Database size in megabytes When no failover is performed due to -WhatIf or user cancellation, no output is returned. &nbsp;"
  },
  {
    "name": "Invoke-DbaDbMirroring",
    "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't 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're 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.",
    "category": "Utilities",
    "tags": [
      "mirroring",
      "mirror",
      "ha"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbMirroring",
    "popularityRank": 340,
    "synopsis": "Creates and configures database mirroring between SQL Server instances with full validation and setup",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbMirroring View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates and configures database mirroring between SQL Server instances with full validation and setup 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. The function performs comprehensive validation before setup and handles all the technical requirements: Verifies that mirroring is possible between the specified instances and databases Sets the recovery model to Full if needed (required for mirroring) Creates and restores full and log backups to initialize the mirror database if it doesn't exist Sets up database mirroring endpoints on all participating instances Creates logins and grants CONNECT permissions to service accounts on all endpoints Starts endpoints if they're not already running Establishes the mirroring partnership between primary and mirror Configures witness server if specified for automatic failover scenarios This 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. NOTE: If backup/restore is performed, the backup files will remain on the network share for your records. Syntax Invoke-DbaDbMirroring [[-Primary] ] [[-PrimarySqlCredential] ] [-Mirror] [[-MirrorSqlCredential] ] [[-Witness] ] [[-WitnessSqlCredential] ] [[-Database] ] [[-EndpointEncryption] ] [[-EncryptionAlgorithm] ] [[-SharedPath] ] [[-InputObject] ] [-UseLastBackup] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Performs a bunch of checks to ensure the pubs database on sql2017a can be mirrored from sql2017a to sql2017b PS C:\\> $params = @{ >> Primary = 'sql2017a' >> Mirror = 'sql2017b' >> MirrorSqlCredential = 'sqladmin' >> Witness = 'sql2019' >> Database = 'pubs' >> SharedPath = '\\\\nas\\sql\\share' >> } >> PS C:\\> Invoke-DbaDbMirroring @params Performs a bunch of checks to ensure the pubs database on sql2017a can be mirrored from sql2017a to sql2017b. Logs in to sql2019 and sql2017a using Windows credentials and sql2017b using a SQL credential. Prompts for confirmation for most changes. To avoid confirmation, use -Confirm:$false or use the syntax in the second example. Example 2: Performs a bunch of checks to ensure the pubs database on sql2017a can be mirrored from sql2017a to sql2017b PS C:\\> $params = @{ >> Primary = 'sql2017a' >> Mirror = 'sql2017b' >> MirrorSqlCredential = 'sqladmin' >> Witness = 'sql2019' >> Database = 'pubs' >> SharedPath = '\\\\nas\\sql\\share' >> Force = $true >> Confirm = $false >> } >> PS C:\\> Invoke-DbaDbMirroring @params Performs a bunch of checks to ensure the pubs database on sql2017a can be mirrored from sql2017a to sql2017b. Logs in to sql2019 and sql2017a using Windows credentials and sql2017b using a SQL credential. Drops existing pubs database on Mirror and restores it with a fresh backup. Does all the things in the description, does not prompt for confirmation. Example 3: Restores backups from sql2017a to a specific file structure on sql2017b then creates mirror with no prompts... PS C:\\> $map = @{ 'database_data' = 'M:\\Data\\database_data.mdf' 'database_log' = 'L:\\Log\\database_log.ldf' } PS C:\\> Get-ChildItem \\\\nas\\seed | Restore-DbaDatabase -SqlInstance sql2017b -FileMapping $map -NoRecovery PS C:\\> Get-DbaDatabase -SqlInstance sql2017a -Database pubs | Invoke-DbaDbMirroring -Mirror sql2017b -Confirm:$false Restores backups from sql2017a to a specific file structure on sql2017b then creates mirror with no prompts for confirmation. Example 4: Mirrors pubs on sql2017a to sql2017b and uses the last full and logs from sql2017a to seed PS C:\\> Get-DbaDatabase -SqlInstance sql2017a -Database pubs | >> Invoke-DbaDbMirroring -Mirror sql2017b -UseLastBackup -Confirm:$false Mirrors pubs on sql2017a to sql2017b and uses the last full and logs from sql2017a to seed. Doesn't prompt for confirmation. Required Parameters -Mirror Specifies the SQL Server instance(s) that will serve as the mirror server(s) in the mirroring partnership. This is where the mirrored database copies will be created and maintained. Supports multiple mirror instances for creating mirror partnerships with different servers. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -Primary Specifies the SQL Server instance that will serve as the primary (principal) server in the mirroring partnership. Use this when setting up mirroring from scratch rather than piping database objects from Get-DbaDatabase. Must be paired with the Database parameter to identify which databases to mirror. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PrimarySqlCredential Alternative credentials for connecting to the primary SQL Server instance. Required when the current user context doesn't have sufficient permissions on the primary server. Accepts PowerShell credential objects created with Get-Credential for SQL Authentication or domain accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MirrorSqlCredential Alternative credentials for connecting to the mirror SQL Server instance(s). Required when the current user context doesn't have sufficient permissions on the mirror server. Accepts PowerShell credential objects created with Get-Credential for SQL Authentication or domain accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Witness Specifies the SQL Server instance that will serve as the witness server for automatic failover scenarios. Optional parameter that enables high safety mode with automatic failover when all three servers can communicate. Leave empty if you only need high safety mode without automatic failover or high performance mode. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -WitnessSqlCredential Alternative credentials for connecting to the witness SQL Server instance. Required when the current user context doesn't have sufficient permissions on the witness server. Accepts PowerShell credential objects created with Get-Credential for SQL Authentication or domain accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which database(s) on the primary server to set up for mirroring. Required when using the Primary parameter instead of piping from Get-DbaDatabase. Supports multiple database names to set up mirroring for several databases in a single operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EndpointEncryption Controls the encryption requirement for database mirroring endpoints created during setup. Default is 'Required' which enforces encrypted communication between all mirroring partners. Use 'Supported' to allow both encrypted and unencrypted connections, or 'Disabled' to prevent encryption. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Required | | Accepted Values | Disabled,Required,Supported | -EncryptionAlgorithm Specifies the encryption algorithm used by database mirroring endpoints for secure communication. Default is 'Aes' which provides strong encryption with good performance. Consider 'AesRC4' or 'RC4Aes' for compatibility with older SQL Server versions in mixed environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Aes | | Accepted Values | Aes,AesRC4,None,RC4,RC4Aes | -SharedPath Network share path accessible by all SQL Server service accounts for backup and restore operations. Required when the mirror database doesn't exist and needs to be initialized from backups. Must have read/write permissions for the service accounts running SQL Server on primary and mirror instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase to set up mirroring for specific databases. Use this approach when you want to filter databases first or work with existing database objects. Alternative to using the Primary and Database parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -UseLastBackup Uses the most recent full and log backups from the primary server to initialize the mirror database. Avoids creating new backups when recent ones already exist and are sufficient for mirroring setup. Requires the primary database to be in Full recovery model with existing backup history. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Drops and recreates the mirror database even if it already exists, using fresh backups from the primary. Use this when you need to completely reinitialize mirroring or when the existing mirror database is corrupted. Requires either SharedPath for new backups or UseLastBackup to use existing ones. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database successfully configured for mirroring, containing configuration summary information for the mirroring partnership. Default display properties (via Select-DefaultView): Without witness server: Primary: The SQL Server instance serving as the primary (principal) server Mirror: The SQL Server instance serving as the mirror server Database: The name of the database configured for mirroring Status: Status of the mirroring setup (Success indicates successful configuration) With witness server: Primary: The SQL Server instance serving as the primary (principal) server Mirror: The SQL Server instance serving as the mirror server Witness: The SQL Server instance configured as the witness server for automatic failover Database: The name of the database configured for mirroring Status: Status of the mirroring setup (Success indicates successful configuration) Additional properties available (from PSCustomObject): ServiceAccount: String array of SQL Server service accounts that were granted CONNECT permissions on the mirroring endpoints Output occurs only when the ShouldProcess block executes successfully. Multiple objects are returned when mirroring is configured for multiple databases or to multiple mirror instances. &nbsp;"
  },
  {
    "name": "Invoke-DbaDbPiiScan",
    "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 <dbatools module root>\\bin\\datamasking\\pii-knownnames.json and <dbatools module root>\\bin\\datamasking\\pii-patterns.json.",
    "category": "Utilities",
    "tags": [
      "datamasking",
      "gdpr",
      "pii"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbPiiScan",
    "popularityRank": 230,
    "synopsis": "Command to return any columns that could potentially contain PII (Personal Identifiable Information)",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbPiiScan View Source Sander Stad (@sqlstad, sqlstad.nl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Command to return any columns that could potentially contain PII (Personal Identifiable Information) Description This command will go through the tables in your database and assess each column. It will first check the columns names if it was named in such a way that it would indicate PII. The next thing that it will do is pattern recognition by looking into the data from the table. Custom scan definitions can be specified using the formats seen in \\bin\\datamasking\\pii-knownnames.json and \\bin\\datamasking\\pii-patterns.json. Syntax Invoke-DbaDbPiiScan [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Table] ] [[-Column] ] [[-Country] ] [[-CountryCode] ] [[-ExcludeTable] ] [[-ExcludeColumn] ] [[-SampleCount] ] [[-KnownNameFilePath] ] [[-PatternFilePath] ] [-ExcludeDefaultKnownName] [-ExcludeDefaultPattern] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Scan the database db1 on instance sql1 PS C:\\> Invoke-DbaDbPiiScan -SqlInstance sql1 -Database db1 Example 2: Scan multiple databases on multiple instances PS C:\\> Invoke-DbaDbPiiScan -SqlInstance sql1, sql2 -Database db1, db2 Example 3: Scan database db2 but exclude the column firstname PS C:\\> Invoke-DbaDbPiiScan -SqlInstance sql1 -Database db2 -ExcludeColumn firstname Example 4: Scan database db2 but only apply data patterns used for the United States PS C:\\> Invoke-DbaDbPiiScan -SqlInstance sql1 -Database db2 -CountryCode US Example 5: Scans db1 on instance sql1 with additional custom patterns PS C:\\> Invoke-DbaDbPiiScan -SqlInstance sql1 -Database db1 -PatternFilePath c:\\pii\\patterns.json Example 6: Scans db1 on instance sql1 with additional custom patterns, excluding the default patterns PS C:\\> Invoke-DbaDbPiiScan -SqlInstance sql1 -Database db1 -PatternFilePath c:\\pii\\patterns.json -ExcludeDefaultPattern Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the databases to scan for potential PII data. Required parameter - at least one database must be specified. Use this to target specific databases rather than scanning entire SQL Server instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Limits the scan to specific tables within the target databases. Accepts multiple table names. Use this when you need to focus PII scanning on known tables containing sensitive data rather than scanning all tables. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Column Restricts the scan to specific columns within the target tables. Accepts multiple column names. Use this when you want to validate specific columns suspected of containing PII or to recheck previously identified columns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Country Filters PII pattern matching to specific countries using full country names (e.g., \"United States\", \"Canada\"). Use this when your data contains region-specific formats like phone numbers or postal codes that should only match certain countries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CountryCode Filters PII pattern matching to specific countries using ISO country codes (e.g., \"US\", \"CA\", \"GB\"). Use this for more precise regional filtering when you know the specific country codes for your data regions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeTable Prevents scanning of specified tables even if they would otherwise be included in the scan scope. Use this to skip known system tables, staging tables, or tables confirmed to not contain PII data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeColumn Prevents scanning of specified columns even if they would otherwise be included in the scan scope. Use this to skip columns like timestamps, IDs, or other fields confirmed to not contain PII data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SampleCount Sets the number of data rows to examine per column for pattern matching. Default is 100 rows. Increase this value for more thorough scanning of large tables, or decrease it to speed up scans of tables with consistent data patterns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 100 | -KnownNameFilePath Specifies a JSON file path containing custom column name patterns that indicate PII data. Use this to add organization-specific column naming conventions that should be flagged as potential PII beyond the default patterns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PatternFilePath Specifies a JSON file path containing custom regex patterns for identifying PII data within column values. Use this to add custom data patterns specific to your organization or industry that aren't covered by the default patterns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDefaultKnownName Disables the built-in column name patterns for PII detection, using only custom patterns if provided. Use this when the default column name patterns generate too many false positives for your specific database schema conventions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeDefaultPattern Disables the built-in data value patterns for PII detection, using only custom patterns if provided. Use this when the default data patterns don't match your data formats or generate excessive false positives. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per detected PII finding across all scanned databases, tables, and columns. The result set includes classification information, masking recommendations, and detection method details. Default properties returned (all findings): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database scanned Schema: The schema name containing the table Table: The table name containing the potential PII column Column: The column name that was flagged as containing potential PII PII-Category: Classification category for the PII data (e.g., Identity, Location, Contact) PII-Name: Specific name of the PII type detected (e.g., SSN, Geography, Phone) FoundWith: Detection method used - DataType, KnownName, or Pattern MaskingType: Recommended type of data masking for this PII (e.g., Random, Shuffle, Partial) MaskingSubType: Sub-type of the masking method (e.g., Decimal, String, Date) Additional properties based on detection method: When FoundWith = \"Pattern\" (pattern-matched data): Country: Country filter applied to the pattern matching rule CountryCode: ISO country code for the matched pattern Pattern: The regex pattern that matched the data Description: Human-readable description of the pattern When FoundWith = \"KnownName\" (column name match): Pattern: The column name pattern that matched When FoundWith = \"DataType\" (geography type): No additional properties beyond the default set &nbsp;"
  },
  {
    "name": "Invoke-DbaDbShrink",
    "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's 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.",
    "category": "Database Operations",
    "tags": [
      "shrink",
      "database"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbShrink",
    "popularityRank": 57,
    "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's transaction log\n- Shrinks can require a lot of time and system resources to perform data movement",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbShrink View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Reduces the physical size of database files by removing unused space from data and log files. Shrinks can cause severe index fragmentation (to the tune of 99%) Shrinks can cause massive growth in the database's transaction log Shrinks can require a lot of time and system resources to perform data movement 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. Use 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's effects. Many 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: http://www.sqlskills.com/blogs/paul/why-you-should-not-shrink-your-data-files https://www.itprotoday.com/sql-server/shrinking-data-files However, there are some cases where a database will need to be shrunk. In the event that you must shrink your database: 1. Ensure you have plenty of space for your T-Log to grow 2. Understand that shrinks require a lot of CPU and disk resources 3. Consider running DBCC INDEXDEFRAG or ALTER INDEX ... REORGANIZE after the shrink is complete. Syntax Invoke-DbaDbShrink [[-SqlInstance] ] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-AllUserDatabases] [-PercentFreeSpace ] [-ShrinkMethod ] [-FileType ] [-StepSize ] [-StatementTimeout ] [-WaitAtLowPriority] [-AbortAfterWait ] [-ExcludeIndexStats] [-ExcludeUpdateUsage] [-EnableException] [-InputObject ] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Shrinks Northwind, pubs and Adventureworks2014 to have as little free space as possible PS C:\\> Invoke-DbaDbShrink -SqlInstance sql2016 -Database Northwind,pubs,Adventureworks2014 Example 2: Shrinks AdventureWorks2014 to have 50% free space PS C:\\> Invoke-DbaDbShrink -SqlInstance sql2014 -Database AdventureWorks2014 -PercentFreeSpace 50 Shrinks AdventureWorks2014 to have 50% free space. So let's say AdventureWorks2014 was 1GB and it's using 100MB space. The database free space would be reduced to 50MB. Example 3: Shrinks AdventureWorks2014 to have 50% free space, runs shrinks in 25MB chunks for improved performance PS C:\\> Invoke-DbaDbShrink -SqlInstance sql2014 -Database AdventureWorks2014 -PercentFreeSpace 50 -FileType Data -StepSize 25MB Example 4: Shrinks all user databases on SQL2012 (not ideal for production) PS C:\\> Invoke-DbaDbShrink -SqlInstance sql2012 -AllUserDatabases Example 5: Shrinks all databases coming from a pre-filtered list via Get-DbaDatabase PS C:\\> Get-DbaDatabase -SqlInstance sql2012 -Database Northwind,pubs | Invoke-DbaDbShrink Example 6: Shrinks AdventureWorks2014 using WAIT_AT_LOW_PRIORITY, killing blocking sessions if the wait expires PS C:\\> Invoke-DbaDbShrink -SqlInstance sql2022 -Database AdventureWorks2014 -WaitAtLowPriority -AbortAfterWait Blockers Shrinks AdventureWorks2014 using WAIT_AT_LOW_PRIORITY, killing blocking sessions if the wait expires. Requires SQL Server 2022+. Optional Parameters -SqlInstance The target SQL Server instance or instances. Defaults to the default instance on localhost. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to shrink on the target instance. Accepts wildcard patterns and multiple database names. Use this when you need to shrink specific databases rather than all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the shrink operation when processing multiple databases. Accepts wildcard patterns. Useful when shrinking all user databases but want to skip critical production databases or those with specific maintenance windows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllUserDatabases Targets all user databases on the instance, excluding system databases (master, model, msdb, tempdb). Use this for maintenance operations across an entire instance while preserving system database integrity. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -PercentFreeSpace Sets the percentage of free space to maintain in the database files after shrinking, ranging from 0-99. Defaults to 0. Leave some free space (10-20%) to accommodate normal database growth and reduce the need for frequent auto-growth events. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -ShrinkMethod Controls how SQL Server performs the shrink operation. Default moves data pages and truncates files. EmptyFile migrates all data to other files in the filegroup. NoTruncate moves pages but doesn't truncate. TruncateOnly reclaims space without moving data. Use TruncateOnly when possible as it's the least resource-intensive and doesn't cause data movement or fragmentation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Default | | Accepted Values | 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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | All | | Accepted Values | All,Data,Log | -StepSize Breaks large shrink operations into smaller chunks of the specified size. Use PowerShell size notation like 100MB or 1GB. Chunked shrinks reduce resource contention and allow for better progress monitoring during large shrink operations. Recommended for databases being shrunk by several gigabytes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -StatementTimeout Sets the command timeout in minutes for the shrink operation. Defaults to 0 (infinite timeout). Large database shrinks can take hours to complete, so the default allows operations to run without timing out. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -WaitAtLowPriority Instructs DBCC SHRINKFILE to wait at low priority for schema modification locks, minimizing blocking of other sessions. Requires SQL Server 2022 (version 16) or later. When a lock cannot be obtained, SQL Server will abort the operation after approximately one minute and log error 49516. The AbortAfterWait parameter controls what is aborted. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AbortAfterWait Specifies what to abort when the WAIT_AT_LOW_PRIORITY wait period expires. Valid values are Self and Blockers. Self aborts the shrink operation itself. Blockers kills the user sessions that block the lock acquisition. Defaults to Self. Only applies when WaitAtLowPriority is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Self | | Accepted Values | Self,Blockers | -ExcludeIndexStats Skips collecting index fragmentation statistics before and after the shrink operation. Use this to speed up the shrink process when you don't need fragmentation analysis or are planning to rebuild indexes immediately afterward. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeUpdateUsage Skips running DBCC UPDATEUSAGE before the shrink operation to ensure accurate space usage statistics. Use this to reduce operation time when space usage statistics are already current or when immediate shrinking is more important than precision. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database objects from the pipeline, typically from Get-DbaDatabase output. Use this for advanced filtering scenarios or when combining multiple database operations in a pipeline. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -WhatIf Shows what would happen if the command were to run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts for confirmation of every step. For example: Are you sure you want to perform this action? Performing the operation \"Shrink database\" on target \"pubs on SQL2016\\VNEXT\". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"): | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database file that was successfully shrunk, providing detailed metrics about the shrink operation including space reclaimed, fragmentation changes, and execution time. Default properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database containing the file File: The logical name of the database file that was shrunk Start: DateTime when the shrink operation began End: DateTime when the shrink operation completed Elapsed: Total execution time in HH:mm:ss format Success: Boolean indicating if the shrink operation completed successfully InitialSize: Original size of the file before shrinking (dbasize object) InitialUsed: Amount of space used in the file before shrinking (dbasize object) InitialAvailable: Amount of free space in the file before shrinking (dbasize object) TargetAvailable: Target amount of free space requested via -PercentFreeSpace parameter (dbasize object) FinalAvailable: Amount of free space remaining in the file after shrinking (dbasize object) FinalSize: Final size of the file after shrinking (dbasize object) InitialAverageFragmentation: Average index fragmentation percentage before shrinking (numeric, 0-100); null if -ExcludeIndexStats was used or SQL Server 2000 FinalAverageFragmentation: Average index fragmentation percentage after shrinking (numeric, 0-100); null if -ExcludeIndexStats was used or SQL Server 2000 InitialTopFragmentation: Maximum index fragmentation percentage before shrinking (numeric, 0-100); null if -ExcludeIndexStats was used or SQL Server 2000 FinalTopFragmentation: Maximum index fragmentation percentage after shrinking (numeric, 0-100); null if -ExcludeIndexStats was used or SQL Server 2000 Notes: Warning message about potential index fragmentation and recommended post-shrink maintenance When -ExcludeIndexStats is specified: The four fragmentation properties (InitialAverageFragmentation, FinalAverageFragmentation, InitialTopFragmentation, FinalTopFragmentation) are excluded from the output All other properties remain available All 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, .Megabytes, .Gigabytes, or .Terabytes properties for specific unit conversions. &nbsp;"
  },
  {
    "name": "Invoke-DbaDbTransfer",
    "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.",
    "category": "Utilities",
    "tags": [
      "general",
      "object"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbTransfer",
    "popularityRank": 293,
    "synopsis": "Transfers database objects and data between SQL Server instances or databases using SMO Transfer objects.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbTransfer View Source Kirill Kravtsov (@nvarscar) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Transfers database objects and data between SQL Server instances or databases using SMO Transfer objects. 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. Syntax Invoke-DbaDbTransfer [[-SqlInstance] ] [[-SqlCredential] ] [[-DestinationSqlInstance] ] [[-DestinationSqlCredential] ] [[-Database] ] [[-DestinationDatabase] ] [[-BatchSize] ] [[-BulkCopyTimeOut] ] [[-ScriptingOption] ] [[-InputObject] ] [-CopyAllObjects] [[-CopyAll] ] [-SchemaOnly] [-DataOnly] [-ScriptOnly] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copies all tables from database mydb on sql1 to database newdb on sql2 PS C:\\> Invoke-DbaDbTransfer -SqlInstance sql1 -DestinationSqlInstance sql2 -Database mydb -CopyAll Tables -DestinationDatabase newdb Example 2: Copies all objects from database mydb on sql1 to database mydb on sql2 PS C:\\> Invoke-DbaDbTransfer -SqlInstance sql1 -DestinationSqlInstance sql2 -Database mydb -CopyAllObjects Example 3: Copies object schema from database mydb on sql1 to database mydb on sql2 using customized transfer parameters PS C:\\> $transfer = New-DbaDbTransfer -SqlInstance sql1 -DestinationSqlInstance sql2 -Database mydb -CopyAllObjects PS C:\\> $transfer.Options.ScriptDrops = $true PS C:\\> $transfer.SchemaOnly = $true PS C:\\> $transfer | Invoke-DbaDbTransfer Example 4: Copies procedures from database mydb on sql1 to database mydb on sql2 using custom scripting parameters PS C:\\> $options = New-DbaScriptingOption PS C:\\> $options.ScriptDrops = $true PS C:\\> $transfer = New-DbaDbTransfer -SqlInstance sql1 -DestinationSqlInstance sql2 -Database mydb -CopyAll StoredProcedures -ScriptingOption $options PS C:\\> $transfer | Invoke-DbaDbTransfer Optional Parameters -SqlInstance Source SQL Server instance name. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this to specify a different server for migrations, environment promotions, or cross-server object synchronization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instance. Accepts PowerShell credentials created with Get-Credential. Only SQL Server Authentication is supported for destination connections. When not specified, the function uses Windows Integrated Authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Source database name containing the objects to transfer. This database must exist on the source SQL Server instance. Specify the exact database name - wildcards are not supported for this parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationDatabase Target database name where objects will be transferred to. If not specified, uses the same name as the source database. Use this when transferring objects to a database with a different name, such as during environment refreshes where databases have different naming conventions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $Database | -BatchSize Number of rows to transfer in each batch operation during data copy. Defaults to 50,000 rows per batch. Increase this value for faster transfers of large tables, or decrease it to reduce memory usage and lock duration on busy systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 50000 | -BulkCopyTimeOut Timeout in seconds for bulk copy operations when transferring table data. Defaults to 5000 seconds. Increase this value when transferring very large tables that take longer than the default timeout to complete. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 5000 | -ScriptingOption Custom scripting configuration created by New-DbaScriptingOption that controls how objects are scripted during transfer. Use this to customize object scripting behavior such as including permissions, indexes, triggers, or generating DROP statements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Pre-configured SMO Transfer object created by New-DbaDbTransfer that defines what to transfer and how. Use this when you need to customize transfer settings beyond what the direct parameters provide, or when reusing the same transfer configuration multiple times. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -CopyAllObjects Transfers all database objects including tables, views, stored procedures, functions, users, roles, and other database-level objects. Use this for complete database migrations where you need to copy everything from the source database to the destination. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CopyAll Specific types of database objects to transfer. Accepts an array of object type names for selective copying. Use this when you only need certain object types instead of everything, such as copying only tables and views for a data warehouse refresh. Common values include Tables, Views, StoredProcedures, UserDefinedFunctions, Users, Roles, and Schemas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this for setting up new environments where you need the database structure but will populate data separately, or for schema synchronization between environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DataOnly Transfers only table data without creating or modifying object schemas. Target objects must already exist in the destination database. Use this for data refreshes where the destination database structure is already in place and you only need to update the data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ScriptOnly Generates T-SQL scripts for creating the selected objects without actually executing the transfer. Use this to review what would be created, save scripts for later execution, or integrate with deployment pipelines that require script artifacts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (default behavior) Returns one object with transfer summary information when the transfer completes successfully. Properties: SourceInstance: Name of the source SQL Server instance SourceDatabase: Name of the source database DestinationInstance: Name of the destination SQL Server instance DestinationDatabase: Name of the destination database Status: Transfer status (returns \"Success\" when transfer completes) Elapsed: Time elapsed during the transfer operation displayed as a human-readable timespan (e.g., \"00:05:30\") Log: Array of event messages captured during transfer from DataTransferEvent events System.String array (when -ScriptOnly is specified) When -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. &nbsp;"
  },
  {
    "name": "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/",
    "category": "Database Operations",
    "tags": [
      "shrink",
      "database"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDbUpgrade",
    "popularityRank": 243,
    "synopsis": "Upgrades database compatibility level and performs post-upgrade maintenance tasks",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDbUpgrade View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Upgrades database compatibility level and performs post-upgrade maintenance tasks 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. Executes 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. Based on https://thomaslarock.com/2014/06/upgrading-to-sql-server-2014-a-dozen-things-to-check/ Syntax Invoke-DbaDbUpgrade [[-SqlInstance] ] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-NoCheckDb] [-NoUpdateUsage] [-NoUpdateStats] [-NoRefreshView] [-AllUserDatabases] [-Force] [-InputObject ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Runs the below processes against the databases -- Puts compatibility of database to level of SQL Instance... PS C:\\> Invoke-DbaDbUpgrade -SqlInstance PRD-SQL-MSD01 -Database Test Runs the below processes against the databases -- Puts compatibility of database to level of SQL Instance -- Changes the target recovery time to the new default of 60 seconds (for SQL Server 2016 and newer) -- Runs CHECKDB DATA_PURITY -- Runs DBCC UPDATESUSAGE -- Updates all users statistics -- Runs sp_refreshview against every view in the database Example 2: Runs the upgrade command skipping the sp_refreshview update on all views PS C:\\> Invoke-DbaDbUpgrade -SqlInstance PRD-SQL-INT01 -Database Test -NoRefreshView Example 3: If database Test is already at the correct compatibility, runs every necessary step PS C:\\> Invoke-DbaDbUpgrade -SqlInstance PRD-SQL-INT01 -Database Test -Force Example 4: Get only specific databases using GridView and pass those to Invoke-DbaDbUpgrade PS C:\\> Get-DbaDatabase -SqlInstance sql2016 | Out-GridView -Passthru | Invoke-DbaDbUpgrade Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to upgrade and run post-upgrade maintenance tasks on. Accepts wildcards for pattern matching. Use this when you need to target specific databases rather than processing all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the upgrade process when using -AllUserDatabases. Accepts wildcards for pattern matching. Useful for skipping system-critical databases or those with special maintenance windows during bulk upgrade operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoCheckDb Skips the DBCC CHECKDB with DATA_PURITY validation step during the upgrade process. Use this when you've recently run integrity checks or need to reduce upgrade time, though this removes corruption detection from the process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoUpdateUsage Skips the DBCC UPDATEUSAGE step that corrects inaccuracies in page and row count information. Use this when you're confident space usage statistics are accurate or need to minimize upgrade time for very large databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoUpdateStats Skips running sp_updatestats to refresh all user table statistics with current data distribution. Use this when statistics were recently updated or when you have a separate statistics maintenance plan in place. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoRefreshView Skips executing sp_refreshview on all user views to update their metadata for the new SQL Server version. Use this when you have no views or prefer to refresh view metadata manually to avoid potential view compilation issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AllUserDatabases Processes all user databases on the instance, excluding system databases. Cannot be used with -Database parameter. Use this for instance-wide upgrades after SQL Server version changes or when standardizing all databases to current compatibility levels. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Runs all maintenance tasks even on databases already at the correct compatibility level and target recovery time. Use this when you need to ensure CHECKDB, UPDATEUSAGE, statistics updates, and view refreshes run regardless of compatibility status. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database objects from the pipeline, typically from Get-DbaDatabase output. Cannot be used with -Database or -AllUserDatabases. Use this for targeted upgrades based on complex filtering criteria or when integrating with other dbatools commands in a pipeline. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts for confirmation of every step. For example: Are you sure you want to perform this action? Performing the operation \"Update database\" on target \"pubs on SQL2016\\VNEXT\". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"): | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database processed with detailed information about each upgrade operation performed. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: Name of the database that was upgraded OriginalCompatibility: Original database compatibility level before upgrade (e.g., \"100\", \"110\", \"140\") CurrentCompatibility: New database compatibility level after upgrade (e.g., \"100\", \"110\", \"140\") Compatibility: Result status of compatibility level update; values: version number if updated, \"No change\" if already correct, \"Fail\" if update failed TargetRecoveryTime: Result of target recovery time update; values: 60 if set to 60 seconds, \"No change\" if already 60 or SQL Server version < 2016, \"Fail\" if update failed DataPurity: Result of DBCC CHECKDB DATA_PURITY; values: \"Success\" if completed, \"Fail\" if failed, omitted if -NoCheckDb is specified UpdateUsage: Result of DBCC UPDATEUSAGE; values: \"Success\" if completed, \"Fail\" if failed, \"Skipped\" if -NoUpdateUsage is specified UpdateStats: Result of sp_updatestats; values: \"Success\" if completed, \"Fail\" if failed, \"Skipped\" if -NoUpdateStats is specified RefreshViews: Result of sp_refreshview on all user views; values: \"Success\" if all refreshed, \"Fail\" if any failed, \"Skipped\" if -NoRefreshView is specified &nbsp;"
  },
  {
    "name": "Invoke-DbaDiagnosticQuery",
    "description": "Runs Glenn Berry's 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.",
    "category": "Advanced Features",
    "tags": [
      "community",
      "glennberry"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaDiagnosticQuery",
    "popularityRank": 73,
    "synopsis": "Executes Glenn Berry's DMV diagnostic queries to assess SQL Server performance and health",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaDiagnosticQuery View Source Andre Kamman (@AndreKamman), andrekamman.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Executes Glenn Berry's DMV diagnostic queries to assess SQL Server performance and health Description Runs Glenn Berry's 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. The 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. This 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. Syntax Invoke-DbaDiagnosticQuery [-SqlInstance] [-Database ] [-ExcludeDatabase ] [-ExcludeQuery ] [-SqlCredential ] [-Path ] [-QueryName ] [-UseSelectionHelper] [-InstanceOnly] [-DatabaseSpecific] [-ExcludeQueryTextColumn] [-ExcludePlanColumn] [-NoColumnParsing] [-OutputPath ] [-ExportQueries] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Run the selection made by the user on the Sql Server instance specified PS C:\\> Invoke-DbaDiagnosticQuery -SqlInstance sql2016 Example 2: Provides a grid view with all the queries to choose from and will run the selection made by the user on the... PS C:\\> Invoke-DbaDiagnosticQuery -SqlInstance sql2016 -UseSelectionHelper | Export-DbaDiagnosticQuery -Path C:\\temp\\gboutput Provides 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. Then it will export the results to Export-DbaDiagnosticQuery. Example 3: Export All Queries to Disk PS C:\\> Invoke-DbaDiagnosticQuery -SqlInstance localhost -ExportQueries -OutputPath \"C:\\temp\\DiagnosticQueries\" Example 4: Export Database Specific Queries for all User Dbs PS C:\\> Invoke-DbaDiagnosticQuery -SqlInstance localhost -DatabaseSpecific -ExportQueries -OutputPath \"C:\\temp\\DiagnosticQueries\" Example 5: Export Database Specific Queries For One Target Database PS C:\\> Invoke-DbaDiagnosticQuery -SqlInstance localhost -DatabaseSpecific -DatabaseName 'tempdb' -ExportQueries -OutputPath \"C:\\temp\\DiagnosticQueries\" Example 6: Export Database Specific Queries For One Target Database and One Specific Query PS C:\\> Invoke-DbaDiagnosticQuery -SqlInstance localhost -DatabaseSpecific -DatabaseName 'tempdb' -ExportQueries -OutputPath \"C:\\temp\\DiagnosticQueries\" -QueryName 'Database-scoped Configurations' Example 7: Choose Queries To Export PS C:\\> Invoke-DbaDiagnosticQuery -SqlInstance localhost -UseSelectionHelper Example 8: Parse the appropriate diagnostic queries by connecting to server, and instead of running them, return as... PS C:\\> [PSObject[]]$results = Invoke-DbaDiagnosticQuery -SqlInstance localhost -WhatIf Parse the appropriate diagnostic queries by connecting to server, and instead of running them, return as [PSCustomObject[]] to work with further Example 9: Run diagnostic queries targeted at specific database, and only run database level queries against this... PS C:\\> $results = Invoke-DbaDiagnosticQuery -SqlInstance Sql2017 -DatabaseSpecific -QueryName 'Database-scoped Configurations' -DatabaseName TestStuff Run diagnostic queries targeted at specific database, and only run database level queries against this database. Required Parameters -SqlInstance The target SQL Server instance or instances. Can be either a string or SMO server | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Database Specifies which databases to run database-specific diagnostic queries against. Accepts wildcard patterns and multiple database names. When omitted, all user databases are processed. System databases are automatically excluded unless explicitly specified. | Property | Value | | --- | --- | | Alias | DatabaseName | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from database-level diagnostic query execution. Accepts wildcard patterns and multiple database names. Useful when you want to run diagnostics on most databases but skip problematic or maintenance databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeQuery Excludes specific diagnostic queries from execution by their query names. Accepts multiple query names as an array. Use this to skip time-consuming queries like index fragmentation analysis or queries that might cause blocking during peak hours. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | Credential | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies a custom directory containing Glenn Berry diagnostic query script files. By default, uses the scripts included with dbatools. Use this when you want to run newer diagnostic query versions downloaded from Glenn Berry's website or custom query collections. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -QueryName Runs only the specified diagnostic queries by their exact query names. Accepts multiple query names as an array. Use this when you know exactly which diagnostics you need, such as 'Wait Stats' or 'Top CPU Queries' for targeted performance analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -UseSelectionHelper Opens an interactive grid view showing all available diagnostic queries with descriptions for manual selection. Perfect for ad-hoc troubleshooting when you want to run only specific queries relevant to your current performance issue. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InstanceOnly Limits execution to server-level diagnostic queries only, skipping all database-specific queries. Ideal for quick instance health checks focusing on server configuration, wait statistics, and instance-wide performance metrics. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DatabaseSpecific Limits execution to database-level diagnostic queries only, skipping all instance-level queries. Use this when investigating database-specific issues like index fragmentation, table statistics, or database configuration problems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeQueryTextColumn Removes the [Complete Query Text] column from diagnostic query results to reduce output size and improve performance. Useful when you only need query execution statistics without the actual SQL text, especially for queries with large stored procedures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludePlanColumn Removes the [Query Plan] column from diagnostic query results to significantly reduce memory usage and improve performance. Essential when processing large result sets or when execution plan XML data is not needed for your analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoColumnParsing Disables all column parsing and formatting for [Complete Query Text] and [Query Plan] columns, returning raw data. Use this for maximum performance when you need the fastest possible execution and don't require formatted output columns. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -OutputPath Specifies the directory path where exported diagnostic query SQL files will be saved when using -ExportQueries. Files are automatically organized by server name, database name, and query name for easy identification and manual execution. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExportQueries Exports diagnostic queries as individual SQL files instead of executing them, organized by query type and target database. Useful for creating a library of diagnostic scripts for offline analysis, sharing with team members, or manual execution during maintenance windows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command would execute, but does not actually perform the command | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts to confirm certain actions | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per diagnostic query executed from Glenn Berry's query collection. Each object contains the query execution results along with metadata about the query and target database. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Number: The query number from Glenn Berry's diagnostic query collection Name: The name or title of the diagnostic query Description: Description of what the diagnostic query analyzes and why it's useful DatabaseSpecific: Boolean indicating if the query is database-specific (true) or instance-level (false) Database: Database name if DatabaseSpecific is true; null for instance-level queries Notes: Status notes; \"Empty Result for this Query\" if no rows returned, \"WhatIf - Bypassed Execution\" when -WhatIf is used, null for successful executions Result: The query result set as an array of DataRow objects containing the diagnostic data; null if no results or on WhatIf execution Special behaviors: When -ExportQueries is used, no output objects are returned; only SQL files are written to disk The Result property contains all columns from the diagnostic query output, formatted as DataRow objects Database-specific queries return one object per database queried, with Database property populated Instance-level queries return one object with Database set to null &nbsp;"
  },
  {
    "name": "Invoke-DbaPfRelog",
    "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.",
    "category": "Utilities",
    "tags": [
      "performance",
      "datacollector",
      "perfcounter",
      "relog"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaPfRelog",
    "popularityRank": 589,
    "synopsis": "Pipeline-compatible wrapper for the relog command which is available on modern Windows platforms.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Invoke-DbaPfRelog View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Pipeline-compatible wrapper for the relog command which is available on modern Windows platforms. Description Pipeline-compatible wrapper for the relog command. Relog is useful for converting Windows Perfmon. Extracts performance counters from performance counter logs into other formats, such as text-TSV (for tab-delimited text), text-CSV (for comma-delimited text), binary-BIN, or SQL. `relog \"C:\\PerfLogs\\Admin\\System Correlation\\WORKSTATIONX_20180112-000001\\DataCollector01.blg\" -o C:\\temp\\foo.csv -f tsv` If you find any input hangs, please send us the output so we can accommodate for it then use -Raw for an immediate solution. Syntax Invoke-DbaPfRelog [[-Path] ] [[-Destination] ] [[-Type] ] [-Append] [-AllowClobber] [[-PerformanceCounter] ] [[-PerformanceCounterPath] ] [[-Interval] ] [[-BeginTime] ] [[-EndTime] ] [[-ConfigPath] ] [-Summary] [[-InputObject] ] [-Multithread] [-AllTime] [-Raw] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Creates C:\\temp\\perfmon.tsv from C:\\temp\\perfmon.blg PS C:\\> Invoke-DbaPfRelog -Path C:\\temp\\perfmon.blg Example 2: Creates the temp, a, and b directories if needed, then generates c.tsv (tab separated) from... PS C:\\> Invoke-DbaPfRelog -Path C:\\temp\\perfmon.blg -Destination C:\\temp\\a\\b\\c Creates the temp, a, and b directories if needed, then generates c.tsv (tab separated) from C:\\temp\\perfmon.blg. Returns the newly created file as a file object. Example 3: Creates C:\\temp\\perf if needed, then generates computername-datacollectorname.tsv (tab separated) from the... PS C:\\> Get-DbaPfDataCollectorSet -ComputerName sql2016 | Get-DbaPfDataCollector | Invoke-DbaPfRelog -Destination C:\\temp\\perf Creates 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 avoid naming conflicts with piped input. Example 4 PS C:\\> Invoke-DbaPfRelog -Path C:\\temp\\perfmon.blg -Destination C:\\temp\\a\\b\\c -Raw >> [Invoke-DbaPfRelog][21:21:35] relog \"C:\\temp\\perfmon.blg\" -f csv -o C:\\temp\\a\\b\\c >> Input Example &gt;&gt; >> File(s): >> C:\\temp\\perfmon.blg (Binary) >> Begin: 1/13/2018 5:13:23 >> End: 1/13/2018 14:29:55 >> Samples: 2227 >> 100.00% >> Output Example &gt;&gt;: Creates the temp, a, and b directories if needed, then generates c.tsv (tab separated) from... >> File: C:\\temp\\a\\b\\c.csv >> Begin: 1/13/2018 5:13:23 >> End: 1/13/2018 14:29:55 >> Samples: 2227 >> The command completed successfully. Creates 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. Example 5: Creates the temp, a, and b directories if needed, then generates c.csv (comma separated) from C:\\temp\\perflog... PS C:\\> Invoke-DbaPfRelog -Path 'C:\\temp\\perflog with spaces.blg' -Destination C:\\temp\\a\\b\\c -Type csv -BeginTime ((Get-Date).AddDays(-30)) -EndTime ((Get-Date).AddDays(-1)) Creates the temp, a, and b directories if needed, then generates c.csv (comma separated) from C:\\temp\\perflog with spaces.blg', starts 30 days ago and ends one day ago. Example 6: Relogs latest data files from all collectors within the servers listed in $servers PS C:\\> $servers | Get-DbaPfDataCollectorSet | Get-DbaPfDataCollector | Invoke-DbaPfRelog -Multithread -AllowClobber Example 7: Relogs all the log files from the DataCollector01 on the local computer and allows overwrite PS C:\\> Get-DbaPfDataCollector -Collector DataCollector01 | Invoke-DbaPfRelog -AllowClobber -AllTime Optional Parameters -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. Use this when you have perfmon binary logs that need to be converted to readable formats like CSV or TSV for analysis. | Property | Value | | --- | --- | | Alias | FullName | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Destination Specifies the output file path or directory where converted performance data will be saved. Creates necessary directories automatically if they don't exist. When omitted, files are saved in the same directory as the source with the appropriate extension (.tsv, .csv, etc.). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies the output format for the converted performance data. Defaults to 'tsv' (tab-separated values). Use 'csv' for Excel compatibility, 'tsv' for easy parsing in PowerShell, 'bin' for binary format, or 'sql' to write directly to a SQL database via ODBC. For SQL output, specify the destination as 'DSN!counter_log' where DSN is configured in ODBC Manager. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | tsv | | Accepted Values | tsv,csv,bin,sql | -Append Appends performance data to an existing output file instead of overwriting it. Only works with binary (-Type bin) format. Use this when consolidating multiple perfmon logs into a single file for comprehensive analysis over time periods. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AllowClobber Overwrites existing output files without prompting. Required when the destination file already exists and you want to replace it. Use this in automated scripts or when you need to refresh converted performance data files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -PerformanceCounter Specifies specific performance counters to extract from the log files. Accepts counter paths like '\\Processor(_Total)\\% Processor Time'. Use this to filter large perfmon logs and extract only the counters you need for analysis, reducing output file size. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PerformanceCounterPath Specifies a text file containing performance counter paths to extract, one counter per line. Alternative to specifying counters directly. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Interval Specifies the sampling interval by including every nth data point from the original log. Reduces output size by skipping intermediate samples. Use this when working with high-frequency perfmon logs where you need less granular data for trend analysis rather than detailed monitoring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this to extract specific time periods from large perfmon logs, such as during a known performance incident or maintenance window. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EndTime Specifies the end time for data extraction using a DateTime object. Performance data after this time will be excluded from the output. Combine with BeginTime to extract data from specific time ranges, useful for analyzing performance during particular events or time periods. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ConfigPath Specifies a configuration file containing relog command-line parameters for complex or frequently-used conversion settings. Use this when you have standardized performance log processing requirements that need consistent parameters across multiple operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Summary Displays summary information about the performance log files including available counters and time ranges without performing the conversion. Use this to examine perfmon logs before processing them, helping you determine what counters are available and the time span covered. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts data collector objects from Get-DbaPfDataCollector and Get-DbaPfDataCollectorSet via pipeline input for automatic log file discovery. Use this to convert performance logs directly from active or configured data collectors without manually specifying file paths. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Multithread Processes multiple performance log files in parallel to improve performance when converting large batches of files. Use this when converting many perfmon logs simultaneously, especially beneficial on multi-core systems with large performance monitoring datasets. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when you need to convert historical performance data from all collection periods, not just the latest monitoring session. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Raw Displays the raw output from the relog command instead of returning file objects. Useful for debugging conversion issues or seeing detailed progress. Use this when troubleshooting relog operations or when you need to see the exact command-line output and statistics from the conversion process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo (default) Returns file objects for each successfully converted performance log file. Each file object includes all standard System.IO.FileInfo properties plus an added RelogFile property. Properties: FullName: The complete path to the converted output file Name: The file name with extension (.tsv, .csv, .bin, etc.) Directory: The directory containing the file DirectoryName: The full path of the directory Extension: The file extension (.tsv, .csv, .bin, .sql) Length: The size of the file in bytes Attributes: File attributes (Archive, ReadOnly, etc.) CreationTime: The date and time the file was created LastAccessTime: The date and time the file was last accessed LastWriteTime: The date and time the file was last modified RelogFile: Boolean NoteProperty set to true, indicating this file was created by relog conversion String (when -Raw is specified) Returns the raw output from the relog command including: Input file information (file path, format, begin/end times, sample count) Output file information (file path, format, begin/end times, sample count) Completion status message Processing progress percentage No output (when -Summary or -ExportQueries is specified) When -Summary is used, summary information is displayed as text output but no objects are returned. When relog output is written directly to SQL via ODBC, no file objects are available for return. &nbsp;"
  },
  {
    "name": "Invoke-DbaQuery",
    "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're 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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "query",
      "utility"
    ],
    "verb": "Invoke",
    "popular": true,
    "url": "/Invoke-DbaQuery",
    "popularityRank": 2,
    "synopsis": "Executes T-SQL queries, scripts, and stored procedures against SQL Server instances with parameterized query support",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaQuery View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Executes T-SQL queries, scripts, and stored procedures against SQL Server instances with parameterized query support 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're extracting data for reports, deploying scripts across multiple servers, or running maintenance commands. The 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. Built 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. Syntax Invoke-DbaQuery [[-SqlInstance] ] [-SqlCredential ] [-Database ] -Query [-QueryTimeout ] [-As ] [-SqlParameter ] [-CommandType {Text | StoredProcedure | TableDirect}] [-AppendServerInstance] [-MessagesToOutput] [-InputObject ] [-ReadOnly] [-NoExec] [-QuotedIdentifier] [-AppendConnectionString ] [-EnableException] [ ] Invoke-DbaQuery [[-SqlInstance] ] [-SqlCredential ] [-Database ] [-QueryTimeout ] -SqlObject [-As ] [-SqlParameter ] [-CommandType {Text | StoredProcedure | TableDirect}] [-AppendServerInstance] [-MessagesToOutput] [-InputObject ] [-ReadOnly] [-NoExec] [-QuotedIdentifier] [-AppendConnectionString ] [-EnableException] [ ] Invoke-DbaQuery [[-SqlInstance] ] [-SqlCredential ] [-Database ] [-QueryTimeout ] -File [-As ] [-SqlParameter ] [-CommandType {Text | StoredProcedure | TableDirect}] [-AppendServerInstance] [-MessagesToOutput] [-InputObject ] [-ReadOnly] [-NoExec] [-QuotedIdentifier] [-AppendConnectionString ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Runs the sql query &#39;SELECT foo FROM bar&#39; against the instance &#39;server\\instance&#39; PS C:\\> Invoke-DbaQuery -SqlInstance server\\instance -Query 'SELECT foo FROM bar' Example 2: Runs the sql query &#39;SELECT foo FROM bar&#39; against all instances in the group [GROUPNAME] on the CMS... PS C:\\> Get-DbaRegServer -SqlInstance [SERVERNAME] -Group [GROUPNAME] | Invoke-DbaQuery -Query 'SELECT foo FROM bar' Runs the sql query 'SELECT foo FROM bar' against all instances in the group [GROUPNAME] on the CMS [SERVERNAME] Example 3: Runs the sql commands stored in rebuild.sql against the instances &quot;server1&quot;, &quot;server1\\nordwind&quot; and &quot;server2&quot; PS C:\\> \"server1\", \"server1\\nordwind\", \"server2\" | Invoke-DbaQuery -File \"C:\\scripts\\sql\\rebuild.sql\" Example 4: Runs the sql commands stored in rebuild.sql against all accessible databases of the instances &quot;server1&quot;... PS C:\\> Get-DbaDatabase -SqlInstance \"server1\", \"server1\\nordwind\", \"server2\" | Invoke-DbaQuery -File \"C:\\scripts\\sql\\rebuild.sql\" Runs the sql commands stored in rebuild.sql against all accessible databases of the instances \"server1\", \"server1\\nordwind\" and \"server2\" Example 5: Executes a simple query against the users table using SQL Parameters PS C:\\> Invoke-DbaQuery -SqlInstance . -Query 'SELECT FROM users WHERE Givenname = @name' -SqlParameter @{ Name = \"Maria\" } Executes a simple query against the users table using SQL Parameters. This avoids accidental SQL Injection and is the safest way to execute queries with dynamic content. Keep in mind the limitations inherent in parameters - it is quite impossible to use them for content references. While it is possible to parameterize a where condition, it is impossible to use this to select which columns to select. The inserted text will always be treated as string content, and not as a reference to any SQL entity (such as columns, tables or databases). Example 6: Executes a query with ReadOnly application intent on aglistener1 PS C:\\> Invoke-DbaQuery -SqlInstance aglistener1 -ReadOnly -Query \"select something from readonlydb.dbo.atable\" Example 7: Executes a stored procedure Example_SP using SQL Parameters PS C:\\> Invoke-DbaQuery -SqlInstance server1 -Database tempdb -Query Example_SP -SqlParameter @{ Name = \"Maria\" } -CommandType StoredProcedure Example 8: Executes a stored procedure Example_SP using multiple SQL Parameters PS C:\\> $queryParameters = @{ >> StartDate = $startdate >> EndDate = $enddate >> } PS C:\\> Invoke-DbaQuery -SqlInstance server1 -Database tempdb -Query Example_SP -SqlParameter $queryParameters -CommandType StoredProcedure Example 9: Creates an TVP input parameter and uses it to invoke a stored procedure PS C:\\> $inparam = @() PS C:\\> $inparam += [PSCustomObject]@{ >> somestring = 'string1' >> somedate = '2021-07-15T01:02:00' >> } PS C:\\> $inparam += [PSCustomObject]@{ >> somestring = 'string2' >> somedate = '2021-07-15T02:03:00' >> } >> $inparamAsDataTable = ConvertTo-DbaDataTable -InputObject $inparam PS C:\\> $inparamAsSQLParameter = New-DbaSqlParameter -SqlDbType structured -Value $inparamAsDataTable -TypeName 'dbatools_tabletype' PS C:\\> Invoke-DbaQuery -SqlInstance localhost -Database master -CommandType StoredProcedure -Query my_proc -SqlParameter $inparamAsSQLParameter Example 10: Creates an output parameter and uses it to invoke a stored procedure PS C:\\> $output = New-DbaSqlParameter -ParameterName json_result -SqlDbType NVarChar -Size -1 -Direction Output PS C:\\> Invoke-DbaQuery -SqlInstance localhost -Database master -CommandType StoredProcedure -Query my_proc -SqlParameter $output PS C:\\> $output.Value Example 11: Creates an input parameter using Always Encrypted PS C:\\> $server = Connect-DbaInstance -SqlInstance localhost -Database master -AlwaysEncrypted PS C:\\> $inputparamSSN = New-DbaSqlParameter -Direction Input -ParameterName \"@SSN\" -DbType AnsiStringFixedLength -Size 11 -SqlValue \"444-44-4444\" -ForceColumnEncryption PS C:\\> Invoke-DbaQuery -SqlInstance $server -Query 'SELECT FROM bar WHERE SSN_col = @SSN' -SqlParameter @inputparamSSN Example 12: Reuses Connect-DbaInstance, leveraging advanced paramenters, to adhere to official guidelines to target FCI... PS C:\\> $server = Connect-DbaInstance -SqlInstance AG1 -Database dbatools -MultiSubnetFailover -ConnectTimeout 60 PS C:\\> Invoke-DbaQuery -SqlInstance $server -Query 'SELECT foo FROM bar' Reuses Connect-DbaInstance, leveraging advanced paramenters, to adhere to official guidelines to target FCI or AG listeners. See https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/sqlclient-support-for-high-availability-disaster-recovery#connecting-with-multisubnetfailover Example 13: Leverages your own parameters, giving you full power, mimicking Connect-DbaInstance&#39;s `-MultiSubnetFailover... PS C:\\> Invoke-DbaQuery -SqlInstance AG1 -Query 'SELECT foo FROM bar' -AppendConnectionString 'MultiSubnetFailover=true;Connect Timeout=60' Leverages your own parameters, giving you full power, mimicking Connect-DbaInstance's `-MultiSubnetFailover -ConnectTimeout 60`, to adhere to official guidelines to target FCI or AG listeners. See https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/sqlclient-support-for-high-availability-disaster-recovery#connecting-with-multisubnetfailover Example 14: Executes an INSERT statement with QUOTED_IDENTIFIER set to ON PS C:\\> Invoke-DbaQuery -SqlInstance server1 -Database tempdb -Query \"INSERT INTO dbo.TableWithFilteredIndex (Id, Name) VALUES (1, 'Test')\" -QuotedIdentifier Executes 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. Required Parameters -Query Contains the T-SQL commands to execute against the target instances. Supports T-SQL statements, XQuery, and SQLCMD commands with GO batch separators. Use this for ad-hoc queries, maintenance scripts, or data extraction commands. For complex scripts or version-controlled SQL, consider using the File parameter instead. Escape any double quotation marks included in the string. Consider using bracketed identifiers such as [MyTable] instead of quoted identifiers such as \"MyTable\". | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. Use this for deploying version-controlled SQL scripts, running standardized maintenance routines, or executing scripts downloaded from repositories. | Property | Value | | --- | --- | | Alias | InputFile | | Required | True | | Pipeline | false | | Default Value | | -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. Use this to deploy database schema changes by passing SMO objects from a source environment to recreate them elsewhere. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -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 are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -QueryTimeout Sets the command timeout in seconds before the query is cancelled. Defaults to the connection's default timeout if not specified. Increase this value for long-running maintenance operations, large data exports, or complex analytical queries that need more processing time. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -As Controls the format of returned query results. Choose 'DataRow' (default) for typical result sets, 'PSObject' for PowerShell-friendly objects, or 'SingleValue' for scalar results. Use 'PSObject' when you need to pipe results to other PowerShell commands that expect objects. Use 'SingleValue' for queries returning a single value like COUNT() or configuration checks. PSObject and PSObjectArray output introduces overhead but adds flexibility for working with results: https://forums.powershell.org/t/dealing-with-dbnull/2328/2 | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | DataRow | | Accepted Values | 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. Use this whenever your queries include user input, dynamic values, or when calling stored procedures with input/output parameters. Essential for secure production scripts. http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/ | Property | Value | | --- | --- | | Alias | SqlParameters | | Required | False | | Pipeline | false | | Default Value | | -CommandType Defines how the Query parameter should be interpreted. Use 'Text' (default) for T-SQL statements, 'StoredProcedure' for procedure calls, or 'TableDirect' for direct table access. Set this to 'StoredProcedure' when calling stored procedures, which enables proper parameter handling and allows the use of output parameters. Further information: https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.commandtype | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when you need to identify which instance produced each row of results, essential for multi-instance reporting and troubleshooting scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MessagesToOutput Captures and returns T-SQL PRINT statements, RAISERROR messages, and other informational messages along with query results. Use this when debugging stored procedures, monitoring script progress, or when you need to see messages that SQL scripts output during execution. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database objects from the pipeline, typically from Get-DbaDatabase. The query will execute against each database in the collection. Use this to run the same query across multiple databases efficiently, such as checking configuration settings or gathering statistics from all user databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -ReadOnly Sets the connection to use ReadOnly application intent, directing queries to readable secondary replicas in Availability Groups. Use this when querying Availability Group listeners to reduce load on primary replicas and take advantage of readable secondaries for reporting workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoExec Enables syntax and semantic validation without executing the actual statements. The SQL engine parses and compiles queries but doesn't run them. Use this to validate T-SQL syntax, check object references, and verify permissions before running potentially destructive scripts in production environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 indexes. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AppendConnectionString Adds custom connection string parameters for specialized connection requirements like MultiSubnetFailover, encryption settings, or timeout values. Use 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 SqlInstance and SqlCredential. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Data.DataSet (when -As DataSet is specified) Returns a DataSet object containing all result tables from the query. This format preserves table relationships and metadata. System.Data.DataTable[] (when -As DataTable is specified) Returns 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. System.Data.DataRow[] (when -As DataRow is specified - default) Returns 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 RAISERROR messages are also included in the output stream alongside the data rows. PSObject (when -As PSObject is specified) Returns 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 need to pipe results to other PowerShell commands that expect objects. PSObject[] (when -As PSObjectArray is specified) Returns 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. System.Object (when -As SingleValue is specified) Returns 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. When -AppendServerInstance is specified, an additional ServerInstance column is added to DataRow and PSObject output, containing the source SQL Server instance name. &nbsp;"
  },
  {
    "name": "Invoke-DbatoolsFormatter",
    "description": "Applies consistent code formatting to PowerShell files using PSScriptAnalyzer's 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.",
    "category": "Utilities",
    "tags": [
      "module",
      "support"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbatoolsFormatter",
    "popularityRank": 517,
    "synopsis": "Formats PowerShell function files to dbatools coding standards",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbatoolsFormatter View Source Simone Bizzotto Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Formats PowerShell function files to dbatools coding standards Description Applies consistent code formatting to PowerShell files using PSScriptAnalyzer's 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. Syntax Invoke-DbatoolsFormatter [-Path] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Reformats C:\\dbatools\\public\\Get-DbaDatabase.ps1 to dbatools&#39; standards PS C:\\> Invoke-DbatoolsFormatter -Path C:\\dbatools\\public\\Get-DbaDatabase.ps1 Required Parameters -Path Specifies the path to one or more PowerShell (.ps1) files that need to be formatted to dbatools coding standards. Accepts pipeline input from Get-ChildItem or other file listing commands for batch processing multiple files. Use this when you want to apply consistent OTBS formatting, proper indentation, and standardized brace placement to your dbatools contributions. | Property | Value | | --- | --- | | Alias | FullName) | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs None This 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 using the dbatools Write-Message function. &nbsp;"
  },
  {
    "name": "Invoke-DbatoolsRenameHelper",
    "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.",
    "category": "Utilities",
    "tags": [
      "module"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbatoolsRenameHelper",
    "popularityRank": 567,
    "synopsis": "Updates PowerShell scripts to replace deprecated dbatools command and parameter names with current equivalents.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbatoolsRenameHelper View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Updates PowerShell scripts to replace deprecated dbatools command and parameter names with current equivalents. 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. Syntax Invoke-DbatoolsRenameHelper [-InputObject] [[-Encoding] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Checks to see if any ps1 file in C:\\temp\\ps matches an old command name PS C:\\> Get-ChildItem C:\\temp\\ps\\.ps1 -Recurse | Invoke-DbatoolsRenameHelper Checks to see if any ps1 file in C:\\temp\\ps matches an old command name. If so, then the command name within the text is updated and the resulting changes are written to disk in UTF-8. Example 2: Shows what would happen if the command would run PS C:\\> Get-ChildItem C:\\temp\\ps\\.ps1 -Recurse | Invoke-DbatoolsRenameHelper -Encoding Ascii -WhatIf Shows what would happen if the command would run. If the command would run and there were matches, the resulting changes would be written to disk as Ascii encoded. Required Parameters -InputObject Specifies the PowerShell script files to scan and update for deprecated dbatools command and parameter names. Accept file objects from Get-ChildItem when you need to process multiple scripts containing outdated dbatools commands. Use this when modernizing existing automation scripts or migrating legacy PowerShell code to current dbatools naming conventions. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Encoding Sets the character encoding used when writing the updated script files back to disk. Defaults to UTF8. Use this when your PowerShell scripts require specific encoding formats for compatibility with source control systems or deployment processes. Most modern environments work well with the default UTF8 encoding, but legacy systems may require ASCII or other specific encodings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UTF8 | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per matched pattern found and replaced in each file. If no deprecated command or parameter names are found, nothing is returned. Properties: Path: The full file path that was updated Pattern: The deprecated command or parameter name that was found (e.g., 'Get-SqlMaxMemory', 'ExcludeSystem') ReplacedWith: The current equivalent name that replaced the deprecated name (e.g., 'Get-DbaMaxMemory', 'ExcludeSystem') Objects 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 each file. &nbsp;"
  },
  {
    "name": "Invoke-DbaWhoIsActive",
    "description": "Executes Adam Machanic's 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's 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",
    "category": "Utilities",
    "tags": [
      "community",
      "whoisactive"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaWhoIsActive",
    "popularityRank": 403,
    "synopsis": "Retrieves real-time information about active SQL Server sessions and currently running queries",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaWhoIsActive View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves real-time information about active SQL Server sessions and currently running queries Description Executes Adam Machanic's 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. This command was built with Adam's permission. To read more about sp_WhoIsActive, please visit: Updates: http://sqlblog.com/blogs/adam_machanic/archive/tags/who+is+active/default.aspx Also, consider donating to Adam if you find this stored procedure helpful: http://tinyurl.com/WhoIsActiveDonate Syntax Invoke-DbaWhoIsActive [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Filter] ] [[-FilterType] ] [[-NotFilter] ] [[-NotFilterType] ] [-ShowOwnSpid] [-ShowSystemSpids] [[-ShowSleepingSpids] ] [-GetFullInnerText] [[-GetPlans] ] [-GetOuterCommand] [-GetTransactionInfo] [[-GetTaskInfo] ] [-GetLocks] [-GetAverageTime] [-GetAdditonalInfo] [-FindBlockLeaders] [[-DeltaInterval] ] [[-OutputColumnList] ] [[-SortOrder] ] [[-FormatOutput] ] [[-DestinationTable] ] [-ReturnSchema] [[-Schema] ] [-Help] [[-As] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Execute sp_whoisactive on sqlserver2014a PS C:\\> Invoke-DbaWhoIsActive -SqlInstance sqlserver2014a Execute sp_whoisactive on sqlserver2014a. This command expects sp_WhoIsActive to be in the master database. Logs into the SQL Server with Windows credentials. Example 2: Execute sp_whoisactive on sqlserver2014a PS C:\\> Invoke-DbaWhoIsActive -SqlInstance sqlserver2014a -SqlCredential $credential -Database dbatools Execute sp_whoisactive on sqlserver2014a. This command expects sp_WhoIsActive to be in the dbatools database. Logs into the SQL Server with SQL Authentication. Example 3: Similar to running sp_WhoIsActive @get_avg_time PS C:\\> Invoke-DbaWhoIsActive -SqlInstance sqlserver2014a -GetAverageTime Example 4: Similar to running sp_WhoIsActive @get_outer_command = 1, @find_block_leaders = 1 PS C:\\> Invoke-DbaWhoIsActive -SqlInstance sqlserver2014a -GetOuterCommand -FindBlockLeaders Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database where sp_WhoIsActive is installed. Defaults to master if not specified. Use this when you've installed sp_WhoIsActive in a different database like a DBA utilities database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Filter Filters results to include only sessions matching the specified criteria. Supports wildcards (% and _) for pattern matching. Use this to focus on specific sessions, applications, databases, logins, or hosts when troubleshooting performance issues. For session ID filtering, use 0 or an empty string to include all sessions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FilterType Specifies what type of filtering to apply with the Filter parameter. Valid options: Session, Program, Database, Login, Host. Use 'Program' to filter by application name, 'Login' to filter by SQL login, or 'Host' to filter by client machine name. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Session | | Accepted Values | Session,Program,Database,Login,Host | -NotFilter Excludes sessions matching the specified criteria from results. Supports wildcards (% and _) for pattern matching. Use this to exclude specific applications, databases, or users when you want to focus on everything else. For session ID filtering, use 0 or an empty string to exclude no sessions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NotFilterType Specifies what type of exclusion filtering to apply with the NotFilter parameter. Valid options: Session, Program, Database, Login, Host. Use this in combination with NotFilter to exclude sessions by application name, database, login, or host. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Session | | Accepted Values | Session,Program,Database,Login,Host | -ShowOwnSpid Includes the current session (the one running sp_WhoIsActive) in the results. By default, your own session is excluded to reduce clutter in the output. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ShowSystemSpids Includes internal SQL Server system sessions in the results. Use this when troubleshooting system-level performance issues or investigating background processes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use 1 when investigating blocking issues or long-running transactions, or 2 for comprehensive session auditing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -GetFullInnerText Retrieves the complete SQL batch or stored procedure text instead of just the current statement. Use this when you need to see the full context of what's executing, not just the individual statement within a larger batch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -GetPlans Retrieves execution plans for active queries. 1 = plan for current statement only, 2 = entire plan for the batch or procedure. Essential for performance troubleshooting to identify inefficient queries, missing indexes, and optimization opportunities. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -GetOuterCommand Captures the original command that initiated the current batch, including stored procedure calls with parameters. Useful for understanding the full call stack when procedures call other procedures or dynamic SQL. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -GetTransactionInfo Includes transaction log usage and duration information for active sessions. Critical for identifying sessions with long-running transactions that may cause blocking or log space issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use level 1 for general troubleshooting or level 2 for detailed performance analysis when you need full wait statistics. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -GetLocks Retrieves detailed lock information for each session in XML format. Essential for troubleshooting blocking issues and understanding what resources sessions are waiting for or holding. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -GetAverageTime Calculates the average execution time for the currently running query based on historical execution data. Helps identify queries that are running longer than usual, indicating potential performance degradation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -GetAdditonalInfo Includes session configuration details like ANSI settings, isolation level, language, and command type information. Useful for troubleshooting application-specific issues where session settings affect query behavior or when investigating SQL Agent job activity. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FindBlockLeaders Identifies the root cause sessions in blocking chains and counts how many sessions each one is blocking. Critical for resolving blocking issues by showing you which sessions to focus on first when multiple blocking chains exist. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DeltaInterval Captures performance metrics at two points in time separated by the specified interval (in seconds) to show rate-of-change data. Excellent for identifying which sessions are actively consuming CPU, I/O, or memory resources during the measurement period. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -OutputColumnList Specifies which columns to include in the results and their display order using bracket-delimited column names. Customize this to focus on specific metrics or reduce output complexity for your monitoring scenarios. Only columns related to enabled features will actually appear in the output. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | [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. Sort by CPU, physical_io, or start_time to quickly identify the most resource-intensive or longest-running sessions. Defaults to sorting by start_time in ascending order. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | [start_time] ASC | -FormatOutput Controls output formatting for better readability. 0 = no formatting, 1 = variable-width fonts (default), 2 = fixed-width fonts. Use 2 when displaying results in console windows or fixed-width displays for better column alignment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1 | -DestinationTable Inserts results directly into a specified table instead of returning them to PowerShell. Useful for automated monitoring scripts or building historical performance data repositories. Table must already exist with the correct schema structure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ReturnSchema Returns a CREATE TABLE statement showing the schema structure needed for the DestinationTable instead of collecting data. Use this to generate the correct table structure before setting up automated data collection with DestinationTable. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Schema Alternative parameter name for ReturnSchema functionality. Returns a CREATE TABLE statement for the result set structure instead of collecting actual data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Help Returns detailed help information about sp_WhoIsActive parameters and their usage instead of executing the procedure. Use this to understand all available options when you're unsure which parameters to use for your specific troubleshooting scenario. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -As Specifies the PowerShell output format. Options: DataSet, DataTable, DataRow (default), PSObject. Use PSObject for advanced scripting scenarios where you need better handling of null values and type conversion. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | DataRow | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Output type depends on the -As parameter: DataRow (default) System.Data.DataRow for each row of sp_WhoIsActive results DataTable System.Data.DataTable containing all sp_WhoIsActive result rows with columns for session activity DataSet System.Data.DataSet containing one DataTable from sp_WhoIsActive results PSObject PSCustomObject with properties for each column returned by sp_WhoIsActive The actual properties and columns returned depend on which feature parameters are enabled: Base columns include: session_id, sql_text, login_name, start_time, status, host_name, etc. GetPlans adds: query_plan (XML execution plan) GetLocks adds: locks (XML lock information) GetTransactionInfo adds: tran_log_used_percent, tran_start_time, tran_duration_sec GetTaskInfo adds: wait_info, tasks, CPU usage information GetAverageTime adds: avg_elapsed_time_ms DeltaInterval adds: CPU delta, IO delta, and other rate-of-change metrics OutputColumnList parameter controls which columns are included in results When -ReturnSchema or -Schema is specified, a CREATE TABLE statement is returned instead of data. When -DestinationTable is specified, data is inserted to the specified table and no results are returned to PowerShell. &nbsp;"
  },
  {
    "name": "Invoke-DbaXEReplay",
    "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.",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Invoke",
    "popular": false,
    "url": "/Invoke-DbaXEReplay",
    "popularityRank": 691,
    "synopsis": "Replays SQL queries captured in Extended Event files against target SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Invoke-DbaXEReplay View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Replays SQL queries captured in Extended Event files against target SQL Server instances 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. The 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. By 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. Syntax Invoke-DbaXEReplay [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Event] ] [-InputObject] [-Raw] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Runs all batch_text for sql_batch_completed against tempdb on sql2017 PS C:\\> Read-DbaXEFile -Path C:\\temp\\sample.xel | Invoke-DbaXEReplay -SqlInstance sql2017 Example 2: Sets the initial database to planning then runs only sql_batch_completed against sql2017 PS C:\\> Read-DbaXEFile -Path C:\\temp\\sample.xel | Invoke-DbaXEReplay -SqlInstance sql2017 -Database planning -Event sql_batch_completed Example 3: Runs all batch_text for sql_batch_completed against tempdb on sql2017 and sql2016 PS C:\\> Read-DbaXEFile -Path C:\\temp\\sample.xel | Invoke-DbaXEReplay -SqlInstance sql2017, sql2016 Required Parameters -SqlInstance Target SQL Server(s) | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts Extended Event objects from Read-DbaXEFile or Read-DbaXESession containing captured SQL statements for replay. This is typically piped from Read-DbaXEFile when processing Extended Event files or from Read-DbaXESession for live session data. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Sets the initial database context for the replayed SQL statements. This determines which database sqlcmd connects to before executing the captured queries. Use this when you need to replay workloads in a specific database context, especially when the captured queries don't include explicit database references. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Event Filters which Extended Event types to replay from the input stream. Defaults to sql_batch_completed and rcp_completed events. Use this to replay only specific event types when you want to test particular workload patterns or exclude certain query types from the replay. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @('sql_batch_completed', 'rcp_completed') | -Raw Shows all sqlcmd output immediately without cleanup or formatting. By default, results are collected, cleaned, and filtered for readability. Use this when you need to see complete sqlcmd output including headers and formatting, or when troubleshooting query execution issues during replay. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String Returns the output from sqlcmd execution. The exact content depends on the SQL queries being replayed. When -Raw is specified, all sqlcmd output is returned unmodified, including headers and formatting lines. When -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. If 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. &nbsp;"
  },
  {
    "name": "Join-DbaAvailabilityGroup",
    "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's configuration.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Join",
    "popular": false,
    "url": "/Join-DbaAvailabilityGroup",
    "popularityRank": 177,
    "synopsis": "Adds a SQL Server instance as a secondary replica to an existing availability group.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Join-DbaAvailabilityGroup View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Adds a SQL Server instance as a secondary replica to an existing availability group. 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's configuration. Syntax Join-DbaAvailabilityGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-ClusterType] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Joins sql02 to the SharePoint availability group on sql01 PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02 Example 2: Joins sql02 to the SharePoint availability group on sql01 PS C:\\> $ag = Get-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint PS C:\\> Join-DbaAvailabilityGroup -SqlInstance sql02 -InputObject $ag Example 3: Shows what would happen if the command were to run PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02 -WhatIf Shows what would happen if the command were to run. No actions are actually performed. Example 4: Prompts for confirmation then joins sql02 to the SharePoint availability group on sql01 PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Join-DbaAvailabilityGroup -SqlInstance sql02 -Confirm Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies the name of the availability group that the target instance will join as a secondary replica. Use this when you need to add a secondary replica to an existing availability group that was created on the primary server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ClusterType Specifies the cluster type for the availability group when joining SQL Server 2017 or later instances. Use 'Wsfc' for Windows Server Failover Clustering, 'External' for Linux cluster managers like Pacemaker, or 'None' for read-scale availability groups without clustering. If not specified, the cluster type is automatically detected from the existing availability group. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | External,Wsfc,None | -InputObject Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations. Use this when you want to retrieve availability group details from the primary replica and pipe them directly to join secondary replicas. The availability group name and cluster type are automatically extracted from the input object. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This command does not return any objects. It modifies the SQL Server instance configuration by joining an existing availability group on the secondary replica. The 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. &nbsp;"
  },
  {
    "name": "Join-DbaPath",
    "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's 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's path separator conventions.",
    "category": "Utilities",
    "tags": [
      "path",
      "utility"
    ],
    "verb": "Join",
    "popular": false,
    "url": "/Join-DbaPath",
    "popularityRank": 524,
    "synopsis": "Constructs file paths with correct separators for Windows and Linux SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Join-DbaPath View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Constructs file paths with correct separators for Windows and Linux SQL Server instances. 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's 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's path separator conventions. Syntax Join-DbaPath [-Path] [-SqlInstance ] [-Child ] [ ] &nbsp; Examples &nbsp; Example 1: Returns &#39;C:\\temp\\Foo\\Bar&#39; on windows PS C:\\> Join-DbaPath -Path 'C:\\temp' 'Foo' 'Bar' Returns 'C:\\temp\\Foo\\Bar' on windows. Returns 'C:/temp/Foo/Bar' on non-windows. Required Parameters -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlInstance Optional -- tests to see if destination SQL Server is Linux or Windows | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this to organize files into logical groupings like database names, backup types, or date-based folders (e.g., 'MyDatabase', 'Full', '2024-01-15'). | Property | Value | | --- | --- | | Alias | ChildPath | | Required | False | | Pipeline | false | | Default Value | | Outputs System.String Returns a single string containing the constructed file path with the appropriate path separators for the target system. When no -SqlInstance is specified, the path uses the local computer's separator convention. When -SqlInstance targets a Linux SQL Server, forward slashes (/) are used as separators. When -SqlInstance targets a Windows SQL Server, backslashes (\\) are used as separators. &nbsp;"
  },
  {
    "name": "Measure-DbaBackupThroughput",
    "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",
    "category": "Backup & Restore",
    "tags": [
      "backup",
      "database"
    ],
    "verb": "Measure",
    "popular": false,
    "url": "/Measure-DbaBackupThroughput",
    "popularityRank": 347,
    "synopsis": "Calculates backup throughput statistics from msdb backup history to analyze backup performance.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Measure-DbaBackupThroughput View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Calculates backup throughput statistics from msdb backup history to analyze backup performance. 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. The 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. Output 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. Output looks like this: SqlInstance : sql2016 Database : SharePoint_Config AvgThroughput : 1.07 MB AvgSize : 24.17 AvgDuration : 00:00:01.1000000 MinThroughput : 0.02 MB MaxThroughput : 2.26 MB MinBackupDate : 8/6/2015 10:22:01 PM MaxBackupDate : 6/19/2016 12:57:45 PM BackupCount : 10 Syntax Measure-DbaBackupThroughput [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Since] ] [-Last] [[-Type] ] [[-DeviceType] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Parses every backup in msdb&#39;s backuphistory for stats on all databases PS C:\\> Measure-DbaBackupThroughput -SqlInstance sql2016 Example 2: Parses every backup in msdb&#39;s backuphistory for stats on AdventureWorks2014 PS C:\\> Measure-DbaBackupThroughput -SqlInstance sql2016 -Database AdventureWorks2014 Example 3: Processes the last full, diff and log backups every backup for all databases on sql2005 PS C:\\> Measure-DbaBackupThroughput -SqlInstance sql2005 -Last Example 4: Processes the last log backups every backup for all databases on sql2005 PS C:\\> Measure-DbaBackupThroughput -SqlInstance sql2005 -Last -Type Log Example 5: Gets backup calculations for the last week and filters results that have a minimum of 1GB throughput PS C:\\> Measure-DbaBackupThroughput -SqlInstance sql2016 -Since (Get-Date).AddDays(-7) | Where-Object { $_.MinThroughput.Gigabyte -gt 1 } Example 6: Gets backup calculations, limited to the last year and only the bigoldb database PS C:\\> Measure-DbaBackupThroughput -SqlInstance sql2016 -Since (Get-Date).AddDays(-365) -Database bigoldb Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for backup throughput statistics. Accepts wildcards for pattern matching. Use this when you need to focus performance analysis on specific databases rather than analyzing all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to exclude from throughput analysis. Accepts wildcards for pattern matching. Use this to remove system databases or problematic databases from your performance analysis without affecting other databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Since Filters backup history to analyze only backups taken on or after the specified date and time. Use this to focus your throughput analysis on recent backups or compare performance before and after infrastructure changes. Accepts standard PowerShell datetime formats. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Last Analyzes only the most recent backup for each database instead of processing the entire backup history. Use this for quick performance checks or when you only need current backup throughput statistics rather than historical trends. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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\". Use this to analyze specific backup types when troubleshooting performance issues or comparing different backup strategies. Defaults to \"Full\" backups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Full | | Accepted Values | 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. Use this to compare throughput performance between different backup destinations or troubleshoot specific backup infrastructure components. Accepts custom integer values for specialized backup devices. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database analyzed, containing aggregated backup throughput statistics across the backup history. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database being analyzed AvgThroughput: Average backup throughput in megabytes per second; DbaSize object with unit conversion properties (.Megabyte, .Gigabyte, etc.) AvgSize: Average backup size; DbaSize object with unit conversion properties AvgDuration: Average time required for backups; DbaTimeSpan object representing time span MinThroughput: Minimum backup throughput observed; DbaSize object MaxThroughput: Maximum backup throughput observed; DbaSize object MinBackupDate: DateTime of the earliest backup in the analyzed time period; DbaDateTime object MaxBackupDate: DateTime of the most recent backup in the analyzed time period; DbaDateTime object BackupCount: Total number of backups analyzed for this database (int) All size and throughput values use dbasize objects that automatically format to appropriate units (Bytes, KB, MB, GB, TB) when displayed. The DbaTimeSpan and DbaDateTime objects provide specialized handling for time values with automatic formatting. &nbsp;"
  },
  {
    "name": "Measure-DbaDbVirtualLogFile",
    "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've got a high number of VLFs, you can use Expand-SqlTLogResponsibly to reduce the number.",
    "category": "Utilities",
    "tags": [
      "diagnostic",
      "vlf",
      "logfile"
    ],
    "verb": "Measure",
    "popular": false,
    "url": "/Measure-DbaDbVirtualLogFile",
    "popularityRank": 365,
    "synopsis": "Measures Virtual Log File (VLF) counts in transaction logs to identify performance bottlenecks",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Measure-DbaDbVirtualLogFile View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Measures Virtual Log File (VLF) counts in transaction logs to identify performance bottlenecks 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. High 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. The 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. References: http://www.sqlskills.com/blogs/kimberly/transaction-log-vlfs-too-many-or-too-few/ http://blogs.msdn.com/b/saponsqlserver/archive/2012/02/22/too-many-virtual-log-files-vlfs-can-cause-slow-database-recovery.aspx If you've got a high number of VLFs, you can use Expand-SqlTLogResponsibly to reduce the number. Syntax Measure-DbaDbVirtualLogFile [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-IncludeSystemDBs] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all user database virtual log file counts for the sqlcluster instance PS C:\\> Measure-DbaDbVirtualLogFile -SqlInstance sqlcluster Example 2: Returns user databases that have 50 or more VLFs PS C:\\> Measure-DbaDbVirtualLogFile -SqlInstance sqlserver | Where-Object {$_.Total -ge 50} Example 3: Returns all VLF information for the sqlserver and sqlcluster SQL Server instances PS C:\\> @('sqlserver','sqlcluster') | Measure-DbaDbVirtualLogFile Returns all VLF information for the sqlserver and sqlcluster SQL Server instances. Processes data via the pipeline. Example 4: Returns VLF counts for the db1 and db2 databases on sqlcluster PS C:\\> Measure-DbaDbVirtualLogFile -SqlInstance sqlcluster -Database db1, db2 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for VLF counts. Accepts database names, wildcards, or arrays of database names. Use this to focus VLF analysis on specific databases when troubleshooting performance issues or during targeted maintenance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during VLF analysis. Accepts database names, wildcards, or arrays of database names. Use this to exclude problematic databases or those you know are healthy when running instance-wide VLF checks. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSystemDBs Includes system databases (master, model, msdb, tempdb) in the VLF analysis. By default only user databases are analyzed since system database VLF counts are typically less critical for performance tuning. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database containing virtual log file (VLF) statistics and transaction log growth configuration. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database Total: Total count of VLFs in the transaction log Additional properties available: TotalCount: Duplicate of Total (total count of VLFs) Inactive: Count of inactive VLFs (status = 0) Active: Count of active VLFs (status = 2) LogFileName: Comma-separated list of logical names of the transaction log files LogFileGrowth: Comma-separated list of growth increment values for each log file LogFileGrowthType: Comma-separated list of growth types (Percent or kb) for each log file Use Select-Object * to access all properties. &nbsp;"
  },
  {
    "name": "Measure-DbaDiskSpaceRequirement",
    "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.",
    "category": "Database Operations",
    "tags": [
      "diagnostic",
      "storage",
      "space",
      "database"
    ],
    "verb": "Measure",
    "popular": false,
    "url": "/Measure-DbaDiskSpaceRequirement",
    "popularityRank": 282,
    "synopsis": "Calculates disk space requirements for database migration between SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Measure-DbaDiskSpaceRequirement View Source Pollus Brodeur (@pollusb) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Calculates disk space requirements for database migration between SQL Server instances 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. The 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. Accepts pipeline input with Source, Database, and Destination properties, making it ideal for bulk migration planning from CSV files, SQL queries, or PowerShell objects. Syntax Measure-DbaDiskSpaceRequirement [-Source] [-Database] [[-SourceSqlCredential] ] [-Destination] [[-DestinationDatabase] ] [[-DestinationSqlCredential] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Calculate space needed for a simple migration with one database with the same name at destination PS C:\\> Measure-DbaDiskSpaceRequirement -Source INSTANCE1 -Database DB1 -Destination INSTANCE2 Example 2: Using a PSCustomObject with 2 databases to migrate on SQL2 PS C:\\> @( >> [PSCustomObject]@{Source='SQL1';Destination='SQL2';Database='DB1'}, >> [PSCustomObject]@{Source='SQL1';Destination='SQL2';Database='DB2'} >> ) | Measure-DbaDiskSpaceRequirement Example 3: Using a CSV file PS C:\\> Import-Csv -Path .\\migration.csv -Delimiter \"`t\" | Measure-DbaDiskSpaceRequirement | Format-Table -AutoSize Using a CSV file. You will need to use this header line \"Source Destination Database DestinationDatabase\". Example 4: Using a SQL table PS C:\\> $qry = \"SELECT Source, Destination, Database FROM dbo.Migrations\" PS C:\\> Invoke-DbaCmd -SqlInstance DBA -Database Migrations -Query $qry | Measure-DbaDiskSpaceRequirement Using a SQL table. We are DBA after all! Required Parameters -Source Specifies the source SQL Server instance containing the database to analyze for migration. This is where the database currently exists and from which file sizes will be measured. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | -Database Specifies the name of the database to analyze on the source instance. The database must exist on the source server as the function reads actual file sizes from this database. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | -Destination Specifies the destination SQL Server instance where the database will be migrated. Used to determine target file paths, check for existing databases with the same name, and calculate mount point requirements. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -SourceSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -DestinationDatabase Specifies the database name to use on the destination instance if different from the source database name. When omitted, the destination database will use the same name as the source database. Useful when migrating databases that need to be renamed or when avoiding naming conflicts on the destination server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -DestinationSqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Credential The credentials to use to connect via CIM/WMI/PowerShell remoting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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: files on both source and destination, files only on source, or files only on destination. Default display properties (via Select-DefaultView): SourceSqlInstance: The full SQL Server instance name of the source (computer\\instance) SourceDatabase: Name of the source database SourceLogicalName: Logical name of the database file on the source SourceFileName: Operating system file path of the source file SourceFileSize: DbaSize object of the source file size (bytes, converts to KB/MB/GB/TB) DestinationComputerName: The computer name of the destination SQL Server instance DestinationSqlInstance: The full SQL Server instance name of the destination (computer\\instance) DestinationDatabase: Name of the destination database (may differ from source if renamed) DestinationFileName: Operating system file path of the destination file (null if file only on source) DestinationFileSize: DbaSize object of destination file size; null or 0 if file only on source (displayed as negative value when present) DifferenceSize: DbaSize object showing the difference in file size between source and destination MountPoint: The volume mount point where the destination file is or will be located FileLocation: Scenario description - \"Source and Destination\", \"Only on Source\", or \"Only on Destination\" *Hidden properties (available via Select-Object ):* SourceComputerName: The computer name of the source SQL Server instance SourceInstance: The SQL Server instance name of the source DestinationInstance: The SQL Server instance name of the destination DestinationLogicalName: Logical name of the destination file (null if file only on source) SourceDatabaseName: Source database name (used in \"Only on Destination\" scenario) DestinationDatabaseName: Destination database name (used in \"Only on Destination\" scenario) Use Select-Object to access all properties including hidden ones. &nbsp;"
  },
  {
    "name": "Measure-DbatoolsImport",
    "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.",
    "category": "Utilities",
    "tags": [
      "module",
      "support"
    ],
    "verb": "Measure",
    "popular": false,
    "url": "/Measure-DbatoolsImport",
    "popularityRank": 583,
    "synopsis": "Measures and displays detailed timing metrics for dbatools module import operations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Measure-DbatoolsImport View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Outputs Synopsis Measures and displays detailed timing metrics for dbatools module import operations 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. Syntax Measure-DbatoolsImport [ ] &nbsp; Examples &nbsp; Example 1: Displays the import load times of the dbatools PowerShell module PS C:\\> Measure-DbatoolsImport Example 2: Displays the import load times of the dbatools PowerShell module PS C:\\> Import-Module dbatools PS C:\\> Measure-DbatoolsImport Outputs PSCustomObject Returns 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, external commands, and other initialization operations. Properties: Name: Name of the initialization step (e.g., \"Importing Type Aliases\", \"Loading Internal Commands\") Duration: TimeSpan representing how long the step took to complete; only steps with Duration greater than 00:00:00 are returned &nbsp;"
  },
  {
    "name": "Mount-DbaDatabase",
    "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't 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.",
    "category": "Database Operations",
    "tags": [
      "attach",
      "database"
    ],
    "verb": "Mount",
    "popular": false,
    "url": "/Mount-DbaDatabase",
    "popularityRank": 175,
    "synopsis": "Attaches detached database files to a SQL Server instance",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Mount-DbaDatabase View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Attaches detached database files to a SQL Server instance 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. If you don't 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. Syntax Mount-DbaDatabase [-SqlInstance] [[-SqlCredential] ] [-Database] [[-FileStructure] ] [[-DatabaseOwner] ] [[-AttachOption] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Attaches a database named &quot;example&quot; to sql2016 with the files &quot;E:\\archive\\example.mdf&quot;... PS C:\\> $fileStructure = New-Object System.Collections.Specialized.StringCollection PS C:\\> $fileStructure.Add(\"E:\\archive\\example.mdf\") PS C:\\> $filestructure.Add(\"E:\\archive\\example.ldf\") PS C:\\> $filestructure.Add(\"E:\\archive\\example.ndf\") PS C:\\> Mount-DbaDatabase -SqlInstance sql2016 -Database example -FileStructure $fileStructure Attaches 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 option is None. Example 2: Since the FileStructure was not provided, this command will attempt to determine it based on backup history PS C:\\> Mount-DbaDatabase -SqlInstance sql2016 -Database example Since 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. Example 3: Shows what would happen if the command were executed (without actually performing the command) PS C:\\> Mount-DbaDatabase -SqlInstance sql2016 -Database example -WhatIf Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Database Specifies the names of the detached databases to attach to the SQL Server instance. Use this when you have database files (.mdf, .ldf, .ndf) on disk but the database is no longer registered in SQL Server. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileStructure Specifies the complete collection of database file paths (.mdf, .ldf, .ndf) required to attach the database. When omitted, the command attempts to determine file locations automatically using backup history from the most recent full backup. Use this parameter when files are in non-standard locations or when automatic detection fails. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DatabaseOwner Sets the login account that will own the attached database. When not specified, defaults to the sa account or the SQL Server sysadmin with ID 1 if sa is not available. Use this to assign ownership to a specific login for security or administrative requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AttachOption Controls how SQL Server handles the database attachment process and Service Broker configuration. Use 'RebuildLog' when transaction log files are missing or corrupt, 'EnableBroker' to activate Service Broker, or 'NewBroker' to create a new Service Broker identifier. Defaults to 'None' for standard attachment without special handling. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | None | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database successfully attached to the SQL Server instance. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database that was attached AttachResult: Status of the attach operation (always \"Success\" when returned) AttachOption: The attach option that was used (None, RebuildLog, EnableBroker, NewBroker, or ErrorBrokerConversations) FileStructure: System.Collections.Specialized.StringCollection containing the file paths that were attached &nbsp;"
  },
  {
    "name": "Move-DbaDbFile",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "move",
      "file"
    ],
    "verb": "Move",
    "popular": false,
    "url": "/Move-DbaDbFile",
    "popularityRank": 87,
    "synopsis": "Relocates database files to different drives or folders while maintaining database integrity.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Move-DbaDbFile View Source Claudio Silva (@claudioessilva), claudioeesilva.eu Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Relocates database files to different drives or folders while maintaining database integrity. 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. This 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. Syntax Move-DbaDbFile -SqlInstance [-SqlCredential ] -Database [-FileType ] [-FileDestination ] [-DeleteAfterMove] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Move-DbaDbFile -SqlInstance [-SqlCredential ] -Database [-FileToMove ] [-DeleteAfterMove] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Move-DbaDbFile -SqlInstance [-SqlCredential ] -Database [-FileStructureOnly] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Copy all data files of dbatools database on sql2017 instance to the &quot;D:\\DATA2&quot; path PS C:\\> Move-DbaDbFile -SqlInstance sql2017 -Database dbatools -FileType Data -FileDestination D:\\DATA2 Copy all data files of dbatools database on sql2017 instance to the \"D:\\DATA2\" path. Before it puts database offline and after copy each file will update database metadata and it ends by set the database back online Example 2: Declares a hashtable that says for each logical file the new path PS C:\\> $fileToMove=@{ >> 'dbatools'='D:\\DATA3' >> 'dbatools_log'='D:\\LOG2' >> } PS C:\\> Move-DbaDbFile -SqlInstance sql2019 -Database dbatools -FileToMove $fileToMove Declares a hashtable that says for each logical file the new path. Copy 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). Before it puts database offline and after copy each file will update database metadata and it ends by set the database back online Example 3: Shows the current database file structure (without filenames) PS C:\\> Move-DbaDbFile -SqlInstance sql2017 -Database dbatools -FileStructureOnly Shows the current database file structure (without filenames). Example: 'dbatools'='D:\\Data' Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Database Specifies the user database whose files will be relocated to new paths. System databases (master, model, msdb, tempdb) are not supported for safety reasons. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileType Specifies which file types to relocate: Data, Log, or Both (default). Use this with FileDestination when you want to move all files of a specific type to the same directory. Cannot be combined with FileToMove parameter as they serve different movement strategies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Data,Log,Both | -FileDestination Sets the target directory where all selected database files will be moved. Used with FileType parameter to move all data files, log files, or both to a single location. Must be accessible to the SQL Server service account and have sufficient space for the files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileToMove Defines specific file movements using a hashtable where keys are logical file names and values are destination directory paths. Use this when you need granular control over where each file goes, like separating data and log files to different drives. Example: @{'MyDB_Data'='E:\\Data'; 'MyDB_Log'='F:\\Logs'} | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DeleteAfterMove Removes the original database files from their source location after successful relocation. Use this to free up disk space on the source drive once files are confirmed copied and database metadata updated. Files are only deleted after successful copy and database metadata update to prevent data loss. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FileStructureOnly Returns the current file structure as a hashtable template without performing any file operations. Use this to discover logical file names and current paths, then modify the output for use with FileToMove. Helpful for planning complex moves or scripting multiple database relocations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Forces the database offline using WITH ROLLBACK IMMEDIATE, terminating active transactions and connections. Use this when the database has active connections that would prevent it from going offline gracefully. Without this switch, the operation may fail if users are connected to the database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.String (when -FileStructureOnly is specified) Returns 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. Example: $fileToMove=@{'MyDB_Data'='D:\\Data'; 'MyDB_Log'='D:\\Logs'} PSCustomObject (default) Returns one object per database file processed during the move operation. Each object represents the result of moving a single logical database file. Properties: Instance: The target SQL Server instance name Database: The name of the database containing the file LogicalName: The logical name of the database file within SQL Server Source: The original physical file path before the move Destination: The new physical file path after the move Result: Status of the operation (Success, Failed, or Already exists. Skipping) DatabaseFileMetadata: Status of SQL Server metadata update (Updated, N/A if file copy failed, or N/A if file already exists) SourceFileDeleted: Boolean indicating if source file was deleted (True, False) or N/A if not deleted or copy failed &nbsp;"
  },
  {
    "name": "Move-DbaRegServer",
    "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.",
    "category": "Utilities",
    "tags": [
      "registeredserver",
      "cms"
    ],
    "verb": "Move",
    "popular": false,
    "url": "/Move-DbaRegServer",
    "popularityRank": 532,
    "synopsis": "Moves registered servers between groups within SQL Server Central Management Server (CMS)",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Move-DbaRegServer View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Moves registered servers between groups within SQL Server Central Management Server (CMS) 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. Syntax Move-DbaRegServer [[-SqlInstance] ] [[-SqlCredential] ] [[-Name] ] [[-ServerName] ] [[-Group] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Moves the registered server on sql2012 titled &#39;Web SQL Cluster&#39; to the Prod group within the HR group PS C:\\> Move-DbaRegServer -SqlInstance sql2012 -Name 'Web SQL Cluster' -Group HR\\Prod Example 2: Moves the registered server &#39;Web SQL Cluster&#39; on sql2017 to the Web group, also on sql2017 PS C:\\> Get-DbaRegServer -SqlInstance sql2017 -Name 'Web SQL Cluster' | Move-DbaRegServer -Group Web Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 actual server instance name. Use this when you know the descriptive name assigned to servers in CMS but not necessarily their technical instance names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need to target servers by their network instance names rather than their CMS display names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Group Specifies the destination group where the registered servers will be moved. Use backslash notation for nested groups like 'Production\\WebServers'. If not specified, servers are moved to the root level of the CMS hierarchy. The target group must already exist in CMS. | Property | Value | | --- | --- | | Alias | NewGroup | | Required | False | | Pipeline | false | | Default Value | | -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. Use this approach when you need complex filtering or when working with servers from multiple CMS instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.RegisteredServers.RegisteredServer Returns 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. Default display properties include: ComputerName: The computer name of the Central Management Server instance InstanceName: The SQL Server instance name hosting the CMS SqlInstance: The full SQL Server instance name (computer\\instance) Name: The display name of the registered server in CMS ServerName: The actual SQL Server instance name (connection string) Group: The group path where the registered server is now located &nbsp;"
  },
  {
    "name": "Move-DbaRegServerGroup",
    "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.",
    "category": "Utilities",
    "tags": [
      "registeredserver",
      "cms"
    ],
    "verb": "Move",
    "popular": false,
    "url": "/Move-DbaRegServerGroup",
    "popularityRank": 666,
    "synopsis": "Moves registered server groups to different parent groups within SQL Server Central Management Server (CMS)",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Move-DbaRegServerGroup View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Moves registered server groups to different parent groups within SQL Server Central Management Server (CMS) 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. Syntax Move-DbaRegServerGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-Group] ] [-NewGroup] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Moves the Development group within HR to the Prod group within AD PS C:\\> Move-DbaRegServerGroup -SqlInstance sql2012 -Group HR\\Development -NewGroup AD\\Prod Example 2: Moves the Development group within HR to the Web group PS C:\\> Get-DbaRegServerGroup -SqlInstance sql2017 -Group HR\\Development| Move-DbaRegServerGroup -NewGroup Web Required Parameters -NewGroup Specifies the destination group where the selected groups will be moved. Accepts group paths like 'AD\\Prod' or 'Web', or use 'Default' to move to the root level. The destination group must already exist in the Central Management Server hierarchy. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Group Specifies the registered server group(s) to move within your Central Management Server hierarchy. Accepts group paths like 'HR\\Development' or 'Production\\WebServers'. Use this when you need to select specific groups to relocate rather than piping group objects from Get-DbaRegServerGroup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. This parameter enables advanced scenarios like moving multiple groups based on complex criteria or properties. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.RegisteredServers.ServerGroup Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the CMS host InstanceName: The SQL Server instance name of the CMS SqlInstance: The full SQL Server instance name in computer\\instance format Name: The name of the moved server group DisplayName: Display name of the server group for UI presentation Description: Text description of the group's purpose or contents ServerGroups: Collection of child server groups nested under this group RegisteredServers: Collection of registered servers that belong to this group All properties from the base SMO ServerGroup object are accessible using Select-Object *, including Urn, Parent, ParentServer, and other internal properties. &nbsp;"
  },
  {
    "name": "New-DbaAgentAlert",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "alert"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaAgentAlert",
    "popularityRank": 587,
    "synopsis": "Creates SQL Server Agent alerts for automated monitoring and notification of errors, performance conditions, or system events",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaAgentAlert View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates SQL Server Agent alerts for automated monitoring and notification of errors, performance conditions, or system events 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. Syntax New-DbaAgentAlert [-SqlInstance] [[-SqlCredential] ] [-Alert] [[-Category] ] [[-Database] ] [[-Operator] ] [[-DelayBetweenResponses] ] [-Disabled] [[-EventDescriptionKeyword] ] [[-EventSource] ] [[-JobId] ] [[-Severity] ] [[-MessageId] ] [[-NotificationMessage] ] [[-PerformanceCondition] ] [[-WmiEventNamespace] ] [[-WmiEventQuery] ] [[-NotifyMethod] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: SqlInstance = &quot;sql01&quot; Severity = 18 Alert = &quot;Severity 018 - Nonfatal Internal Error&quot; DelayBetweenResponses =... PS C:\\> $parms = @{ PS C:\\> $alert = New-DbaAgentAlert @parms SqlInstance = \"sql01\" Severity = 18 Alert = \"Severity 018 - Nonfatal Internal Error\" DelayBetweenResponses = 60 NotifyMethod = \"NotifyEmail\" } Creates a new alert for severity 18 with the name Severity 018 - Nonfatal Internal Error. It will send an email to the default operator and wait 60 seconds before sending another email. Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Alert Specifies the name for the new SQL Server Agent alert. Must be unique within the SQL Server instance. Use descriptive names that clearly identify the alert's purpose, such as 'High Severity Errors' or 'Database Full'. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Category Assigns the alert to a specific category for organization and management purposes. Categories help group related alerts together in SQL Server Management Studio and can be used for filtering in reports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Restricts the alert to monitor events occurring only in the specified database. Leave blank to monitor all databases on the instance, or specify a database name to limit scope and reduce false positives. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Operator Specifies which SQL Server Agent operators will receive notifications when this alert fires. The operators must already exist and be configured with valid email addresses, pager numbers, or net send addresses. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DelayBetweenResponses Sets the minimum time in seconds between alert notifications to prevent notification spam. Use higher values like 300-900 seconds for recurring issues to avoid overwhelming operators with repeated alerts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 60 | -Disabled Creates the alert in a disabled state, preventing it from triggering until manually enabled. Useful when setting up alerts during maintenance windows or when you need to configure notifications before activating monitoring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EventDescriptionKeyword Filters alert triggers to only events containing this keyword in the error message text. Use this to create targeted alerts for specific error conditions like 'deadlock', 'timeout', or 'corruption' within broader error categories. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EventSource Identifies the source application or component for WMI event monitoring. Required when creating WMI-based alerts to specify which system component's events should trigger the alert. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -JobId Specifies the GUID of a SQL Server Agent job to automatically execute when the alert fires. Use this for automated responses like running diagnostics, performing cleanup, or triggering failover procedures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 00000000-0000-0000-0000-000000000000 | -Severity Sets the SQL Server error severity level that triggers this alert, ranging from 0-25. Common values include 16-18 for user errors, 19-21 for resource issues, and 22-25 for system errors requiring immediate attention. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MessageId Creates an alert that triggers on a specific SQL Server error message number. Use this for precise monitoring of known error conditions like message 9002 (transaction log full) or 825 (read-retry errors). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -NotificationMessage Defines custom text to include in alert notifications sent to operators. Use this to provide context, troubleshooting steps, or escalation procedures specific to this alert condition. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PerformanceCondition Defines a performance counter condition that triggers the alert when threshold values are exceeded. Specify conditions like 'SQLServer:General Statistics|Logins/sec|>|100' to monitor performance metrics and respond to resource issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -WmiEventNamespace Specifies the WMI namespace to monitor for events, typically 'root\\cimv2' for system events. Required when creating WMI-based alerts to monitor Windows system events, hardware failures, or application-specific WMI providers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -WmiEventQuery Defines the WQL (WMI Query Language) query that determines which WMI events trigger the alert. Use queries like 'SELECT FROM Win32_VolumeChangeEvent' to monitor specific system events outside of SQL Server's direct control. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NotifyMethod The method to use to notify the user of the alert. Valid values are 'None', 'NotifyEmail', 'Pager', 'NetSend', 'NotifyAll'. It is NotifyAll by default. The Pager and net send options will be removed from SQL Server Agent in a future version of Microsoft SQL Server. Avoid using these features in new development work, and plan to modify applications that currently use these features. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | NotifyAll | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.Alert Returns one Alert object for each newly created SQL Server Agent alert. The object represents the alert as configured on the target instance. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Name of the newly created alert ID: Unique identifier of the alert in the msdb database JobName: Name of the job that responds to this alert (if any) AlertType: Type of alert (EventAlert, ErrorNumberAlert, PerformanceConditionAlert, or WmiEventAlert) CategoryName: Category name assigned to the alert Severity: SQL Server error severity level (0-25) that triggers this alert MessageId: SQL Server message ID that triggers this alert (if alert is message-based) IsEnabled: Boolean indicating if the alert is enabled or disabled DelayBetweenResponses: Delay in seconds between repeated alert responses Additional properties available (from SMO Alert object): CategoryId: Unique identifier of the alert category CreateDate: DateTime when the alert was created DateLastModified: DateTime when the alert was last modified DatabaseName: Name of the database this alert applies to (for database-specific alerts) EventDescriptionKeyword: Keyword filter for event descriptions LastOccurrenceDate: DateTime when this alert was last triggered Notifications: DataTable containing operators notified by this alert and their notification methods OccurrenceCount: Number of times this alert has been raised PerformanceCondition: Performance condition that triggers the alert (if performance-based) WmiEventNamespace: WMI namespace for WMI-based alerts WmiEventQuery: WMI query for WMI-based alerts Urn: Uniform Resource Name for the SMO object State: SMO object state (Existing, Creating, Pending, etc.) All properties from the base SMO Alert object are accessible using Select-Object . &nbsp;"
  },
  {
    "name": "New-DbaAgentAlertCategory",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "alert",
      "alertcategory"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaAgentAlertCategory",
    "popularityRank": 629,
    "synopsis": "Creates new SQL Agent alert categories for organizing and managing database alerts.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaAgentAlertCategory View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates new SQL Agent alert categories for organizing and managing database alerts. Description Creates custom alert categories in SQL Server Agent to help organize and group related alerts for better management and monitoring. Alert 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. This is particularly useful in environments with many alerts where categorization helps with organization, reporting, and maintenance workflows. Returns the newly created alert category objects that can be immediately used when configuring SQL Agent alerts. Syntax New-DbaAgentAlertCategory [-SqlInstance] [[-SqlCredential] ] [-Category] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new alert category with the name &#39;Category 1&#39; PS C:\\> New-DbaAgentAlertCategory -SqlInstance sql1 -Category 'Category 1' Example 2: Creates a new alert category with the name &#39;Category 2&#39; PS C:\\> 'sql1' | New-DbaAgentAlertCategory -Category 'Category 2' Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Category Specifies the name or names of the alert categories to create in SQL Server Agent. Use descriptive names that reflect how you organize alerts, such as 'Database Errors', 'Performance Issues', or 'Security Events'. Multiple categories can be created in a single operation by providing an array of category names. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Bypasses confirmation prompts and creates the alert categories without user interaction. Use this parameter in automated scripts or when you're confident about the category names being created. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.AlertCategory Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ID: Unique identifier for the alert category within the instance Name: The name of the alert category CategoryType: Type of category (Alert or JobStep) All properties from the base SMO AlertCategory object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaAgentJob",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "jobstep"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaAgentJob",
    "popularityRank": 157,
    "synopsis": "Creates SQL Server Agent jobs with notification settings and schedule assignments",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaAgentJob View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates SQL Server Agent jobs with notification settings and schedule assignments Description Creates SQL Server Agent jobs with full configuration options including owner assignment, job categories, and comprehensive notification settings. You can configure email, event log, pager, and netsend notifications with specific operators and trigger conditions (success, failure, completion). The function also supports attaching existing schedules during job creation and can automatically create missing job categories when using -Force. This replaces the manual process of using SQL Server Management Studio or T-SQL scripts to create and configure Agent jobs across multiple instances. Syntax New-DbaAgentJob [-SqlInstance] [[-SqlCredential] ] [-Job] [[-Schedule] ] [[-ScheduleId] ] [-Disabled] [[-Description] ] [[-StartStepId] ] [[-Category] ] [[-OwnerLogin] ] [[-EventLogLevel] ] [[-EmailLevel] ] [[-PageLevel] ] [[-EmailOperator] ] [[-NetsendOperator] ] [[-PageOperator] ] [[-DeleteLevel] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a job with the name &quot;Job1&quot; and a small description PS C:\\> New-DbaAgentJob -SqlInstance sql1 -Job 'Job One' -Description 'Just another job' Example 2: Creates the job but sets it to disabled PS C:\\> New-DbaAgentJob -SqlInstance sql1 -Job 'Job One' -Disabled Example 3: Creates the job and sets the notification to write to the Windows Application event log on success PS C:\\> New-DbaAgentJob -SqlInstance sql1 -Job 'Job One' -EventLogLevel OnSuccess Example 4: Creates the job and sets the notification to send an e-mail to the e-mail operator PS C:\\> New-DbaAgentJob -SqlInstance SSTAD-PC -Job 'Job One' -EmailLevel OnFailure -EmailOperator dba Example 5: Doesn&#39;t create the job but shows what would happen PS C:\\> New-DbaAgentJob -SqlInstance sql1 -Job 'Job One' -Description 'Just another job' -Whatif Example 6: Creates a job with the name &quot;Job One&quot; on multiple servers PS C:\\> New-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job 'Job One' Example 7: Creates a job with the name &quot;Job One&quot; on multiple servers using the pipe line PS C:\\> \"sql1\", \"sql2\", \"sql3\" | New-DbaAgentJob -Job 'Job One' Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Job The name of the job. The name must be unique and cannot contain the percent (%) character. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schedule Schedule to attach to job. This can be more than one schedule. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ScheduleId Schedule ID to attach to job. This can be more than one schedule ID. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Disabled Sets the status of the job to disabled. By default a job is enabled. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Description The description of the job. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartStepId The identification number of the first step to execute for the job. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Category The category of the job. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OwnerLogin The name of the login that owns the job. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EventLogLevel Specifies when to place an entry in the Microsoft Windows application log for this job. Allowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\" The text value can either be lowercase, uppercase or something in between as long as the text is correct. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 0,Never,1,OnSuccess,2,OnFailure,3,Always | -EmailLevel Specifies when to send an e-mail upon the completion of this job. Allowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\" The text value can either be lowercase, uppercase or something in between as long as the text is correct. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 0,Never,1,OnSuccess,2,OnFailure,3,Always | -PageLevel Specifies when to send a page upon the completion of this job. Allowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\" The text value can either be lowercase, uppercase or something in between as long as the text is correct. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NetsendOperator The name of the operator to whom the network message is sent. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PageOperator The name of the operator to whom a page is sent. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DeleteLevel Specifies when to delete the job. Allowed values 0, \"Never\", 1, \"OnSuccess\", 2, \"OnFailure\", 3, \"Always\" The text value can either be lowercase, uppercase or something in between as long as the text is correct. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 0,Never,1,OnSuccess,2,OnFailure,3,Always | -Force The force parameter will ignore some errors in the parameters and assume defaults. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.Job Returns 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 notification settings, schedules, and job category assignments. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the SQL Server Agent job Enabled: Boolean indicating if the job is enabled Description: The description of the job Owner: The owner login name of the job CreateDate: DateTime when the job was created LastModifiedDate: DateTime when the job was last modified Category: The category assigned to the job EventLogLevel: Notification level for Windows Application event log (Never, OnSuccess, OnFailure, Always) EmailLevel: Notification level for e-mail notifications (Never, OnSuccess, OnFailure, Always) NetSendLevel: Notification level for network message notifications (Never, OnSuccess, OnFailure, Always) PageLevel: Notification level for pager notifications (Never, OnSuccess, OnFailure, Always) DeleteLevel: Automatic deletion level (Never, OnSuccess, OnFailure, Always) IsScheduled: Boolean indicating if the job has schedules attached All properties from the base SMO Job object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaAgentJobCategory",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "jobcategory"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaAgentJobCategory",
    "popularityRank": 539,
    "synopsis": "Creates new SQL Server Agent job categories for organizing and managing jobs.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaAgentJobCategory View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates new SQL Server Agent job categories for organizing and managing jobs. 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. Syntax New-DbaAgentJobCategory [-SqlInstance] [[-SqlCredential] ] [-Category] [[-CategoryType] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new job category with the name &#39;Category 1&#39; PS C:\\> New-DbaAgentJobCategory -SqlInstance sql1 -Category 'Category 1' Example 2: Creates a new job category with the name &#39;Category 2&#39; and assign the category type for a multi server job PS C:\\> New-DbaAgentJobCategory -SqlInstance sql1 -Category 'Category 2' -CategoryType MultiServerJob Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -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. Use descriptive names that reflect job functions like 'Database Maintenance', 'ETL Jobs', or 'Reporting' to help organize jobs by purpose or department. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 general-purpose categories. Defaults to \"LocalJob\" when not specified, which is appropriate for most standalone SQL Server instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | LocalJob,MultiServerJob,None | -Force Suppresses confirmation prompts during category creation. Sets the confirmation preference to bypass interactive confirmation requests. Use this when automating category creation in scripts where manual confirmation is not desired or possible. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.JobCategory Returns one JobCategory object for each category created. The output is returned via Get-DbaAgentJobCategory after creation completes. Default display properties (via Get-DbaAgentJobCategory): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Name of the job category ID: Unique identifier for the category CategoryType: Type of category (LocalJob, MultiServerJob, or None) All properties from the base SMO JobCategory object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaAgentJobStep",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "jobstep"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaAgentJobStep",
    "popularityRank": 180,
    "synopsis": "Creates a new step within an existing SQL Server Agent job with configurable execution options and flow control",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaAgentJobStep View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a new step within an existing SQL Server Agent job with configurable execution options and flow control 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. Syntax New-DbaAgentJobStep [-SqlInstance] [[-SqlCredential] ] [-Job] [[-StepId] ] [-StepName] [[-Subsystem] ] [[-SubsystemServer] ] [[-Command] ] [[-CmdExecSuccessCode] ] [[-OnSuccessAction] ] [[-OnSuccessStepId] ] [[-OnFailAction] ] [[-OnFailStepId] ] [[-Database] ] [[-DatabaseUser] ] [[-RetryAttempts] ] [[-RetryInterval] ] [[-OutputFileName] ] [-Insert] [[-Flag] ] [[-ProxyName] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Create a step in &quot;Job1&quot; with the name Step1 with the default subsystem TransactSql PS C:\\> New-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 Example 2: Create a step in &quot;Job1&quot; with the name Step1 where the database will the msdb PS C:\\> New-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -Database msdb Example 3: Create a step in &quot;Job1&quot; with the name Step1 where the database will the &quot;msdb&quot; for multiple servers PS C:\\> New-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1 -Database msdb Example 4: Create a step in &quot;Job1&quot; with the name Step1 where the database will the &quot;msdb&quot; for multiple servers for... PS C:\\> New-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1, Job2, 'Job Three' -StepName Step1 -Database msdb Create a step in \"Job1\" with the name Step1 where the database will the \"msdb\" for multiple servers for multiple jobs Example 5: Create a step in &quot;Job1&quot; with the name Step1 where the database will the &quot;msdb&quot; for multiple servers using... PS C:\\> sql1, sql2, sql3 | New-DbaAgentJobStep -Job Job1 -StepName Step1 -Database msdb Create a step in \"Job1\" with the name Step1 where the database will the \"msdb\" for multiple servers using pipeline Example 6: Assuming Job1 already has steps Step1 and Step2, will create a new step Step A and set the step order as... PS C:\\> New-DbaAgentJobStep -SqlInstance sq1 -Job Job1 -StepName StepA -Database msdb -StepId 2 -Insert Assuming Job1 already has steps Step1 and Step2, will create a new step Step A and set the step order as Step1, StepA, Step2 Internal StepIds will be updated, and any specific OnSuccess/OnFailure step references will also be updated Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Job Specifies the SQL Server Agent job name where the new step will be added. Accepts job names or job objects from Get-DbaAgentJob. Use this to target specific jobs when building multi-step automation workflows. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -StepName Defines a descriptive name for the job step that appears in SQL Server Agent and job history logs. Choose meaningful names that clearly identify the step's purpose for easier troubleshooting and maintenance. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StepId Sets the execution order position for this step within the job sequence. Step numbers start at 1 and must be sequential. Use this to control step execution order or when inserting steps between existing ones. If not specified, adds the step at the end. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Subsystem Determines what execution engine SQL Server Agent uses to run the step command. Defaults to 'TransactSql' for T-SQL scripts. Use 'PowerShell' for PowerShell scripts, 'CmdExec' for operating system commands, 'Ssis' for SSIS packages, or replication subsystems for replication tasks. Analysis subsystems require SQL Server Analysis Services and the SubSystemServer parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | TransactSql | | Accepted Values | 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. Required for Analysis Services job steps to connect to the appropriate SSAS instance for cube processing or MDX queries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Command Contains the actual code or command that the job step will execute, such as T-SQL scripts, PowerShell code, or operating system commands. The command syntax must match the specified subsystem type. For T-SQL steps, include complete SQL statements or stored procedure calls. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CmdExecSuccessCode Defines the exit code that indicates successful completion for CmdExec subsystem steps. Most applications return 0 for success. Use this when running batch files or executables that return non-zero success codes to prevent the job from failing incorrectly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -OnSuccessAction Controls job flow when this step completes successfully. Default 'QuitWithSuccess' ends the job with success status. Use 'GoToNextStep' for sequential execution, 'GoToStep' to jump to a specific step, or 'QuitWithFailure' for conditional failure handling. Essential for building complex workflows with branching logic based on step outcomes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | QuitWithSuccess | | Accepted Values | QuitWithSuccess,QuitWithFailure,GoToNextStep,GoToStep | -OnSuccessStepId Specifies which step to execute next when OnSuccessAction is set to 'GoToStep' and this step succeeds. Use this to create conditional branching in job workflows, such as skipping cleanup steps when data processing completes successfully. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -OnFailAction Determines job behavior when this step fails. Default 'QuitWithFailure' stops the job and reports failure. Use 'GoToNextStep' to continue despite failures, 'GoToStep' for error handling routines, or 'QuitWithSuccess' when failure is acceptable. Critical for implementing error handling and recovery procedures in automated processes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | QuitWithFailure | | Accepted Values | QuitWithFailure,QuitWithSuccess,GoToNextStep,GoToStep | -OnFailStepId Identifies the step to execute when OnFailAction is 'GoToStep' and this step fails. Use this to implement error handling workflows, such as sending notifications or running cleanup procedures when critical steps fail. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Database Specifies the database context for TransactSql subsystem steps. Defaults to 'master' if not specified. Set this to the appropriate database where your T-SQL commands should execute, as it determines schema resolution and object access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DatabaseUser Sets the database user context for executing T-SQL steps, overriding the SQL Server Agent service account permissions. Use this when the step needs specific database-level permissions that differ from the Agent service account's access rights. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RetryAttempts Sets how many times SQL Server Agent will retry this step if it fails before considering it permanently failed. Use this for steps that might fail due to temporary issues like network connectivity or resource contention. Defaults to 0 (no retries). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RetryInterval Defines the wait time in minutes between retry attempts when a step fails. Defaults to 0 (immediate retry). Set appropriate intervals to allow temporary issues to resolve, such as waiting for locked resources or network recovery. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -OutputFileName Specifies a file path where the step's output will be written for logging and troubleshooting purposes. Use this to capture command results, error messages, or progress information for later analysis when jobs fail or need auditing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Insert Inserts the new step at the specified StepId position, automatically renumbering subsequent steps and updating their references. Use this when adding steps to existing jobs without breaking the workflow sequence, such as inserting validation steps between existing processes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Flag Controls how job step output and history are logged and stored. Multiple flags can be specified for comprehensive logging. Use 'AppendAllCmdExecOutputToJobHistory' to capture command output in job history, 'AppendToLogFile' for SQL Server error log entries, or 'AppendToTableLog' for database table logging. Essential for troubleshooting and auditing job execution, especially for steps that generate important output or error information. Flag Description ---------------------------------------------------------------------------- AppendAllCmdExecOutputToJobHistory Job history, including command output, is appended to the job history file. AppendToJobHistory Job history is appended to the job history file. AppendToLogFile Job history is appended to the SQL Server log file. AppendToTableLog Job history is appended to a log table. LogToTableWithOverwrite Job history is written to a log table, overwriting previous contents. None Job history is not appended to a file. ProvideStopProcessEvent Job processing is stopped. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this when steps need specific Windows credentials for file system access, network resources, or applications that require different security contexts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Bypasses validation checks and overwrites existing steps with the same name or ID. Use this when recreating steps during development or when you need to replace existing steps without manual deletion first. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.JobStep Returns the newly created JobStep object with all properties configured according to the specified parameters. Returned properties (includes all standard SMO JobStep properties plus configured settings): Name: The descriptive name of the job step ID: The execution sequence number for this step within the job (starting at 1) Parent: Reference to the parent Job object containing this step Subsystem: The execution engine type (TransactSql, PowerShell, CmdExec, Ssis, etc.) Command: The actual code or command to be executed DatabaseName: The database context for T-SQL steps DatabaseUserName: The database user context for T-SQL execution OnSuccessAction: Action to take when step completes successfully (QuitWithSuccess, GoToNextStep, GoToStep, QuitWithFailure) OnSuccessStep: Step ID to jump to on success when using GoToStep OnFailAction: Action to take when step fails (QuitWithFailure, GoToNextStep, GoToStep, QuitWithSuccess) OnFailStep: Step ID to jump to on failure when using GoToStep RetryAttempts: Number of times to retry the step on failure RetryInterval: Minutes to wait between retry attempts OutputFileName: File path where step output will be logged ProxyName: SQL Server Agent proxy account used for step execution JobStepFlags: Logging and output flags (AppendToJobHistory, AppendToLogFile, etc.) Server: Analysis Services server for SSAS job steps CommandExecutionSuccessCode: Exit code indicating success for CmdExec steps All properties from the base SMO JobStep object are accessible even though only the configured properties above are set during creation. &nbsp;"
  },
  {
    "name": "New-DbaAgentOperator",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "operator"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaAgentOperator",
    "popularityRank": 465,
    "synopsis": "Creates a new SQL Server Agent operator with notification settings for alerts and job failures.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaAgentOperator View Source Tracy Boggiano (@TracyBoggiano), databasesuperhero.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a new SQL Server Agent operator with notification settings for alerts and job failures. 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. Syntax New-DbaAgentOperator [[-SqlInstance] ] [[-SqlCredential] ] [-Operator] [[-EmailAddress] ] [[-NetSendAddress] ] [[-PagerAddress] ] [[-PagerDay] ] [[-SaturdayStartTime] ] [[-SaturdayEndTime] ] [[-SundayStartTime] ] [[-SundayEndTime] ] [[-WeekdayStartTime] ] [[-WeekdayEndTime] ] [-IsFailsafeOperator] [[-FailsafeNotificationMethod] ] [-Force] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: This sets a new operator named DBA with the above email address with default values to alerts everyday for... PS C:\\> New-DbaAgentOperator -SqlInstance sql01 -Operator DBA -EmailAddress operator@operator.com -PagerDay Everyday -Force This sets a new operator named DBA with the above email address with default values to alerts everyday for all hours of the day. Example 2: Creates a new operator named DBA on the sql01 instance with email address operator@operator.com, net send... PS C:\\> New-DbaAgentOperator -SqlInstance sql01 -Operator DBA -EmailAddress operator@operator.com ` >> -NetSendAddress dbauser1 -PagerAddress dbauser1@pager.dbatools.io -PagerDay Everyday ` >> -SaturdayStartTime 070000 -SaturdayEndTime 180000 -SundayStartTime 080000 ` >> -SundayEndTime 170000 -WeekdayStartTime 060000 -WeekdayEndTime 190000 Creates 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, Saturday 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. Required Parameters -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. Use descriptive names like 'DBA Team' or 'On-Call Admin' to identify who receives notifications. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EmailAddress Email address where SQL Server Agent sends alert notifications and job failure notifications. This is the primary notification method for most operators. Specify a monitored email address or distribution list that reaches the appropriate support staff. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NetSendAddress Network address for receiving net send messages from SQL Server Agent. This is a legacy Windows messaging system rarely used in modern environments. Most organizations use email notifications instead since net send requires specific network configurations and may not work across subnets. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Configure pager schedules with PagerDay and time parameters to control when these urgent notifications are sent. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Choose 'Weekdays' for business-hour coverage, 'EveryDay' for 24/7 support, or specific days like 'Monday' through 'Sunday' for rotation schedules. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | EveryDay,Weekdays,Weekend,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday | -SaturdayStartTime Starting time for Saturday pager notifications in HHMMSS format (e.g., '080000' for 8:00 AM). Required when PagerDay includes Saturday, Weekend, or EveryDay. Use '000000' for midnight start times or specify business hours to limit when urgent alerts are sent. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SaturdayEndTime Ending time for Saturday pager notifications in HHMMSS format (e.g., '180000' for 6:00 PM). Must be specified with SaturdayStartTime. Use '235959' for end-of-day coverage or match your organization's Saturday support hours. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SundayStartTime Starting time for Sunday pager notifications in HHMMSS format (e.g., '090000' for 9:00 AM). Required when PagerDay includes Sunday, Weekend, or EveryDay. Configure based on your weekend support schedule or emergency-only coverage requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SundayEndTime Ending time for Sunday pager notifications in HHMMSS format (e.g., '170000' for 5:00 PM). Must be specified with SundayStartTime. Set to match your organization's weekend support availability or use '235959' for full-day coverage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -WeekdayStartTime Starting time for weekday pager notifications in HHMMSS format (e.g., '060000' for 6:00 AM). Required when PagerDay includes Weekdays or individual weekdays. Typically set to business hours start time or earlier for critical production monitoring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -WeekdayEndTime Ending time for weekday pager notifications in HHMMSS format (e.g., '190000' for 7:00 PM). Must be specified with WeekdayStartTime. Configure to match business hours end time or extend for after-hours support coverage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IsFailsafeOperator Designates this operator as the failsafe operator for the SQL Server instance. The failsafe operator receives notifications when all other operators are unavailable. Only one failsafe operator can exist per instance, and this setting replaces any existing failsafe operator configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FailsafeNotificationMethod Specifies how the failsafe operator receives notifications when used with IsFailsafeOperator. Choose 'NotifyEmail' for email notifications or 'NotifyPager' for pager alerts. Defaults to 'NotifyEmail' which works with most modern notification systems and email-to-SMS gateways. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when updating operator configurations or when you need to ensure consistent settings across multiple environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when you have existing server connections or need to process multiple instances with specific connection properties. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.Operator Returns one Operator object for the newly created SQL Server Agent operator. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the operator EmailAddress: Email address for alert notifications NetSendAddress: Network send address for notifications PagerAddress: Pager email address for urgent alerts Enabled: Boolean indicating if the operator is active LastEmailDate: DateTime of the most recent email sent to this operator LastNetSendDate: DateTime of the most recent net send notification LastPagerDate: DateTime of the most recent pager notification Additional properties available (from SMO Operator object): ID: Unique identifier for the operator CategoryName: Alert category classification PagerDays: Bitmask indicating which days pager notifications are active WeekdayPagerStartTime: Start time for weekday pager notifications (HH:MM:SS format) WeekdayPagerEndTime: End time for weekday pager notifications (HH:MM:SS format) SaturdayPagerStartTime: Start time for Saturday pager notifications (HH:MM:SS format) SaturdayPagerEndTime: End time for Saturday pager notifications (HH:MM:SS format) SundayPagerStartTime: Start time for Sunday pager notifications (HH:MM:SS format) SundayPagerEndTime: End time for Sunday pager notifications (HH:MM:SS format) Parent: Reference to the parent JobServer object All properties from the base SMO Operator object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaAgentProxy",
    "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",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "proxy"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaAgentProxy",
    "popularityRank": 0,
    "synopsis": "Creates SQL Server Agent proxy accounts to enable job steps to run under different security contexts",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaAgentProxy View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates SQL Server Agent proxy accounts to enable job steps to run under different security contexts 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. You 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. Note: 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 Syntax New-DbaAgentProxy [-SqlInstance] [[-SqlCredential] ] [-Name] [-ProxyCredential] [[-SubSystem] ] [[-Description] ] [[-Login] ] [[-ServerRole] ] [[-MsdbRole] ] [-Disabled] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates an Agent Proxy on sql2016 with the name STIG with the &#39;PowerShell Proxy&#39; credential PS C:\\> New-DbaAgentProxy -SqlInstance sql2016 -Name STIG -ProxyCredential 'PowerShell Proxy' Creates an Agent Proxy on sql2016 with the name STIG with the 'PowerShell Proxy' credential. The proxy is automatically added to the CmdExec subsystem. Example 2: -ServerRole securityadmin -MsdbRole ServerGroupAdministratorRole Creates an Agent Proxy on sql2016 with the... PS C:\\> New-DbaAgentProxy -SqlInstance localhost\\sql2016 -Name STIG -ProxyCredential 'PowerShell Proxy' -Description \"Used for auditing purposes\" -Login ad\\sqlstig -SubSystem CmdExec, PowerShell -ServerRole securityadmin -MsdbRole ServerGroupAdministratorRole Creates an Agent Proxy on sql2016 with the name STIG with the 'PowerShell Proxy' credential and the following principals: Login: ad\\sqlstig ServerRole: securityadmin MsdbRole: ServerGroupAdministratorRole By default, only sysadmins have access to create job steps with proxies. This will allow 3 additional principals access: The proxy is then added to the CmdExec and PowerShell subsystems Required Parameters -SqlInstance The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Name Specifies the name for the SQL Agent proxy account being created. The name must be unique within the SQL Server instance. Use a descriptive name that indicates the proxy's purpose or the credential it represents for easier management. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. This credential defines the Windows account under which job steps will run when using this proxy. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SubSystem Specifies which SQL Agent subsystems can use this proxy account for job step execution. Defaults to CmdExec if not specified. Multiple subsystems can be assigned to a single proxy, allowing it to run different types of job steps under the same security context. Valid options include: ActiveScripting AnalysisCommand AnalysisQuery CmdExec Distribution LogReader Merge PowerShell QueueReader Snapshot Ssis | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | CmdExec | | Accepted Values | 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. Use this to help other DBAs understand when and how this proxy should be used in job steps. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Specifies which SQL Server logins can use this proxy account in their job steps. By default, only sysadmin members can use proxy accounts. Add specific logins here to grant non-sysadmin users the ability to create job steps that run under this proxy's security context. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. This provides role-based access control for proxy usage without needing to grant permissions to individual logins. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MsdbRole Specifies which msdb database roles can use this proxy account in job steps. Common roles include SQLAgentUserRole, SQLAgentReaderRole, and SQLAgentOperatorRole. This allows you to grant proxy access based on existing Agent role membership rather than individual user assignments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Disabled Creates the proxy account in a disabled state, preventing its immediate use in job steps. Use this when you need to set up the proxy configuration first before allowing job steps to use it. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Drops and recreates the proxy account if one with the same name already exists on the instance. Without this switch, the function will skip existing proxy accounts and display a warning message. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.ProxyAccount Returns one ProxyAccount object for the newly created SQL Server Agent proxy account. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ID: Unique identifier for the proxy account Name: The name of the proxy account CredentialName: Name of the SQL Server credential used by this proxy CredentialIdentity: The Windows account or identity associated with the credential Description: Text description of the proxy's purpose or usage Logins: Array of SQL Server logins that have permission to use this proxy ServerRoles: Array of server roles that have permission to use this proxy MsdbRoles: Array of msdb database roles that have permission to use this proxy SubSystems: Array of SQL Agent subsystems this proxy can execute (CmdExec, PowerShell, SSIS, etc.) IsEnabled: Boolean indicating if the proxy is currently enabled and usable Additional properties available (from SMO ProxyAccount object): CredentialID: Internal identifier for the associated credential Parent: Reference to the parent JobServer object Urn: The Uniform Resource Name for the proxy account object State: Current state of the object (Existing, Creating, Pending, etc.) All properties from the base SMO ProxyAccount object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaAgentSchedule",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "jobstep"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaAgentSchedule",
    "popularityRank": 198,
    "synopsis": "Creates a new SQL Server Agent schedule for automated job execution",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaAgentSchedule View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a new SQL Server Agent schedule for automated job execution 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. Syntax New-DbaAgentSchedule [-SqlInstance] [[-SqlCredential] ] [[-Job] ] [[-Schedule] ] [-Disabled] [[-FrequencyType] ] [[-FrequencyInterval] ] [[-FrequencySubdayType] ] [[-FrequencySubdayInterval] ] [[-FrequencyRelativeInterval] ] [[-FrequencyRecurrenceFactor] ] [[-FrequencyText] ] [[-StartDate] ] [[-EndDate] ] [[-StartTime] ] [[-EndTime] ] [[-Owner] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a schedule that runs jobs every day at 6 in the morning PS C:\\> New-DbaAgentSchedule -SqlInstance sql01 -Schedule DailyAt6 -FrequencyType Daily -StartTime \"060000\" -Force Creates 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. Example 2: Creates a schedule with a daily frequency every day PS C:\\> New-DbaAgentSchedule -SqlInstance localhost\\SQL2016 -Schedule daily -FrequencyType Daily -FrequencyInterval Everyday -Force Creates 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. Example 3: Create a schedule with a monthly frequency occuring every 10th of the month PS C:\\> New-DbaAgentSchedule -SqlInstance sstad-pc -Schedule MonthlyTest -FrequencyType Monthly -FrequencyInterval 10 -FrequencyRecurrenceFactor 1 -Force Create 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. Example 4: Create a schedule that will run jobs once a week on Sunday @ 1:00AM PS C:\\> New-DbaAgentSchedule -SqlInstance sstad-pc -Schedule RunWeekly -FrequencyType Weekly -FrequencyInterval Sunday -StartTime 010000 -Force Example 5: Create a schedule with the name &quot;Every sunday at 02:00:00&quot; that will run jobs once a week on Sunday @ 2:00AM PS C:\\> New-DbaAgentSchedule -SqlInstance sstad-pc -FrequencyText 'Every sunday at 02:00:00' Example 6: SqlInstance = &quot;sql01&quot; Schedule = &quot;HourlyBusinessHours&quot; FrequencyType = &quot;Daily&quot; FrequencySubdayType = &quot;Hours&quot;... PS C:\\> $splatSchedule = @{ PS C:\\> New-DbaAgentSchedule @splatSchedule SqlInstance = \"sql01\" Schedule = \"HourlyBusinessHours\" FrequencyType = \"Daily\" FrequencySubdayType = \"Hours\" FrequencySubdayInterval = 1 StartTime = \"080000\" EndTime = \"170000\" Force = $true } Creates 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. Example 7: SqlInstance = &quot;sql01&quot; Schedule = &quot;EveryFiveMinutes&quot; FrequencyType = &quot;Daily&quot; FrequencySubdayType = &quot;Minutes&quot;... PS C:\\> $splatSchedule = @{ PS C:\\> New-DbaAgentSchedule @splatSchedule SqlInstance = \"sql01\" Schedule = \"EveryFiveMinutes\" FrequencyType = \"Daily\" FrequencySubdayType = \"Minutes\" FrequencySubdayInterval = 5 Force = $true } Creates a schedule that runs every 5 minutes throughout the day. Useful for frequent monitoring jobs that need to check system health regularly. Example 8: SqlInstance = &quot;sql01&quot; Schedule = &quot;TwiceDaily&quot; FrequencyType = &quot;Daily&quot; FrequencySubdayType = &quot;Hours&quot;... PS C:\\> $splatSchedule = @{ PS C:\\> New-DbaAgentSchedule @splatSchedule SqlInstance = \"sql01\" Schedule = \"TwiceDaily\" FrequencyType = \"Daily\" FrequencySubdayType = \"Hours\" FrequencySubdayInterval = 12 StartTime = \"060000\" Force = $true } Creates 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. Example 9: SqlInstance = &quot;sql01&quot; Schedule = &quot;FirstMondayOfMonth&quot; FrequencyType = &quot;MonthlyRelative&quot; FrequencyInterval =... PS C:\\> $splatSchedule = @{ PS C:\\> New-DbaAgentSchedule @splatSchedule SqlInstance = \"sql01\" Schedule = \"FirstMondayOfMonth\" FrequencyType = \"MonthlyRelative\" FrequencyInterval = \"Monday\" FrequencyRelativeInterval = \"First\" FrequencyRecurrenceFactor = 1 StartTime = \"020000\" Force = $true } Creates 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. Example 10: SqlInstance = &quot;sql01&quot; Schedule = &quot;MaintenanceWindow&quot; FrequencyType = &quot;Weekly&quot; FrequencyInterval = &quot;Saturday&quot;... PS C:\\> $splatSchedule = @{ PS C:\\> New-DbaAgentSchedule @splatSchedule SqlInstance = \"sql01\" Schedule = \"MaintenanceWindow\" FrequencyType = \"Weekly\" FrequencyInterval = \"Saturday\", \"Sunday\" StartTime = \"220000\" EndTime = \"060000\" StartDate = \"20250101\" EndDate = \"20251231\" Force = $true } Creates 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. Example 11: SqlInstance = &quot;sql01&quot; Schedule = &quot;PreprodRefresh&quot; Disabled = $true FrequencyType = &quot;Weekly&quot; FrequencyInterval... PS C:\\> $splatSchedule = @{ PS C:\\> New-DbaAgentSchedule @splatSchedule SqlInstance = \"sql01\" Schedule = \"PreprodRefresh\" Disabled = $true FrequencyType = \"Weekly\" FrequencyInterval = \"Sunday\" StartTime = \"040000\" Force = $true } Creates a disabled schedule for pre-production database refreshes. The schedule is configured but won't execute until manually enabled, allowing you to prepare schedules in advance. Example 12: SqlInstance = &quot;sql01&quot; Job = &quot;BackupUserDatabases&quot;, &quot;CheckDBIntegrity&quot;, &quot;UpdateStatistics&quot; Schedule =... PS C:\\> $splatSchedule = @{ PS C:\\> New-DbaAgentSchedule @splatSchedule SqlInstance = \"sql01\" Job = \"BackupUserDatabases\", \"CheckDBIntegrity\", \"UpdateStatistics\" Schedule = \"NightlyMaintenance\" FrequencyType = \"Daily\" StartTime = \"010000\" Force = $true } Creates a schedule and immediately attaches it to three different jobs. This demonstrates how to apply a single schedule to multiple jobs in one command. Example 13: SqlInstance = &quot;sql01&quot; Schedule = &quot;QuarterEndReports&quot; FrequencyType = &quot;Monthly&quot; FrequencyInterval = 31... PS C:\\> $splatSchedule = @{ PS C:\\> New-DbaAgentSchedule @splatSchedule SqlInstance = \"sql01\" Schedule = \"QuarterEndReports\" FrequencyType = \"Monthly\" FrequencyInterval = 31 FrequencyRecurrenceFactor = 3 StartTime = \"180000\" Owner = \"DOMAIN\\SQLServiceAccount\" Force = $true } Creates 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. Example 14: SqlInstance = &quot;sql01&quot; Schedule = &quot;BusinessHoursEvery30Min&quot; FrequencyType = &quot;Daily&quot; FrequencySubdayType =... PS C:\\> $splatSchedule = @{ PS C:\\> New-DbaAgentSchedule @splatSchedule SqlInstance = \"sql01\" Schedule = \"BusinessHoursEvery30Min\" FrequencyType = \"Daily\" FrequencySubdayType = \"Minutes\" FrequencySubdayInterval = 30 StartTime = \"083000\" EndTime = \"173000\" Force = $true } Creates 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. Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies existing SQL Server Agent jobs to immediately attach this schedule to after creation. Use this when you want to apply the same schedule to multiple jobs without manually attaching it later through SSMS. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schedule The name for the new schedule that will appear in SQL Server Agent. Choose descriptive names like \"DailyAt6AM\" or \"WeeklyMaintenanceWindow\" to make schedule management easier for your team. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Disabled Creates the schedule in a disabled state, preventing any attached jobs from running until the schedule is manually enabled. Use this when you need to set up schedules in advance but don't want them active immediately. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FrequencyType Determines the basic execution pattern for jobs using this schedule. Daily 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.\" Once/OneTime creates single-execution schedules, while AgentStart/AutoStart and IdleComputer/OnIdle create event-triggered schedules. Allowed values: 'Once', 'OneTime', 'Daily', 'Weekly', 'Monthly', 'MonthlyRelative', 'AgentStart', 'AutoStart', 'IdleComputer', 'OnIdle' The following synonyms provide flexibility to the allowed values for this function parameter: Once=OneTime AgentStart=AutoStart IdleComputer=OnIdle If force is used the default will be \"Once\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Once,OneTime,Daily,Weekly,Monthly,MonthlyRelative,AgentStart,AutoStart,IdleComputer,OnIdle | -FrequencyInterval Defines which specific days the job executes based on the FrequencyType selected. For Daily: use numbers 1-365 for \"every N days\" or \"EveryDay\" for daily execution. For Weekly: specify day names like \"Monday,Friday\" or use \"Weekdays,\" \"Weekend,\" or \"EveryDay.\" For Monthly: use numbers 1-31 to run on specific dates of each month. Allowed values for FrequencyType 'Daily': EveryDay or a number between 1 and 365. Allowed values for FrequencyType 'Weekly': Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Weekdays, Weekend or EveryDay. Allowed values for FrequencyType 'Monthly': Numbers 1 to 31 for each day of the month. If \"Weekdays\", \"Weekend\" or \"EveryDay\" is used it over writes any other value that has been passed before. If force is used the default will be 1. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FrequencySubdayType Sets the time interval unit when jobs need to run multiple times per day. Use \"Once\" for single daily execution, \"Hours\" for hourly intervals, \"Minutes\" for minute-based intervals, or \"Seconds\" for very frequent execution. Most maintenance jobs use \"Once\" while monitoring jobs might use \"Minutes\" or \"Hours.\" Allowed values: 'Once', 'Time', 'Seconds', 'Second', 'Minutes', 'Minute', 'Hours', 'Hour' The following synonyms provide flexibility to the allowed values for this function parameter: Once=Time Seconds=Second Minutes=Minute Hours=Hour | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Once,Time,Seconds,Second,Minutes,Minute,Hours,Hour | -FrequencySubdayInterval Specifies how often the job repeats within a day when FrequencySubdayType is not \"Once.\" For example, with FrequencySubdayType \"Hours\" and FrequencySubdayInterval 4, the job runs every 4 hours. Minimum interval is 10 seconds for second-based scheduling. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -FrequencyRelativeInterval Determines which occurrence of a day type to use for MonthlyRelative schedules. Use \"First\" for first occurrence, \"Second\" for second occurrence, etc., or \"Last\" for the final occurrence of that day in the month. For example, \"Second\" with \"Friday\" runs on the second Friday of each month. Allowed values: First, Second, Third, Fourth or Last | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Unused,First,Second,Third,Fourth,Last | -FrequencyRecurrenceFactor Controls how many weeks or months to skip between executions for Weekly, Monthly, and MonthlyRelative schedules. Use 1 for every week/month, 2 for every other week/month, 3 for every third, etc. This allows schedules like \"every 2 weeks on Monday\" or \"every 3 months on the 15th.\" FrequencyRecurrenceFactor is used only if FrequencyType is \"Weekly\", \"Monthly\" or \"MonthlyRelative\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -FrequencyText Describe common frequencies as a text. Sample text: Every minute Every 5 minutes Every 10 minutes starting at 00:02:30 Every hour Every 2 hours Every 4 hours starting at 02:00:00 Every day at 05:00:00 Every sunday at 02:00:00 This is the used regex: every(\\s+(? \\d+))?\\s+(? minute|hour|day|sunday|monday|tuesday|wednesday|thursday|friday|saturday)s?(\\s+starting)?(\\s+at\\s+(? \\d\\d:\\d\\d:\\d\\d))? If parameter Schedule is not provided, the FrequencyText will be used as the name of the schedule. Parameter Force will be set to $true. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartDate The earliest date this schedule can execute jobs, formatted as yyyyMMdd (e.g., \"20240315\" for March 15, 2024). Use this to delay schedule activation until a future date or to document when recurring maintenance should begin. With -Force, defaults to today's date. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EndDate The latest date this schedule can execute jobs, formatted as yyyyMMdd (e.g., \"20241231\" for December 31, 2024). Use this for temporary schedules or to automatically deactivate seasonal jobs. With -Force, defaults to \"99991231\" (no expiration). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartTime The time of day when job execution can begin, formatted as HHmmss in 24-hour format (e.g., \"143000\" for 2:30 PM). For subday schedules, this is when the first execution occurs each day. With -Force, defaults to \"000000\" (midnight). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EndTime The time of day when job execution must stop, formatted as HHmmss in 24-hour format (e.g., \"180000\" for 6:00 PM). For subday schedules, no new executions start after this time, but running jobs can complete. With -Force, defaults to \"235959\" (one second before midnight). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Owner The SQL Server login that owns this schedule, which determines permissions for schedule modification. Defaults to the login running this command, but you can specify a service account or DBA login for centralized schedule management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Bypasses parameter validation and applies default values for missing required parameters like dates and times. Also removes any existing schedule with the same name before creating the new one, preventing naming conflicts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.JobSchedule Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the schedule IsEnabled: Boolean indicating if the schedule is enabled FrequencyTypes: The frequency type (Once, Daily, Weekly, Monthly, etc.) NextRunDate: DateTime of the next scheduled execution LastRunDate: DateTime of the last scheduled execution Additional properties available from the SMO JobSchedule object include: FrequencyInterval: The frequency interval value FrequencySubDayTypes: The subday frequency type (Once, Hours, Minutes, Seconds) FrequencySubDayInterval: The subday frequency interval FrequencyRelativeIntervals: The relative interval for monthly relative schedules FrequencyRecurrenceFactor: How often the schedule repeats (weeks or months) ActiveStartDate: The date when the schedule becomes active ActiveEndDate: The date when the schedule stops being active ActiveStartTimeOfDay: The time when the schedule starts each day ActiveEndTimeOfDay: The time when the schedule stops each day OwnerLoginName: The login that owns the schedule DateCreated: DateTime when the schedule was created ID: Unique identifier for the schedule ScheduleUid: Unique GUID for the schedule All properties from the base SMO JobSchedule object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaAvailabilityGroup",
    "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't 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're 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/",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaAvailabilityGroup",
    "popularityRank": 89,
    "synopsis": "Creates SQL Server availability groups with automated replica setup, database seeding, and listener configuration.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaAvailabilityGroup View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates SQL Server availability groups with automated replica setup, database seeding, and listener configuration. 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't have to manually coordinate across multiple servers and troubleshoot common setup issues. Perfect 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. Validates prerequisites across all instances Creates availability group and configures primary replica Sets up database mirroring endpoints with proper authentication Adds and joins secondary replicas automatically Seeds databases using backup/restore or direct seeding Configures listeners with static IP or DHCP Grants necessary cluster and endpoint permissions Enables AlwaysOn_health extended events sessions The command handles the complex coordination between servers that trips up manual setups - endpoint permissions, service account access, database seeding modes, and cluster integration. NOTES: If a backup / restore is performed, the backups will be left intact on the network share. If you're using SQL Server on Linux and a fully qualified domain name is required, please use the FQDN to create a proper Endpoint PLEASE NOTE THE CHANGED DEFAULTS: Starting with version 1.1.x we changed the defaults of the following parameters to have the same defaults as the T-SQL command \"CREATE AVAILABILITY GROUP\" and the wizard in SQL Server Management Studio: ClusterType from External to Wsfc (Windows Server Failover Cluster). FailureConditionLevel from OnServerDown (Level 1) to OnCriticalServerErrors (Level 3). ConnectionModeInSecondaryRole from AllowAllConnections (ALL) to AllowNoConnections (NO). To change these defaults we have introduced configuration parameters for all of them, see documentation of the parameters for details. Thanks for this, Thomas Stringer! https://blogs.technet.microsoft.com/heyscriptingguy/2013/04/29/set-up-an-alwayson-availability-group-with-powershell/ Syntax New-DbaAvailabilityGroup [[-Primary] ] [[-PrimarySqlCredential] ] [[-Secondary] ] [[-SecondarySqlCredential] ] [-Name] [-IsContained] [-ReuseSystemDatabases] [-DtcSupport] [[-ClusterType] ] [[-AutomatedBackupPreference] ] [[-FailureConditionLevel] ] [[-HealthCheckTimeout] ] [-Basic] [-DatabaseHealthTrigger] [-Passthru] [[-Database] ] [[-SharedPath] ] [-UseLastBackup] [-Force] [[-AvailabilityMode] ] [[-FailoverMode] ] [[-BackupPriority] ] [[-ConnectionModeInPrimaryRole] ] [[-ConnectionModeInSecondaryRole] ] [[-SeedingMode] ] [[-Endpoint] ] [[-EndpointUrl] ] [[-Certificate] ] [-ConfigureXESession] [[-IPAddress] ] [[-SubnetMask] ] [[-Port] ] [-Dhcp] [[-ClusterConnectionOption] ] [[-MasterKeySecurePassword] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new availability group on sql2016a named SharePoint PS C:\\> New-DbaAvailabilityGroup -Primary sql2016a -Name SharePoint Example 2: Creates a new availability group on sql2016a named SharePoint with a secondary replica, sql2016b PS C:\\> New-DbaAvailabilityGroup -Primary sql2016a -Name SharePoint -Secondary sql2016b Example 3: Creates a basic availability group named BAG1 on sql2016std and does not confirm when setting up PS C:\\> New-DbaAvailabilityGroup -Primary sql2016std -Name BAG1 -Basic -Confirm:$false Example 4: Creates a contained availability group named AgContained on nodes sql2022n01 and sql2022n02 PS C:\\> New-DbaAvailabilityGroup -Primary sql2022n01 -Secondary sql2022n02 -Name AgContained -IsContained Example 5: Creates an availability group on sql2016b with the name ag1 PS C:\\> New-DbaAvailabilityGroup -Primary sql2016b -Name AG1 -Dhcp -Database db1 -UseLastBackup Creates an availability group on sql2016b with the name ag1. Uses the last backups available to add the database db1 to the AG. Example 6: Creates a new availability group on sql2017 named SharePoint with a cluster type of none and a failover mode... PS C:\\> New-DbaAvailabilityGroup -Primary sql2017 -Name SharePoint -ClusterType None -FailoverMode Manual Creates a new availability group on sql2017 named SharePoint with a cluster type of none and a failover mode of manual Example 7: Creates a new availability group with a primary replica on sql1 and a secondary on sql2 PS C:\\> New-DbaAvailabilityGroup -Primary sql1 -Secondary sql2 -Name ag1 -Database pubs -ClusterType None -SeedingMode Automatic -FailoverMode Manual Creates a new availability group with a primary replica on sql1 and a secondary on sql2. Automatically adds the database pubs. Example 8: Creates a new availability group with a primary replica on sql1 and a secondary on sql2 with custom endpoint... PS C:\\> New-DbaAvailabilityGroup -Primary sql1 -Secondary sql2 -Name ag1 -Database pubs -EndpointUrl 'TCP://sql1.specialnet.local:5022', 'TCP://sql2.specialnet.local:5022' Creates a new availability group with a primary replica on sql1 and a secondary on sql2 with custom endpoint urls. Automatically adds the database pubs. Example 9: This exact command was used to create an availability group on docker! PS C:\\> $cred = Get-Credential sqladmin PS C:\\> $params = @{ >> Primary = \"sql1\" >> PrimarySqlCredential = $cred >> Secondary = \"sql2\" >> SecondarySqlCredential = $cred >> Name = \"test-ag\" >> Database = \"pubs\" >> ClusterType = \"None\" >> SeedingMode = \"Automatic\" >> FailoverMode = \"Manual\" >> Confirm = $false >> } PS C:\\> New-DbaAvailabilityGroup @params Required Parameters -Name Specifies the name for the new availability group. This name must be unique across all availability groups in the Windows Server Failover Cluster. Choose a descriptive name that reflects the application or purpose, as this will be used for monitoring and management. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -Primary Specifies the SQL Server instance that will host the primary replica of the availability group. This instance must have AlwaysOn Availability Groups enabled and be running SQL Server 2012 or higher. Use this when setting up the main server that will handle write operations and coordinate with secondary replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -PrimarySqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Secondary Specifies one or more SQL Server instances that will host secondary replicas in the availability group. All instances must have AlwaysOn enabled and be running SQL Server 2012 or higher. These servers will receive synchronized copies of your databases and can serve read-only workloads or provide disaster recovery. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecondarySqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IsContained Creates a contained availability group that includes system databases alongside user databases. Only supported in SQL Server 2022 and above, this eliminates the need to manually synchronize logins and jobs. Use this for simplified management when you need consistent security objects across all replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ReuseSystemDatabases Reuses existing system databases when recreating a contained availability group with the same name. Only applicable with contained availability groups (-IsContained). Use this when rebuilding an AG to avoid conflicts with previously created system database copies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DtcSupport Enables support for distributed transactions using Microsoft Distributed Transaction Coordinator (DTC). Required when applications use distributed transactions that span databases in the availability group. Note that DTC support is not available on Linux SQL Server instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ClusterType Defines the clustering technology used by the availability group (SQL Server 2017+). Options: Wsfc (Windows Server Failover Cluster), External (Linux Pacemaker), or None (no cluster). Use 'None' for read-scale scenarios without automatic failover, 'External' for Linux environments, or 'Wsfc' for traditional Windows clustering. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'AvailabilityGroups.Default.ClusterType' -Fallback 'Wsfc') | | Accepted Values | Wsfc,External,None | -AutomatedBackupPreference Controls which replicas are preferred for automated backup operations. Options: Primary, Secondary, SecondaryOnly, or None. Use 'Secondary' to offload backup I/O from the primary, or 'SecondaryOnly' to ensure backups never impact primary performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Secondary | | Accepted Values | None,Primary,Secondary,SecondaryOnly | -FailureConditionLevel Determines what conditions trigger automatic failover in the availability group. Default is Level 3 (OnCriticalServerErrors), which balances protection against false positives. Use Level 1 for fastest failover, Level 5 for maximum sensitivity, or adjust based on your tolerance for automatic failover events. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'AvailabilityGroups.Default.FailureConditionLevel' -Fallback 'OnCriticalServerErrors') | | Accepted Values | OnAnyQualifiedFailureCondition,OnCriticalServerErrors,OnModerateServerErrors,OnServerDown,OnServerUnresponsive | -HealthCheckTimeout Sets the timeout in milliseconds for health check responses from the sp_server_diagnostics procedure. Default is 30000 (30 seconds). Lower values provide faster failure detection but may cause false positives. Increase this value in environments with high I/O load or slower storage to prevent unnecessary failovers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 30000 | -Basic Creates a Basic Availability Group limited to one database and two replicas. Available in SQL Server 2016 Standard Edition and above as an alternative to Database Mirroring. Use this for simple two-node high availability scenarios when you don't need multiple databases or advanced features. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DatabaseHealthTrigger Enables database-level health monitoring that can trigger automatic failover. When enabled, database corruption or other critical database errors can initiate failover. Use this for additional protection when database integrity is more critical than minimizing failover events. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Passthru Returns the availability group object without creating it, allowing further customization. Use this when you need to modify advanced properties or add custom configurations before creating the AG. The returned object can be passed to other dbatools commands or have properties modified directly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Database Specifies which databases to add to the availability group during creation. Databases must be in Full recovery model and have recent transaction log backups. Use this to automatically include databases rather than adding them separately after AG creation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SharedPath Specifies the network path where database backups will be stored during secondary replica initialization. All SQL Server service accounts must have read/write access to this location. Required for manual seeding mode when adding databases - backups remain on the share after completion. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -UseLastBackup Uses existing backup files instead of creating new ones for database initialization. The most recent full backup and subsequent log backups will be restored to secondary replicas. Use this to save time and storage when recent backups are already available and accessible. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Removes existing databases on secondary replicas before restoring from backup. Use this when databases already exist on secondary servers but you want to refresh them. Requires SharedPath or UseLastBackup to be specified for the restore operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AvailabilityMode Controls whether transaction commits wait for secondary replica acknowledgment. SynchronousCommit ensures zero data loss but may impact performance over distance. Use AsynchronousCommit for disaster recovery replicas or when network latency affects performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | SynchronousCommit | | Accepted Values | AsynchronousCommit,SynchronousCommit | -FailoverMode Determines how failover occurs for the availability group. Automatic enables cluster-managed failover with synchronous replicas, Manual requires DBA intervention. Use External for Linux environments with Pacemaker cluster management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Automatic | | Accepted Values | Automatic,Manual,External | -BackupPriority Sets the priority for backup operations on this replica (0-100, default 50). Higher values make this replica more preferred for automated backup jobs. Use lower values on primary replicas to offload backup I/O, higher values on dedicated backup servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 50 | -ConnectionModeInPrimaryRole Controls what connections are allowed to the primary replica. AllowAllConnections (default) permits both read-write and read-intent connections. Use AllowReadWriteConnections to restrict read-only workloads to secondary replicas only. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | AllowAllConnections | | Accepted Values | AllowAllConnections,AllowReadWriteConnections | -ConnectionModeInSecondaryRole Controls what connections are allowed to secondary replicas. Default is AllowNoConnections to prevent accidental writes or outdated reads. Use AllowReadIntentConnectionsOnly for reporting workloads, or AllowAllConnections for maximum flexibility. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'AvailabilityGroups.Default.ConnectionModeInSecondaryRole' -Fallback 'AllowNoConnections') | | Accepted Values | AllowNoConnections,AllowReadIntentConnectionsOnly,AllowAllConnections,No,Read-intent only,Yes | -SeedingMode Determines how databases are initialized on secondary replicas. Manual (default) uses backup/restore through shared storage, Automatic uses direct network streaming. Use Automatic for SQL Server 2016+ to simplify setup when network bandwidth is sufficient and shared storage is limited. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Manual | | Accepted Values | Automatic,Manual | -Endpoint Specifies the name for the database mirroring endpoint used for availability group communication. If not specified, the command searches for existing endpoints or creates 'hadr_endpoint'. Use a custom name when you have specific endpoint naming standards or multiple AGs on the same instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EndpointUrl Specifies custom TCP URLs for availability group endpoints when automatic detection isn't suitable. Required format: 'TCP://hostname:port' for each instance (primary first, then secondaries). Use this in complex network environments with custom DNS, firewalls, or when instances use non-default ports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Certificate Specifies the certificate name for endpoint authentication instead of Windows authentication. Both endpoints must have matching certificates with corresponding public/private key pairs. Use this for cross-domain scenarios or when Windows authentication is not available between replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ConfigureXESession Automatically starts the AlwaysOn_health Extended Events session on all replicas. This session captures availability group events for monitoring and troubleshooting. Use this to match the behavior of the SQL Server Management Studio AG wizard and enable built-in diagnostics. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IPAddress Specifies one or more static IP addresses for the availability group listener. Each IP should correspond to a different subnet if replicas span multiple subnets. Use static IPs when DHCP is not available or when you need predictable listener addresses for applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SubnetMask Specifies the subnet mask for static IP listener configuration. Default is 255.255.255.0, which works for most standard network configurations. Adjust this to match your network's subnet configuration when using custom IP addressing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 255.255.255.0 | -Port Specifies the TCP port for the availability group listener. Default is 1433 (standard SQL Server port). Applications connect to this port to reach the current primary. Use a different port when 1433 is already in use or for security through obscurity. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1433 | -Dhcp Configures the availability group listener to use DHCP for IP address assignment. The cluster will request an IP address from DHCP servers on each replica's subnet. Use this when static IP management is not desired and DHCP reservations can provide consistent addressing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ClusterConnectionOption Specifies connection options for TDS 8.0 support in SQL Server 2025 and above. This allows the Windows Server Failover Cluster (WSFC) to connect to SQL Server instances using ODBC with TLS 1.3 encryption. The value is a string containing semicolon-delimited key-value pairs. Available keys: Encrypt: Controls connection encryption TrustServerCertificate: Whether to trust the server certificate HostNameInCertificate: Expected hostname in the certificate ServerCertificate: Path to server certificate This setting is persisted by WSFC in the registry and used continuously for cluster-to-instance communication. Note: PowerShell does not validate these values - invalid combinations will be rejected by SMO or the ODBC driver. Example: \"Encrypt=Strict;TrustServerCertificate=False\" For detailed documentation, see: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-availability-group-transact-sql | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MasterKeySecurePassword Password for creating the database master key on secondary replicas when adding TDE-encrypted databases. When databases protected by Transparent Data Encryption (TDE) are added to the availability group, the TDE certificate in the primary's master database must be copied to each secondary. Providing this parameter alongside SharedPath enables automatic certificate copying. If a secondary replica is missing a master key, this password is used to create one. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityGroup (when -Passthru is not specified) Returns the newly created SQL Server availability group object after full setup is complete. The returned object includes all configured replicas, databases, and listeners. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the availability group PrimaryReplica: The server name of the primary replica LocalReplicaRole: The role of the local replica (Primary or Secondary) AvailabilityReplicas: Collection of replica objects in the availability group AvailabilityDatabases: Collection of databases in the availability group AvailabilityGroupListeners: Collection of listeners configured for the AG Additional properties available from the SMO AvailabilityGroup object include: AutomatedBackupPreference: Which replicas are preferred for backups (Primary, Secondary, SecondaryOnly, None) FailureConditionLevel: The level that triggers automatic failover HealthCheckTimeout: Timeout in milliseconds for health checks (default 30000) BasicAvailabilityGroup: Boolean indicating if this is a Basic AG DatabaseHealthTrigger: Boolean indicating if database health triggers failover DtcSupportEnabled: Boolean indicating if DTC is enabled (SQL Server 2016+) ClusterType: The cluster type (Wsfc, External, or None) IsContained: Boolean indicating if this is a contained AG (SQL Server 2022+) ClusterConnectionOptions: Connection options for cluster communication (SQL Server 2025+) DateCreated: DateTime when the availability group was created Passthru behavior (when -Passthru is specified): Returns the AvailabilityGroup object immediately after configuration but before creation, with these properties displayed: LocalReplicaRole: The role of the local replica AvailabilityGroup: The name of the AG PrimaryReplica: The primary replica server name AutomatedBackupPreference: Backup preference setting AvailabilityReplicas: Configured replicas AvailabilityDatabases: Databases to be added AvailabilityGroupListeners: Listeners to be created All properties from the base SMO AvailabilityGroup object are accessible using Select-Object . &nbsp;"
  },
  {
    "name": "New-DbaAzAccessToken",
    "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",
    "category": "Utilities",
    "tags": [
      "connect",
      "connection",
      "azure"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaAzAccessToken",
    "popularityRank": 228,
    "synopsis": "Generates OAuth2 access tokens for Azure SQL Database and other Azure services authentication.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaAzAccessToken View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates OAuth2 access tokens for Azure SQL Database and other Azure services authentication. 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. Want to know more about Access Tokens? This page explains it well: https://dzone.com/articles/using-managed-identity-to-securely-access-azure-re Syntax New-DbaAzAccessToken [-Type] [[-Subtype] ] [[-Config] ] [[-Credential] ] [[-Tenant] ] [[-Thumbprint] ] [[-Store] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a plain-text token for Managed Identities for SQL Azure Db PS C:\\> New-DbaAzAccessToken -Type ManagedIdentity Example 2: Generates a token then uses it to connect to Azure SQL DB then connects to an Azure SQL Db PS C:\\> $token = New-DbaAzAccessToken -Type ManagedIdentity -Subtype AzureSqlDb PS C:\\> $server = Connect-DbaInstance -SqlInstance myserver.database.windows.net -Database mydb -AccessToken $token -DisableException Example 3: Generates a token then uses it to connect to Azure SQL DB then connects to an Azure SQL Db PS C:\\> $token = New-DbaAzAccessToken -Type ServicePrincipal -Tenant whatup.onmicrosoft.com -Credential ee590f55-9b2b-55d4-8bca-38ab123db670 PS C:\\> $server = Connect-DbaInstance -SqlInstance myserver.database.windows.net -Database mydb -AccessToken $token -DisableException PS C:\\> Invoke-DbaQuery -SqlInstance $server -Query \"select 1 as test\" Generates a token then uses it to connect to Azure SQL DB then connects to an Azure SQL Db. Once the connection is made, it is used to perform a test query. Required Parameters -Type Specifies the authentication method for generating the access token. ManagedIdentity uses Azure VM identity for password-free authentication, ServicePrincipal uses application credentials for automated scripts, and RenewableServicePrincipal creates tokens that automatically refresh for long-running connections. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | | Accepted Values | ManagedIdentity,ServicePrincipal,RenewableServicePrincipal | Optional Parameters -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 their respective Azure services. Defaults to AzureSqlDb for database connections. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | AzureSqlDb | | Accepted Values | 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 custom resource URLs or API versions not covered by standard subtypes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential When using the ServicePrincipal type, a Credential is required. The username is the App ID and Password is the App Password https://docs.microsoft.com/en-us/azure/active-directory/user-help/multi-factor-authentication-end-user-app-passwords | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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's tenant ID (GUID format) or domain name like 'contoso.onmicrosoft.com'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'azure.tenantid') | -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 the value stored in dbatools configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'azure.certificate.thumbprint') | -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 certificate-based Managed Service Identity authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'azure.certificate.store') | | Accepted Values | CurrentUser,LocalMachine | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String (when -Type is ManagedIdentity or ServicePrincipal) Returns a plain-text OAuth2 access token that can be used with Connect-DbaInstance and other Azure-aware dbatools commands. PSObjectIRenewableToken (when -Type is RenewableServicePrincipal) Returns a custom IRenewableToken object that automatically refreshes tokens for long-running connections. This object implements Microsoft.SqlServer.Management.Common.IRenewableToken. Properties: ClientSecret: The application secret/password used for token renewal Resource: The Azure resource URI (e.g., \"https://database.windows.net/\") Tenant: The Azure AD tenant ID or domain name UserID: The service principal application ID TokenExpiry: DateTime when the token expires; automatically updated when GetAccessToken() is called &nbsp;"
  },
  {
    "name": "New-DbaClientAlias",
    "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.",
    "category": "Utilities",
    "tags": [
      "sqlclient",
      "alias"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaClientAlias",
    "popularityRank": 368,
    "synopsis": "Creates SQL Server client aliases in the Windows registry for simplified connection management",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "New-DbaClientAlias View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates SQL Server client aliases in the Windows registry for simplified connection management 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. Syntax New-DbaClientAlias [[-ComputerName] ] [[-Credential] ] [-ServerName] [-Alias] [[-Protocol] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new TCP alias on the local workstation called sp, which points sqlcluster\\sharepoint PS C:\\> New-DbaClientAlias -ServerName sqlcluster\\sharepoint -Alias sp Example 2: Creates a new TCP alias on the local workstation called spinstance, which points to sqlcluster, port 14443 PS C:\\> New-DbaClientAlias -ServerName 'sqlcluster,14443' -Alias spinstance Example 3: Creates a new NamedPipes alias on the local workstation called sp, which points sqlcluster\\sharepoint PS C:\\> New-DbaClientAlias -ServerName sqlcluster\\sharepoint -Alias sp -Protocol NamedPipes Required Parameters -ServerName Specifies the actual SQL Server instance that the alias will point to. Can include instance names (server\\instance) or custom ports (server,1433) for non-standard configurations. This is the real connection target that applications will reach when using the alias name. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Alias Defines the short, friendly name that applications will use to connect to SQL Server. Choose a simple name that's easier to remember and type than the full server\\instance name. This alias name will appear in connection strings and SQL management tools. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -ComputerName Specifies the target computer(s) where the client alias will be created in the registry. Use this when configuring aliases on remote workstations or when managing multiple computers centrally. Defaults to the local computer if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to remote computers using alternative credentials | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Protocol Sets the network protocol for the connection, either TCPIP or NamedPipes. TCPIP is recommended for most scenarios and works across network boundaries. NamedPipes may be preferred for local connections or specific security requirements. Defaults to TCPIP. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | TCPIP | | Accepted Values | TCPIP,NamedPipes | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.RegisteredServer Returns 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. Default display properties: ComputerName: The computer where the alias was created AliasName: The alias name that was created ServerName: The SQL Server instance the alias points to Protocol: The network protocol used (TCPIP or NamedPipes) InstanceName: The instance name portion if specified PipeName: The pipe name for NamedPipes protocol aliases Port: The TCP port number if specified in ServerName All properties from the base SMO RegisteredServer object are accessible using Select-Object *. &nbsp;"
  },
  {
    "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.",
    "category": "Utilities",
    "tags": [
      "computermanagement",
      "cim"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaCmConnection",
    "popularityRank": 558,
    "synopsis": "Creates and configures connection objects for remote computer management using CIM/WMI protocols.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "New-DbaCmConnection View Source Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates and configures connection objects for remote computer management using CIM/WMI protocols. Description Creates connection objects that optimize remote computer management for SQL Server environments using CIM and WMI protocols. These objects cache successful authentication methods and connection protocols, reducing authentication errors and improving performance when connecting to multiple SQL Server instances across different servers. The function pre-configures connection settings including credentials, preferred protocols (CIM over WinRM or DCOM), and failover behavior. This eliminates the need to repeatedly authenticate and negotiate protocols when running dbatools commands against remote SQL Server instances. New-DbaCmConnection creates a new connection object and overwrites any existing cached connection for the specified computer. All connection information beyond the computer name gets replaced with the new settings you specify. Unless connection caching has been disabled globally, all connections are automatically stored in the connection cache for reuse. The returned object is primarily informational, though it can be used to bypass the cache if needed. Note: This function is typically optional since dbatools commands like Get-DbaCmObject automatically create default connections when first connecting to a computer. Use this function when you need to pre-configure specific authentication or protocol settings before running other dbatools commands. Syntax New-DbaCmConnection [-ComputerName ] [-Credential ] [-OverrideExplicitCredential] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-WindowsCredentialsAreBad] [-CimWinRMOptions ] [-CimDCOMOptions ] [-EnableException] [-WhatIf] [-Confirm] [ ] New-DbaCmConnection [-ComputerName ] [-UseWindowsCredentials] [-OverrideExplicitCredential] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-CimWinRMOptions ] [-CimDCOMOptions ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Returns a new configuration object for connecting to the computer sql2014 PS C:\\> New-DbaCmConnection -ComputerName sql2014 -UseWindowsCredentials -OverrideExplicitCredential -DisabledConnectionTypes CimRM Returns a new configuration object for connecting to the computer sql2014. The current user credentials are set as valid The connection is configured to ignore explicit credentials (so all connections use the windows credentials) The connections will not try using CIM over WinRM Unless caching is globally disabled, this is automatically stored in the connection cache and will be applied automatically. In that (the default) case, the output is for information purposes only and need not be used. Example 2: Gathers a list of computers from a text file, then creates and registers connections for each of them... PS C:\\> Get-Content computers.txt | New-DbaCmConnection -Credential $cred -CimWinRMOptions $options -DisableBadCredentialCache -OverrideExplicitCredential Gathers a list of computers from a text file, then creates and registers connections for each of them, setting them to ... use the credentials stored in $cred use the options stored in $options when connecting using CIM over WinRM not store credentials that are known to not work to ignore explicitly specified credentials Essentially, this configures all connections to those computers to prefer failure with the specified credentials over using alternative credentials. Optional Parameters -ComputerName Specifies the target computer name or IP address where SQL Server instances are running. Use this to pre-configure connection settings before running other dbatools commands against remote SQL Server hosts. Accepts pipeline input for bulk configuration of multiple servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential The credential to register. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -UseWindowsCredentials Confirms that the current Windows user credentials are valid for connecting to the target computer. Use this when your current domain account has administrative rights on the SQL Server host. Pre-validates these credentials to avoid authentication delays during subsequent dbatools operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -OverrideExplicitCredential Forces the connection to use cached working credentials instead of any explicitly provided credentials. Use this when you want to ensure consistent authentication across multiple dbatools commands. Prevents authentication failures when mixed credentials are accidentally specified in scripts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisabledConnectionTypes Specifies which connection protocols to disable when connecting to the remote computer. Use this to force specific connection methods when certain protocols are blocked by network policies. Common values include 'CimRM' to disable CIM over WinRM or 'CimDCOM' to disable DCOM connections. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | None | -DisableBadCredentialCache Prevents failed credentials from being stored in the credential cache. Use this in environments where credentials change frequently or when testing different authentication methods. Helps avoid repeated authentication attempts with known bad credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisableCimPersistence Forces creation of new CIM sessions for each connection instead of reusing existing sessions. Use this when troubleshooting connection issues or when working with servers that have session limits. May impact performance but ensures fresh connections for each dbatools operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisableCredentialAutoRegister Prevents successful credentials from being automatically stored in the connection cache. Use this for one-time operations where you don't want credentials persisted for future use. Useful in high-security environments where credential caching is not permitted. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableCredentialFailover Automatically switches to cached working credentials when the initially provided credentials fail. Use this to ensure dbatools operations continue even if incorrect credentials are accidentally specified. Prevents script interruptions due to authentication failures when multiple credential sets are available. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WindowsCredentialsAreBad Explicitly marks the current Windows user credentials as invalid for this computer connection. Use this when your domain account lacks privileges on the target SQL Server host. Forces the use of alternative credentials and prevents authentication attempts with insufficient privileges. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CimWinRMOptions Configures advanced WinRM connection settings for CIM sessions to the target computer. Use this to specify custom ports, authentication methods, or SSL settings required by your network configuration. Create the options object using New-CimSessionOption with specific timeout, encryption, or proxy settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CimDCOMOptions Configures advanced DCOM connection settings for legacy CIM sessions to the target computer. Use this when connecting to older Windows servers or when WinRM is not available. Create the options object using New-CimSessionOption with DCOM-specific authentication and timeout settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Dataplat.Dbatools.Connection.ManagementConnection Returns 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. Unless 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 returned object itself is primarily informational but can be used to verify connection settings or to bypass the cache if needed. Key properties include: ComputerName: The target computer name for the connection Credentials: The PSCredential object for authentication, or null if using Windows credentials UseWindowsCredentials: Boolean indicating if current Windows credentials are used OverrideExplicitCredential: Boolean forcing use of cached credentials instead of explicit ones DisabledConnectionTypes: ManagementConnectionType flags specifying which protocols to disable (CimRM, CimDCOM, etc.) DisableBadCredentialCache: Boolean preventing storage of failed credentials DisableCimPersistence: Boolean forcing new CIM sessions instead of reusing existing ones DisableCredentialAutoRegister: Boolean preventing auto-storage of successful credentials WindowsCredentialsAreBad: Boolean marking Windows credentials as invalid for this connection CimWinRMOptions: WSManSessionOptions for configuring CIM over WinRM protocol settings CimDCOMOptions: DComSessionOptions for configuring DCOM protocol settings &nbsp;"
  },
  {
    "name": "New-DbaComputerCertificate",
    "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 2048 bits and a friendly name of \"SQL Server\" 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's webserver SSL template on the client machine and pushed to the remote machine.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaComputerCertificate",
    "popularityRank": 140,
    "synopsis": "Creates a new computer certificate useful for Forcing Encryption",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "New-DbaComputerCertificate View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a new computer certificate useful for Forcing Encryption Description Creates a new computer certificate - self-signed or signed by an Active Directory CA, using the Web Server certificate. By default, a key with a length of 2048 bits and a friendly name of \"SQL Server\" is generated. This command was originally intended to help automate the process so that SSL certificates can be available for enforcing encryption on connections. It 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 ;) References: https://www.itprotoday.com/sql-server/7-steps-ssl-encryption https://azurebi.jppp.org/2016/01/23/using-lets-encrypt-certificates-for-secure-sql-server-connections/ https://blogs.msdn.microsoft.com/sqlserverfaq/2016/09/26/creating-and-registering-ssl-certificates/ The certificate is generated using AD's webserver SSL template on the client machine and pushed to the remote machine. Syntax New-DbaComputerCertificate [[-ComputerName] ] [[-Credential] ] [[-CaServer] ] [[-CaName] ] [[-ClusterInstanceName] ] [[-SecurePassword] ] [[-FriendlyName] ] [[-CertificateTemplate] ] [[-KeyLength] ] [[-Store] ] [[-Folder] ] [[-Flag] ] [[-Dns] ] [-SelfSigned] [-DocumentEncryptionCert] [-EnableException] [[-HashAlgorithm] ] [[-MonthsValid] ] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a computer certificate signed by the local domain CA for the local machine with the keylength of 2048... PS C:\\> New-DbaComputerCertificate Creates a computer certificate signed by the local domain CA for the local machine with the keylength of 2048 and SHA-256 hashing. Example 2: Creates a computer certificate signed by the local domain CA _on the local machine_ for server1 with the... PS C:\\> New-DbaComputerCertificate -ComputerName Server1 Creates a computer certificate signed by the local domain CA _on the local machine_ for server1 with the keylength of 2048 and SHA-256 hashing. The certificate is then copied to the new machine over WinRM and imported. Example 3: Creates a computer certificate for sqlcluster, signed by the local domain CA, with the keylength of 4096 PS C:\\> New-DbaComputerCertificate -ComputerName sqla, sqlb -ClusterInstanceName sqlcluster -KeyLength 4096 Creates a computer certificate for sqlcluster, signed by the local domain CA, with the keylength of 4096. The certificate is then copied to sqla _and_ sqlb over WinRM and imported. Example 4: Shows what would happen if the command were run PS C:\\> New-DbaComputerCertificate -ComputerName Server1 -WhatIf Example 5: Creates a self-signed certificate PS C:\\> New-DbaComputerCertificate -SelfSigned Example 6: Creates a self-signed certificate using the SHA256 hashing algorithm that does not expire for 5 years PS C:\\> New-DbaComputerCertificate -SelfSigned -HashAlgorithm Sha256 -MonthsValid 60 Example 7: Creates a self-signed certificate suitable for use as a Column Master Key for Always Encrypted PS C:\\> New-DbaComputerCertificate -SelfSigned -DocumentEncryptionCert Creates a self-signed certificate suitable for use as a Column Master Key for Always Encrypted. The certificate includes the Document Encryption and IKE Intermediate Extended Key Usage OIDs required by SQL Server Always Encrypted. Optional Parameters -ComputerName Specifies the target computer or computers where the certificate will be created and installed. Defaults to localhost. For SQL Server clusters, specify each cluster node here and use ClusterInstanceName for the cluster's virtual name. The certificate is created locally and then copied to remote machines via WinRM if needed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to $ComputerName using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CaServer Specifies the Certificate Authority server that will sign the certificate request. When omitted, the function automatically discovers the CA server from Active Directory. Required for domain-signed certificates when automatic discovery fails. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CaName Specifies the Certificate Authority name on the CA server. When omitted, the function automatically discovers the CA name from Active Directory. Must match the exact CA name as registered in the domain's PKI infrastructure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ClusterInstanceName Specifies the virtual cluster name when creating certificates for SQL Server failover clusters. The certificate subject and SAN will use this cluster name instead of individual node names. Use ComputerName to specify each physical cluster node where the certificate will be installed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecurePassword Specifies the password used to protect the private key during certificate export and import operations. Required when installing certificates on remote machines to secure the private key during transport. The same password is used for both export from the local machine and import on remote machines. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -FriendlyName Specifies the friendly name displayed in the certificate store to help identify the certificate. Defaults to \"SQL Server\" making it easy to locate certificates intended for SQL Server encryption. Choose descriptive names like \"SQL Prod Cluster\" or \"SQL Dev Server\" for better organization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | SQL Server | -CertificateTemplate Specifies the Active Directory Certificate Template used for certificate generation. Defaults to \"WebServer\" which provides the necessary server authentication capabilities for SQL Server encryption. The template must exist in your domain's PKI and allow auto-enrollment for your account. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | WebServer | -KeyLength Specifies the RSA key size in bits for the certificate's private key. Defaults to 2048 bits which meets current industry security standards for production environments. 4096 bits can be used for high-security environments, though it may slightly impact performance during SSL handshakes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 2048 | -Store Specifies the certificate store location where the certificate will be installed. Defaults to \"LocalMachine\" which makes certificates available to services like SQL Server. Use \"CurrentUser\" only for user-specific certificates that don't need service access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | LocalMachine | -Folder Specifies the certificate store folder where the certificate will be placed. Defaults to \"My\" (Personal certificates) which is where SQL Server looks for server certificates. Use \"TrustedPeople\" or other folders only for specific certificate trust scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | My | -Flag Specifies how the certificate's private key should be handled during import operations. Defaults to \"Exportable, PersistKeySet\" allowing the key to be backed up and persisted on disk. Use \"NonExportable\" for high-security environments where private keys should never leave the machine. When copying certificates to remote computers, the temporary source certificate remains exportable so the destination import can honor the requested flags. \"UserProtected\" requires interactive confirmation and only works on localhost installations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @(\"Exportable\", \"PersistKeySet\") | | Accepted Values | EphemeralKeySet,Exportable,PersistKeySet,UserProtected,NonExportable | -Dns Specifies additional DNS names to include in the certificate's Subject Alternative Name (SAN) extension. By default, includes the computer name and FQDN, or cluster name and cluster FQDN for clusters. Add extra DNS names that clients will use to connect, such as aliases or load balancer names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SelfSigned Creates a self-signed certificate instead of requesting one from a Certificate Authority. Useful for development environments or when no domain CA is available. Self-signed certificates will generate trust warnings unless manually added to client trust stores. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DocumentEncryptionCert Creates a certificate suitable for use as a Column Master Key for Always Encrypted. When specified, the certificate uses KeyEncipherment key usage and includes the Document Encryption (1.3.6.1.4.1.311.10.3.11) and IKE Intermediate (1.3.6.1.5.5.8.2.2) Extended Key Usage OIDs required by Always Encrypted, instead of the default Server Authentication OID (1.3.6.1.5.5.7.3.1). For CA-signed certificates, specify -CertificateTemplate with a template configured for Always Encrypted column master keys. The default WebServer template is intended for TLS server certificates and is not suitable for this switch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -HashAlgorithm Specifies the cryptographic hash algorithm used for certificate signing. Defaults to \"Sha256\" which meets current industry security standards for production environments. SHA-384 and SHA-512 provide even stronger security for high-security environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Sha256 | | Accepted Values | Sha256,sha384,sha512 | -MonthsValid Specifies how many months the self-signed certificate remains valid from the creation date. Defaults to 12 months; use longer periods like 60 months (5 years) to reduce certificate renewal frequency. Only applies to self-signed certificates; CA-signed certificates use the CA's validity period. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 12 | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.Security.Cryptography.X509Certificates.X509Certificate2 Returns one or more X.509 certificate objects for the computers where certificates were successfully created and installed. For local host (-ComputerName localhost or not specified): Returns the certificate object created or imported on the local machine after certificate generation/signing completes. For remote hosts: Returns the certificate object after successful import on the remote computer via WinRM. When creating certificates for SQL Server failover clusters (-ClusterInstanceName specified), a single certificate is created and imported on each cluster node specified in -ComputerName. Default display properties (via Select-DefaultView): FriendlyName: The friendly name assigned to the certificate (defaults to \"SQL Server\") DnsNameList: Collection of DNS names in the certificate's Subject Alternative Name (SAN) extension Thumbprint: The SHA-1 hash fingerprint of the certificate, used for certificate identification NotBefore: DateTime when the certificate becomes valid NotAfter: DateTime when the certificate expires Subject: The certificate subject Distinguished Name (DN) containing the CN (Common Name) Issuer: The issuer Distinguished Name (DN) for the certificate (either self-signed or CA name) *Additional properties available via Select-Object :** SerialNumber: The certificate's serial number Version: The X.509 version number (typically 3) SignatureAlgorithm: The signing algorithm used (e.g., sha256RSA, sha1RSA) PublicKey: The certificate's public key information PrivateKey: The private key associated with this certificate (if present and accessible) Extensions: Collection of X.509 extensions (e.g., Subject Alternative Name, Enhanced Key Usage) &nbsp;"
  },
  {
    "name": "New-DbaComputerCertificateSigningRequest",
    "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's 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's 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's 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's encryption stack.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaComputerCertificateSigningRequest",
    "popularityRank": 310,
    "synopsis": "Generates certificate signing requests for SQL Server instances to enable SSL/TLS encryption and connection security.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "New-DbaComputerCertificateSigningRequest View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates certificate signing requests for SQL Server instances to enable SSL/TLS encryption and connection security. 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's encryption requirements. The function generates both the certificate configuration file (.inf) and the signing request file (.csr) with proper Subject Alternative Names (SAN) to support SQL Server's certificate validation. This is essential when implementing Force Encryption, configuring encrypted connections, or meeting compliance requirements that mandate encrypted database communications. Supports both standalone SQL Server instances and cluster configurations, automatically resolving FQDNs and configuring appropriate DNS entries. The generated certificates work with SQL Server's encryption features including encrypted client connections, mirroring, and backup encryption scenarios. By 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's encryption stack. Syntax New-DbaComputerCertificateSigningRequest [[-ComputerName] ] [[-Credential] ] [[-ClusterInstanceName] ] [[-Path] ] [[-FriendlyName] ] [[-KeyLength] ] [[-Dns] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a computer certificate signing request for the local machine with the keylength of 1024 PS C:\\> New-DbaComputerCertificateSigningRequest Example 2: Creates a computer certificate signing request for server1 with the keylength of 1024 PS C:\\> New-DbaComputerCertificateSigningRequest -ComputerName Server1 Example 3: Creates a computer certificate signing request for sqlcluster with the keylength of 4096 PS C:\\> New-DbaComputerCertificateSigningRequest -ComputerName sqla, sqlb -ClusterInstanceName sqlcluster -KeyLength 4096 Example 4: Shows what would happen if the command were run PS C:\\> New-DbaComputerCertificateSigningRequest -ComputerName Server1 -WhatIf Optional Parameters -ComputerName The target computer name hosting the SQL Server instance where the certificate will be installed. Accepts multiple computer names for batch processing. For standalone servers, this creates certificates for the specified machine. For clusters, specify each cluster node here and use ClusterInstanceName for the virtual cluster name. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to $ComputerName using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ClusterInstanceName Specifies the virtual cluster name for SQL Server failover cluster instances. This becomes the certificate's Common Name (CN) and primary DNS entry. Required when generating certificates for clustered SQL Server instances to ensure proper SSL validation during failovers between cluster nodes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Directory where the certificate configuration (.inf) and signing request (.csr) files will be created. Defaults to the dbatools export path. Each computer gets its own subdirectory containing the certificate files needed for submission to your Certificate Authority. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -FriendlyName Sets a descriptive name for the certificate that appears in the Windows Certificate Store. Defaults to \"SQL Server\". This name helps administrators identify the certificate's purpose when managing multiple certificates on the same server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Higher key lengths provide stronger encryption but may impact SQL Server connection performance on older hardware. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1024 | -Dns Additional DNS names to include in the certificate's Subject Alternative Name (SAN) field. By default includes both short and FQDN names. Add extra DNS entries here if clients connect using aliases, load balancer names, or other DNS records that point to your SQL Server instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.IO.FileInfo Returns file information objects for each certificate file created. Two files are returned per computer: request.inf - Certificate configuration file containing certificate settings and Subject Alternative Names .csr - Certificate signing request file that is submitted to the Certificate Authority Properties: Name: The file name (request.inf or .csr) FullName: The complete file path DirectoryName: The directory containing the file Length: The file size in bytes LastWriteTime: DateTime when the file was created CreationTime: DateTime of file creation Extension: The file extension (.inf or .csr) All standard System.IO.FileInfo properties are available for use with Select-Object. &nbsp;"
  },
  {
    "name": "New-DbaConnectionString",
    "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",
    "category": "Utilities",
    "tags": [
      "connection",
      "connect",
      "connectionstring"
    ],
    "verb": "New",
    "popular": true,
    "url": "/New-DbaConnectionString",
    "popularityRank": 25,
    "synopsis": "Creates connection strings for SQL Server instances using PowerShell-friendly parameters",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaConnectionString View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates connection strings for SQL Server instances using PowerShell-friendly parameters 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. This 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. Particularly 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. See https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx and https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx and https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx Syntax New-DbaConnectionString [-SqlInstance] [[-Credential] ] [[-AccessToken] ] [[-ApplicationIntent] ] [[-BatchSeparator] ] [[-ClientName] ] [[-ConnectTimeout] ] [[-Database] ] [-EncryptConnection] [[-FailoverPartner] ] [-IsActiveDirectoryUniversalAuth] [[-LockTimeout] ] [[-MaxPoolSize] ] [[-MinPoolSize] ] [-MultipleActiveResultSets] [-MultiSubnetFailover] [[-NetworkProtocol] ] [-NonPooledConnection] [[-PacketSize] ] [[-PooledConnectionLifetime] ] [[-SqlExecutionModes] ] [[-StatementTimeout] ] [-TrustServerCertificate] [[-WorkstationId] ] [-Legacy] [[-AppendConnectionString] ] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a connection string that connects using Windows Authentication PS C:\\> New-DbaConnectionString -SqlInstance sql2014 Example 2: Builds a connected SMO object using Connect-DbaInstance then extracts and displays the connection string PS C:\\> Connect-DbaInstance -SqlInstance sql2016 | New-DbaConnectionString Example 3: Creates a connection string that connects using alternative Windows credentials PS C:\\> $wincred = Get-Credential ad\\sqladmin PS C:\\> New-DbaConnectionString -SqlInstance sql2014 -Credential $wincred Example 4: Login to sql2014 as SQL login sqladmin PS C:\\> $sqlcred = Get-Credential sqladmin PS C:\\> $server = New-DbaConnectionString -SqlInstance sql2014 -Credential $sqlcred Example 5: Creates a connection string for an Azure Active Directory login to Azure SQL db PS C:\\> $connstring = New-DbaConnectionString -SqlInstance mydb.database.windows.net -SqlCredential me@myad.onmicrosoft.com -Database db Creates a connection string for an Azure Active Directory login to Azure SQL db. Output looks like this: Data Source=TCP:mydb.database.windows.net,1433;Initial Catalog=db;User ID=me@myad.onmicrosoft.com;Password=fakepass;MultipleActiveResultSets=False;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False;Application Name=\"dbatools PowerShell module - dbatools.io\";Authentication=\"Active Directory Password\" Example 6: Creates a connection string that connects using Windows Authentication and uses the client name &quot;mah... PS C:\\> $server = New-DbaConnectionString -SqlInstance sql2014 -ClientName \"mah connection\" Creates 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 connection\". Example 7: Creates a connection string that connects to sql2014 using Windows Authentication, then it sets the packet... PS C:\\> $server = New-DbaConnectionString -SqlInstance sql2014 -AppendConnectionString \"Packet Size=4096;AttachDbFilename=C:\\MyFolder\\MyDataFile.mdf;User Instance=true;\" Creates 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. Example 8: Creates a connection string with Windows Authentication that uses TCPIP and has MultiSubnetFailover enabled PS C:\\> $server = New-DbaConnectionString -SqlInstance sql2014 -NetworkProtocol TcpIp -MultiSubnetFailover Example 9: Creates a connection string with ReadOnly ApplicationIntent PS C:\\> $connstring = New-DbaConnectionString sql2016 -ApplicationIntent ReadOnly Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | ServerInstance,SqlServer,Server,DataSource | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For 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 connection instead of a SQL login, ensure it contains a backslash. | Property | Value | | --- | --- | | Alias | SqlCredential | | Required | False | | Pipeline | false | | Default Value | | -AccessToken Specifies that Azure Active Directory access token authentication should be used. When specified, the connection string is configured for token-based authentication. Use this when connecting to Azure SQL with an access token you've obtained separately from Azure AD authentication flows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use ReadOnly to connect to secondary replicas for reporting queries, which helps offload read traffic from the primary replica. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | ReadOnly,ReadWrite | -BatchSeparator Sets the batch separator for SQL commands. Defaults to \"GO\" if not specified. Change this when working with tools or scripts that use different batch separators, or when \"GO\" conflicts with your SQL code. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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\". Use a descriptive name when you need to identify specific scripts or applications in SQL Server logs and monitoring for troubleshooting or performance analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Increase 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Database Specifies the initial database to connect to when the connection is established. Sets the Initial Catalog property in the connection string. Required for Azure SQL Database connections, and useful for ensuring connections start in the correct database context for your operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EncryptConnection Forces SSL/TLS encryption for the connection to protect data in transit. Automatically enabled for Azure SQL Database connections. Enable this for connections over untrusted networks or when your security policy requires encrypted database connections. Requires proper SSL certificates when TrustServerCertificate is false. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'sql.connection.encrypt') | -FailoverPartner Specifies the failover partner server name for database mirroring configurations. Limited to 128 characters or less. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IsActiveDirectoryUniversalAuth Enables Azure Active Directory Universal Authentication with Multi-Factor Authentication (MFA) support for Azure SQL connections. Use this when connecting to Azure SQL Database or Managed Instance with accounts that require MFA or when using Azure AD guest accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. This parameter is included for legacy compatibility but has no effect on the generated connection string. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaxPoolSize Sets the maximum number of connections allowed in the connection pool for this connection string. Defaults to 100 if not specified. Increase this value for applications with high concurrency requirements, or decrease it to limit resource usage on the SQL Server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MinPoolSize Sets the minimum number of connections maintained in the connection pool for this connection string. Defaults to 0 if not specified. Set this to a higher value when you want to maintain warm connections for faster subsequent connection requests, especially for frequently accessed databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MultipleActiveResultSets Enables Multiple Active Result Sets (MARS) allowing multiple commands to be executed simultaneously on a single connection. Enable 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MultiSubnetFailover Enables faster failover detection when connecting to Always On availability groups across different subnets. Use this when your availability group replicas are distributed across multiple subnets to reduce connection timeout during failover scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NetworkProtocol Forces a specific network protocol for the connection. Valid values include TcpIp, NamedPipes, SharedMemory, and others. Use TcpIp for remote connections or NamedPipes for local connections when you need to override default protocol selection or troubleshoot connectivity issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | TcpIp,NamedPipes,Multiprotocol,AppleTalk,BanyanVines,Via,SharedMemory,NWLinkIpxSpx | -NonPooledConnection Disables connection pooling for this connection, creating a dedicated connection that isn't shared. Use this for long-running operations, debugging scenarios, or when you need to ensure complete isolation of the database connection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -PacketSize Sets the network packet size in bytes for communication with SQL Server. Must be between 512 and 32767 bytes. Increase this value for bulk operations or large result sets to improve performance, but ensure the server's network packet size setting can accommodate the specified value. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -PooledConnectionLifetime Sets the maximum lifetime in seconds for pooled connections. Connections older than this value are destroyed when returned to the pool. Use this in clustered environments to force load balancing across cluster nodes or to ensure connections don't remain open indefinitely. Zero means no lifetime limit. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. This parameter is included for legacy compatibility but has no effect on the generated connection string. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | CaptureSql,ExecuteAndCaptureSql,ExecuteSql | -StatementTimeout Sets the number of seconds before SQL commands timeout. Not supported in connection strings - this parameter generates a warning. This parameter is included for legacy compatibility but has no effect on the generated connection string. Use the CommandTimeout property on SqlCommand objects instead. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -TrustServerCertificate Bypasses SSL certificate validation when EncryptConnection is enabled. The connection will be encrypted but the server certificate won't be verified. Use this for development environments or when connecting to servers with self-signed certificates, but avoid in production due to security risks. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'sql.connection.trustcert') | -WorkstationId Sets the workstation identifier that appears in SQL Server system views and logs. Defaults to the local computer name if not specified. Use this to identify connections from specific machines or applications when monitoring SQL Server activity or troubleshooting connection issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Legacy Forces the use of the older System.Data.SqlClient provider instead of the modern Microsoft.Data.SqlClient provider. Use this only when connecting to applications or tools that specifically require the legacy provider for compatibility reasons. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AppendConnectionString Adds custom connection string parameters to the generated connection string. Authentication parameters cannot be passed this way. Use this when you need to add specialized connection parameters like AttachDbFilename, User Instance, or custom driver-specific settings that aren't available through other parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.String Returns 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. The output format varies by usage path: When an SMO Server object is passed via pipeline, the existing connection string is extracted and optionally modified with new parameters When SQL instance names are specified, new connection strings are built with the specified parameters When using the legacy code path, connection strings are constructed using SMO ServerConnection objects Connection string examples: Windows Authentication: \"Data Source=sql2016;Connection Timeout=15;Integrated Security=true;Application Name=\"custom connection\"\" SQL Authentication: \"Data Source=sql2016;User ID=sqladmin;Password=P@ssw0rd;Connection Timeout=15;Application Name=\"custom connection\"\" 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 Timeout=30;Encrypt=Mandatory;TrustServerCertificate=False;Authentication=Active Directory Password;Application Name=\"custom connection\"\" The 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 commands that accept connection strings. &nbsp;"
  },
  {
    "name": "New-DbaConnectionStringBuilder",
    "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.",
    "category": "Utilities",
    "tags": [
      "sqlbuild",
      "connectionstring",
      "connection"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaConnectionStringBuilder",
    "popularityRank": 367,
    "synopsis": "Creates a SqlConnectionStringBuilder object for constructing properly formatted SQL Server connection strings",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaConnectionStringBuilder View Source zippy1981 , Chrissy LeMaire (@cl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a SqlConnectionStringBuilder object for constructing properly formatted SQL Server connection strings 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. Syntax New-DbaConnectionStringBuilder [[-ConnectionString] ] [[-ApplicationName] ] [[-DataSource] ] [[-SqlCredential] ] [[-InitialCatalog] ] [-IntegratedSecurity] [[-UserName] ] [[-Password] ] [-MultipleActiveResultSets] [[-ColumnEncryptionSetting] ] [-Legacy] [-NonPooledConnection] [[-WorkstationID] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns an empty ConnectionStringBuilder PS C:\\> New-DbaConnectionStringBuilder Example 2: New-DbaConnectionStringBuilder Returns a connection string builder that can be used to connect to the local... PS C:\\> \"Data Source=localhost,1433;Initial Catalog=AlwaysEncryptedSample;UID=sa;PWD=alwaysB3Encrypt1ng;Application Name=Always Encrypted Sample MVC App;Column Encryption Setting=enabled\" | New-DbaConnectionStringBuilder Returns a connection string builder that can be used to connect to the local sql server instance on the default port. Optional Parameters -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. Use this when you need to modify or validate an existing connection string rather than building one from scratch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -ApplicationName Sets the application name that identifies your script or application to SQL Server in monitoring tools and logs. Defaults to \"dbatools Powershell Module\". Useful for tracking connection sources in SQL Server's sys.dm_exec_sessions and activity monitor when troubleshooting performance or connection issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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\"). Use this to set or override the server target when building connection strings for different environments or instances. | Property | Value | | --- | --- | | Alias | SqlInstance | | Required | False | | Pipeline | false | | Default Value | | -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 are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InitialCatalog Sets the default database context for the connection. When specified, queries will execute in this database unless explicitly changed. Use this when your script needs to work with a specific database rather than connecting to the server's default database. | Property | Value | | --- | --- | | Alias | Database | | Required | False | | Pipeline | false | | Default Value | | -IntegratedSecurity Enables Windows Authentication for the connection, using the current user's Windows credentials to authenticate to SQL Server. Use this when connecting to SQL Server instances configured for Windows Authentication mode or mixed mode with your current Windows account. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UserName Specifies the SQL Server login name for SQL Server Authentication. Cannot be used with SqlCredential parameter. Consider using SqlCredential parameter instead for better security as it avoids exposing credentials in plain text. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Password Specifies the password for SQL Server Authentication when using the UserName parameter. Cannot be used with SqlCredential parameter. Consider using SqlCredential parameter instead for better security as it avoids exposing passwords in plain text or command history. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MultipleActiveResultSets Enables Multiple Active Result Sets (MARS) allowing multiple commands to be executed concurrently on a single connection. Use this when your script needs to execute overlapping commands or maintain multiple data readers on the same connection simultaneously. | Property | Value | | --- | --- | | Alias | MARS | | Required | False | | Pipeline | false | | Default Value | False | -ColumnEncryptionSetting Enables Always Encrypted functionality for the connection, allowing access to encrypted columns in SQL Server databases. Use this when connecting to databases with Always Encrypted columns that your application needs to decrypt and work with. | Property | Value | | --- | --- | | Alias | AlwaysEncrypted | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Enabled | -Legacy Creates the connection string builder using the older System.Data.SqlClient library instead of the newer Microsoft.Data.SqlClient library. Use this only when working with legacy applications or frameworks that specifically require the older SQL Client library for compatibility. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NonPooledConnection Disables connection pooling, creating a dedicated connection that bypasses the connection pool. By default, connections are pooled for better performance. Use this for diagnostic scenarios or when you need to ensure complete connection isolation, though it may impact performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Useful for tracking connections by source machine in sys.dm_exec_sessions or when troubleshooting connection issues in multi-server environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.Data.SqlClient.SqlConnectionStringBuilder (default) or System.Data.SqlClient.SqlConnectionStringBuilder (when -Legacy is specified) Returns one SqlConnectionStringBuilder object for each connection string provided via the pipeline or -ConnectionString parameter. The builder object allows programmatic access and modification of all SQL Server connection string properties. The returned object exposes all connection string settings as accessible properties including: Application Name: The application name for connection identification Data Source: The SQL Server instance name and port Initial Catalog: The default database for the connection Integrated Security: Boolean indicating Windows Authentication usage User ID: SQL Server login name (if using SQL Authentication) Password: SQL Server login password (if using SQL Authentication) Workstation ID: The workstation identifier for connection tracking MultipleActiveResultSets: Boolean indicating if MARS is enabled Column Encryption Setting: Setting for Always Encrypted support (Enabled or null) Pooling: Boolean indicating if connection pooling is enabled All 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. &nbsp;"
  },
  {
    "name": "New-DbaCredential",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "credential",
      "security"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaCredential",
    "popularityRank": 201,
    "synopsis": "Creates a SQL Server credential for authentication to external resources",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaCredential View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a SQL Server credential for authentication to external resources 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. Syntax New-DbaCredential [-SqlInstance] [[-SqlCredential] ] [[-Name] ] [-Identity] [[-SecurePassword] ] [[-MappedClassType] ] [[-ProviderName] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: It will create a credential named &quot;MyCredential&quot; that as &quot;ad\\user&quot; as identity and a password on server1 if... PS C:\\> New-DbaCredential -SqlInstance Server1 -Name MyCredential -Identity \"ad\\user\" -SecurePassword (Get-Credential NoUsernameNeeded).Password It will create a credential named \"MyCredential\" that as \"ad\\user\" as identity and a password on server1 if it does not exist. Example 2: It will create a credential with identity value &quot;MyIdentity&quot; and same name but without a password on server1... PS C:\\> New-DbaCredential -SqlInstance Server1 -Identity \"MyIdentity\" It will create a credential with identity value \"MyIdentity\" and same name but without a password on server1 if it does not exist. Example 3: Creates a credential, &quot;AzureBackupBlobStore&quot;, on Server1 using the Access Keys for Backup To URL PS C:\\> $params = @{ >>SqlInstance = \"Server1\" >>Name = \"AzureBackupBlobStore\" >>Identity = \"https:// .blob.core.windows.net/ \" >>SecurePassword = (Get-Credential NoUsernameNeeded).Password # >>} PS C:\\> New-DbaCredential @params Creates 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 SecurePassword supplied is one of the two Access Keys for the Azure Storage Account. Example 4: Create a credential on Server1 using a SAS token for Backup To URL PS C:\\> $sasParams = @{ >>SqlInstance = \"server1\" >>Name = \"https:// .blob.core.windows.net/ \" >>Identity = \"SHARED ACCESS SIGNATURE\" >>SecurePassword = (Get-Credential NoUsernameNeeded).Password # >>} PS C:\\> New-DbaCredential @sasParams Create 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. The SecurePassword will be the Shared Access Token (SAS), as a SecureString. Example 5: Create a credential on Server1 using a Managed Identity for Backup To URL PS C:\\> $managedIdentityParams = @{ >>SqlInstance = \"server1\" >>Name = \"https:// .blob.core.windows.net/ \" >>Identity = \"Managed Identity\" >>} PS C:\\> New-DbaCredential @managedIdentityParams Create 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. As no password is needed in this case, we just don't pass the -SecurePassword parameter. Example 6: Creates a credential on Server1 for SQL Server 2022+ Backup to URL with S3-compatible object storage PS C:\\> $s3Params = @{ >>SqlInstance = \"server1\" >>Name = \"s3://mybucket.s3.us-west-2.amazonaws.com/backups\" >>Identity = \"S3 Access Key\" >>SecurePassword = (ConvertTo-SecureString -String \"AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\" -AsPlainText -Force) >>} PS C:\\> New-DbaCredential @s3Params Creates 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 'S3 Access Key'. The SecurePassword contains your Access Key ID and Secret Key ID separated by a colon (AccessKeyID:SecretKeyID). Required Parameters -SqlInstance The target SQL Server(s) | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Identity Defines the authentication identity for the credential. Can be a Windows account, service account, Azure storage URI, or special values like 'SHARED ACCESS SIGNATURE' or 'Managed Identity'. For Azure backup scenarios, use the full blob container URI or SAS/Managed Identity authentication methods. | Property | Value | | --- | --- | | Alias | CredentialIdentity | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies the name for the SQL Server credential object. Defaults to the Identity value if not provided. Use a descriptive name that identifies the purpose, like 'AzureBackupStorage' or 'NetworkShareAccess'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $Identity | -SecurePassword Provides the password or access key as a SecureString for credential authentication. Required for most authentication methods except Managed Identity. For Azure storage, this would be the access key or SAS token. Use Get-Credential or ConvertTo-SecureString to create the SecureString. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -MappedClassType Specifies the credential mapping class type. Use 'CryptographicProvider' for credentials that will use cryptographic providers, or 'None' for standard credentials. Most common scenarios use 'None' (default). Only specify 'CryptographicProvider' when working with EKM or custom cryptographic providers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | None | | Accepted Values | CryptographicProvider,None | -ProviderName Specifies the name of the cryptographic provider when MappedClassType is 'CryptographicProvider'. Only required when using Extensible Key Management (EKM) scenarios with third-party cryptographic providers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Drops and recreates the credential if it already exists on the target instance. Use this when you need to update an existing credential's identity or password, as SQL Server credentials cannot be modified once created. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Credential Returns 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 connection context. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the credential Identity: The authentication identity for the credential (account name, URI, or special value) CreateDate: DateTime when the credential was created on the instance MappedClassType: The mapped class type - 0 for None (standard credentials), 1 for CryptographicProvider (EKM scenarios) ProviderName: The name of the cryptographic provider (if MappedClassType is CryptographicProvider) Additional properties available from the SMO Credential object: Owner: The owner/principal that owns the credential ID: The unique identifier for the credential within the instance DateLastModified: DateTime when the credential was last modified Urn: The Uniform Resource Name for the credential object State: The current state of the SMO object (Existing, Creating, Deleting, etc.) All properties from the base SMO Credential object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaCustomError",
    "description": "Creates custom error messages in SQL Server's 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.",
    "category": "Utilities",
    "tags": [
      "general",
      "error"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaCustomError",
    "popularityRank": 674,
    "synopsis": "Creates custom error messages in SQL Server's sys.messages table for standardized application and stored procedure error handling",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaCustomError View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates custom error messages in SQL Server's sys.messages table for standardized application and stored procedure error handling Description Creates custom error messages in SQL Server's 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. Custom 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. You 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. Note: 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. Syntax New-DbaCustomError [-SqlInstance] [[-SqlCredential] ] [[-MessageID] ] [[-Severity] ] [[-MessageText] ] [[-Language] ] [-WithLog] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new custom message on the sqldev01 and sqldev02 instances with ID 70001, severity 16, and text... PS C:\\> New-DbaCustomError -SqlInstance sqldev01, sqldev02 -MessageID 70001 -Severity 16 -MessageText \"test\" Creates a new custom message on the sqldev01 and sqldev02 instances with ID 70001, severity 16, and text \"test\". Example 2: Creates a new custom message on the sqldev01 instance for the french language with ID 70001, severity 16, and... PS C:\\> New-DbaCustomError -SqlInstance sqldev01 -MessageID 70001 -Severity 16 -MessageText \"test\" -Language \"French\" Creates a new custom message on the sqldev01 instance for the french language with ID 70001, severity 16, and text \"test\". Example 3: Creates a new custom message on the sqldev01 instance with ID 70001, severity 16, text &quot;test&quot;, and enables... PS C:\\> New-DbaCustomError -SqlInstance sqldev01 -MessageID 70001 -Severity 16 -MessageText \"test\" -WithLog Creates a new custom message on the sqldev01 instance with ID 70001, severity 16, text \"test\", and enables the log mechanism. Example 4: Creates a new custom message on the sqldev01 instance with ID 70000, severity 16, and text &quot;test_70000&quot; To... PS C:\\> $server = Connect-DbaInstance sqldev01 PS C:\\> $newMessage = New-DbaCustomError -SqlInstance $server -MessageID 70000 -Severity 16 -MessageText \"test_70000\" PS C:\\> $original = $server.UserDefinedMessages | Where-Object ID -eq 70000 PS C:\\> $messageID = $original.ID PS C:\\> $severity = 20 PS C:\\> $text = $original.Text PS C:\\> $language = $original.Language PS C:\\> $removed = Remove-DbaCustomError -SqlInstance $server -MessageID 70000 PS C:\\> $alteredMessage = New-DbaCustomError -SqlInstance $server -MessageID $messageID -Severity $severity -MessageText $text -Language $language -WithLog Creates a new custom message on the sqldev01 instance with ID 70000, severity 16, and text \"test_70000\" To modify the custom message at a later time the following can be done to change the severity from 16 to 20: The resulting updated message object is available in $alteredMessage. Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MessageID Specifies the unique identifier for the custom error message, ranging from 50001 to 2147483647. Choose an ID that doesn't conflict with existing custom messages in your environment. Use sequential numbering for organization, such as 60000-60999 for application errors and 61000-61999 for stored procedure validation errors. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 resource errors, and 20-25 are fatal system errors. Most custom application errors use severity 16, while validation errors often use 11-15 depending on whether the application should continue processing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 wrong. Include parameter placeholders using printf-style formatting (like %s, %d) when the message needs dynamic values at runtime. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Language Specifies the language for the error message using values from sys.syslanguages (Name or Alias columns). Defaults to 'English' if not specified. Create 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this for critical errors that require audit trails or monitoring alerts, but avoid for frequently occurring validation errors to prevent log flooding. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.UserDefinedMessage Returns the newly created UserDefinedMessage object from the target SQL Server instance. One object is returned per custom error message created. Properties: ID (int) - The unique message identifier (50001-2147483647) Language (string) - The language of the message (English, French, etc.) Severity (int) - The severity level of the message (1-25) Text (string) - The error message text (up to 255 characters) IsLogged (bool) - Boolean indicating if the message is logged to Windows Application Log and SQL Server Error Log CreateDate (datetime) - DateTime when the message was created All properties from the base SMO UserDefinedMessage object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaDacOption",
    "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",
    "category": "Utilities",
    "tags": [
      "deployment",
      "dacpac"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDacOption",
    "popularityRank": 307,
    "synopsis": "Creates a new Microsoft.SqlServer.Dac.DacExtractOptions/DacExportOptions object depending on the chosen Type",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDacOption View Source Kirill Kravtsov (@nvarscar), nvarscar.wordpress.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a new Microsoft.SqlServer.Dac.DacExtractOptions/DacExportOptions object depending on the chosen Type 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 ;) See: https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.dac.dacexportoptions.aspx https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.dac.dacextractoptions.aspx for more information Syntax New-DbaDacOption [[-Type] ] [-Action] [[-PublishXml] ] [[-Property] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Uses DacOption object to set the CommandTimeout to 0 then extracts the dacpac for SharePoint_Config on... PS C:\\> $options = New-DbaDacOption -Type Dacpac -Action Export PS C:\\> $options.ExtractAllTableData = $true PS C:\\> $options.CommandTimeout = 0 PS C:\\> Export-DbaDacPackage -SqlInstance sql2016 -Database DB1 -Options $options Uses 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. Example 2: Creates a pre-initialized DacOption object and uses it to extrac a DacPac from the database PS C:\\> $options = New-DbaDacOption -Type Dacpac -Action Export -Property @{ExtractAllTableData=$true;CommandTimeout=0} PS C:\\> Export-DbaDacPackage -SqlInstance sql2016 -Database DB1 -Options $options Example 3: Uses DacOption object to set Deployment Options and publish the db.dacpac dacpac file as DB1 on sql2016 PS C:\\> $options = New-DbaDacOption -Type Dacpac -Action Publish PS C:\\> $options.DeployOptions.DropObjectsNotInSource = $true PS C:\\> Publish-DbaDacPackage -SqlInstance sql2016 -Database DB1 -Options $options -Path c:\\temp\\db.dacpac Required Parameters -Action Determines whether you're exporting from a database or publishing to a database. Use Export when extracting a package from an existing database for backup or migration purposes. Use Publish when deploying a package to create or update a target database. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | | Accepted Values | Publish,Export | Optional Parameters -Type Specifies the package type to create: Dacpac (schema and data) or Bacpac (data only). Defaults to Dacpac. Use Dacpac when you need to capture database schema structure along with optional data for deployment scenarios. Use Bacpac when you only need to export and import data without schema changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Dacpac | | Accepted Values | Dacpac,Bacpac | -PublishXml Path to a DAC publish profile XML file that contains deployment options and SQLCMD variables. These profiles are typically created in SQL Server Data Tools (SSDT) and control how the deployment behaves. When specified, the profile's settings override any DeployOptions specified in the Property parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Property Hashtable of properties to configure the DAC options object, such as CommandTimeout or ExtractAllTableData. For Publish actions, use the DeployOptions key to set deployment behaviors like DropObjectsNotInSource or BlockOnPossibleDataLoss. Common properties include CommandTimeout for long operations and ExtractAllTableData when exporting data with schema. Example: @{CommandTimeout=0; DeployOptions=@{DropObjectsNotInSource=$true}} | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Dac.DacExtractOptions (when Type=Dacpac and Action=Export) Returns a DacExtractOptions object for extracting schema and data from a database into a DAC package. Properties include ExtractAllTableData (boolean), CommandTimeout (int), and other extraction settings. Microsoft.SqlServer.Dac.DacExportOptions (when Type=Bacpac and Action=Export) Returns a DacExportOptions object for exporting data only (without schema) from a database into a BAC package. Properties include CommandTimeout (int) and other export-specific settings. Microsoft.SqlServer.Dac.PublishOptions (when Type=Dacpac and Action=Publish) Returns a PublishOptions object for publishing (deploying) a DAC package to a target database. Contains a DeployOptions property (Microsoft.SqlServer.Dac.DacDeployOptions) with settings like DropObjectsNotInSource (boolean) and BlockOnPossibleDataLoss (boolean). When a PublishXml profile is provided, DeployOptions are loaded from the profile file; otherwise DeployOptions can be set via the Property parameter. The GenerateDeploymentScript property (boolean) is initialized based on the Property parameter or defaults to false. Microsoft.SqlServer.Dac.DacImportOptions (when Type=Bacpac and Action=Publish) Returns a DacImportOptions object for importing (deploying) a BAC package data into a target database. Properties include CommandTimeout (int) and other import-specific settings. All 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's settings override Property parameter values. &nbsp;"
  },
  {
    "name": "New-DbaDacPackage",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "dacpac",
      "deployment"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDacPackage",
    "popularityRank": 0,
    "synopsis": "Creates a DACPAC package from SQL source files using the DacFx framework",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDacPackage View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a DACPAC package from SQL source files using the DacFx framework 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. This 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). The DACPAC output can be deployed using Publish-DbaDacPackage, enabling idempotent schema deployments with automatic dependency ordering and drift detection. Syntax New-DbaDacPackage [-Path] [[-OutputPath] ] [[-DacVersion] ] [[-DacDescription] ] [[-DatabaseName] ] [-Recursive] [[-SqlServerVersion] ] [[-Filter] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a DACPAC from all SQL files in C:\\Projects\\MyDatabase\\Schema and saves it to... PS C:\\> New-DbaDacPackage -Path C:\\Projects\\MyDatabase\\Schema -OutputPath C:\\Build\\MyDatabase.dacpac Creates a DACPAC from all SQL files in C:\\Projects\\MyDatabase\\Schema and saves it to C:\\Build\\MyDatabase.dacpac. Example 2: Creates a DACPAC from all SQL files in the Schema directory and subdirectories, setting the database name to... PS C:\\> New-DbaDacPackage -Path C:\\Projects\\MyDatabase\\Schema -Recursive -DatabaseName \"MyAppDB\" -DacVersion \"2.1.0.0\" Creates 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\". Example 3: Creates a DACPAC from source files and immediately deploys it to the TestDeploy database on sql2019 PS C:\\> New-DbaDacPackage -Path C:\\Projects\\MyDatabase -Recursive | Publish-DbaDacPackage -SqlInstance sql2019 -Database TestDeploy Example 4: Creates a DACPAC targeting SQL Server 2017 compatibility, useful when deploying to older SQL Server versions PS C:\\> New-DbaDacPackage -Path C:\\Projects\\MyDatabase\\Schema -SqlServerVersion Sql140 -Recursive Example 5: Creates a DACPAC including only SQL files with &quot;Table&quot; in their filename PS C:\\> New-DbaDacPackage -Path C:\\Projects\\MyDatabase -Filter \"Table.sql\" -Recursive Example 6: Creates a DACPAC and displays detailed results including object count, duration, and any errors or warnings PS C:\\> $result = New-DbaDacPackage -Path .\\sql\\Schema -Recursive -DatabaseName \"dbatoolspro\" -DacVersion \"1.0.0\" PS C:\\> $result | Format-List Required Parameters -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. Alternatively, specify a path to a .sqlproj file to parse project settings and file references from the project definition. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. Example: If DatabaseName is \"MyDatabase\", the default output would be \".\\MyDatabase.dacpac\" | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DacVersion Specifies the version number for the DACPAC package metadata. Defaults to \"1.0.0.0\". Use semantic versioning aligned with your build or release process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1.0.0.0 | -DacDescription Specifies an optional description to embed in the DACPAC package metadata. Use this to document the package purpose or build context. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DatabaseName Specifies the database name for the DACPAC package metadata. Defaults to the name of the Path directory or current directory. This name is used when deploying the DACPAC if no target database name is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Recursive Includes SQL files from subdirectories when Path is a directory. Use this to process hierarchical folder structures like Schema\\Tables\\, Schema\\Views\\, etc. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SqlServerVersion Specifies the target SQL Server version for model validation and compatibility checking. Valid values: Sql90 (2005), Sql100 (2008), Sql110 (2012), Sql120 (2014), Sql130 (2016), Sql140 (2017), Sql150 (2019), Sql160 (2022), SqlAzure. Defaults to Sql160 (SQL Server 2022). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Sql160 | | Accepted Values | Sql90,Sql100,Sql110,Sql120,Sql130,Sql140,Sql150,Sql160,SqlAzure | -Filter Specifies a wildcard pattern to filter which SQL files to include. Defaults to \".sql\". Use this to include only specific file patterns like \"Table.sql\" or \"Schema_.sql\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | *.sql | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one result object per DACPAC build operation. On successful build: ComputerName: The local computer name where the DACPAC was built Path: Full file path to the created DACPAC file Database: The database name embedded in the DACPAC package metadata DatabaseName: Database name (same as Database property) Version: Version string in semantic version format (e.g., \"1.0.0.0\") FileCount: Number of SQL files processed into the DACPAC ObjectCount: Number of database objects in the compiled model Duration: Elapsed time for the build operation (prettytimespan object, displays as human-readable duration) Success: Boolean True indicating successful DACPAC creation Errors: Array of error messages encountered (empty array on success) Warnings: Array of warning messages from validation (empty array if no warnings) Default display properties (via Select-DefaultView): Path: File path to the DACPAC DatabaseName: Database name Version: Package version FileCount: SQL files processed ObjectCount: Database objects compiled Duration: Build time elapsed Success: Build status On build failure (when validation errors prevent DACPAC creation): DacpacPath: Null (DACPAC was not created) DatabaseName: Database name Version: Version string FileCount: Number of files attempted ObjectCount: Object count at time of failure Duration: Elapsed time before failure Success: Boolean False Errors: Array of validation and processing errors preventing build Warnings: Array of warnings encountered before failure All objects are returned as PSCustomObject with properties accessible via dot notation or Select-Object. The output is pipeline-compatible with Publish-DbaDacPackage for automated deployment workflows. PSCustomObject Returns one result object per DACPAC build operation. On successful build: ComputerName: The local computer name where the DACPAC was built Path: Full file path to the created DACPAC file Database: The database name embedded in the DACPAC package metadata DatabaseName: Database name (same as Database property) Version: Version string in semantic version format (e.g., \"1.0.0.0\") FileCount: Number of SQL files processed into the DACPAC ObjectCount: Number of database objects in the compiled model Duration: Elapsed time for the build operation (prettytimespan object, displays as human-readable duration) Success: Boolean True indicating successful DACPAC creation Errors: Array of error messages encountered (empty array on success) Warnings: Array of warning messages from validation (empty array if no warnings) Default display properties (via Select-DefaultView): Path: File path to the DACPAC DatabaseName: Database name Version: Package version FileCount: SQL files processed ObjectCount: Database objects compiled Duration: Build time elapsed Success: Build status On build failure (when validation errors prevent DACPAC creation): DacpacPath: Null (DACPAC was not created) DatabaseName: Database name Version: Version string FileCount: Number of files attempted ObjectCount: Object count at time of failure Duration: Elapsed time before failure Success: Boolean False Errors: Array of validation and processing errors preventing build Warnings: Array of warnings encountered before failure All objects are returned as PSCustomObject with properties accessible via dot notation or Select-Object. The output is pipeline-compatible with Publish-DbaDacPackage for automated deployment workflows. &nbsp;"
  },
  {
    "name": "New-DbaDacProfile",
    "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'll 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",
    "category": "Utilities",
    "tags": [
      "deployment",
      "dacpac"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDacProfile",
    "popularityRank": 511,
    "synopsis": "Creates DAC publish profile XML files for automated dacpac deployment to SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDacProfile View Source Richie lee (@richiebzzzt) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates DAC publish profile XML files for automated dacpac deployment to SQL Server databases. 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. The generated XML template includes basic deployment settings sufficient for most dacpac deployments, but you'll typically want to add additional deployment options to the publish profile for production scenarios. If 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. For automation scenarios, these profiles work directly with SqlPackage.exe command-line deployments, eliminating the need to specify connection and deployment settings manually each time. For 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 Syntax New-DbaDacProfile [[-SqlInstance] ] [[-SqlCredential] ] [-Database] [[-Path] ] [[-ConnectionString] ] [[-PublishOptions] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: In this example, a prompt will appear for alternative credentials, then a connection will be made to sql2017 PS C:\\> New-DbaDacProfile -SqlInstance sql2017 -SqlCredential ad\\sqldba -Database WorldWideImporters -Path C:\\temp In this example, a prompt will appear for alternative credentials, then a connection will be made to sql2017. Using that connection, the ConnectionString will be extracted and used within the Publish Profile XML file which will be created at C:\\temp\\sql2017-WorldWideImporters-publish.xml Example 2: In this example, no connections are made, and a Publish Profile XML would be created at... PS C:\\> New-DbaDacProfile -Database WorldWideImporters -Path C:\\temp -ConnectionString \"SERVER=(localdb)\\MSSQLLocalDB;Integrated Security=True;Database=master\" In this example, no connections are made, and a Publish Profile XML would be created at C:\\temp\\localdb-MSSQLLocalDB-WorldWideImporters-publish.xml Required Parameters -Database Specifies the target database name where the dacpac will be deployed. This sets the TargetDatabaseName property in the generated publish profile. Use this to define which database will receive the dacpac deployment when the profile is used with SqlPackage.exe or Visual Studio publishing. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. Alternatively, you can provide a ConnectionString. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory where the publish profile XML files will be created. Defaults to your Documents folder if not specified. Files are automatically named using the pattern \"instancename-databasename-publish.xml\" for easy identification and organization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \"$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. Use 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 limitations. If you provide SqlInstance, the function will connect and generate the connection string automatically. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this to control dacpac deployment behavior like blocking data loss (BlockOnPossibleDataLoss), ignoring permissions (IgnorePermissions), or script generation options. Common options include IgnoreUserSettingsObjects, GenerateDeploymentScript, and CreateNewDatabase. See SqlPackage.exe documentation for complete option list. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one result object per database specified when generating a publish profile. Objects combine connection context and profile metadata. Properties: ComputerName: Computer name extracted from the DbaInstance object (derived from connection string) InstanceName: Instance name extracted from the DbaInstance object (derived from connection string) SqlInstance: Full SQL Server instance name in format \"ComputerName\\InstanceName\" (from DbaInstance.FullName) Database: Target database name for which the profile was generated FileName: Full file path to the generated XML publish profile (e.g., \"C:\\temp\\sql2017-WorldWideImporters-publish.xml\") ConnectionString: The connection string embedded in the profile (e.g., \"Server=sql2017;Integrated Security=True;Encrypt=False\") ProfileTemplate: Complete XML content of the publish profile (excluded from default display via Select-DefaultView) Default display properties (via Select-DefaultView): SqlInstance: SQL Server instance name Database: Target database FileName: Profile file path ConnectionString: Connection string Output Quantity: Returns one object per database specified in the -Database parameter for each connection string. For example: Specifying one database with one connection string returns 1 object Specifying multiple databases (DB1, DB2) with one connection string returns 2 objects Specifying multiple databases with multiple connection strings returns (databases count Ã— connection strings count) objects The 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. &nbsp;"
  },
  {
    "name": "New-DbaDatabase",
    "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't 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.",
    "category": "Database Operations",
    "tags": [
      "database"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDatabase",
    "popularityRank": 77,
    "synopsis": "Creates new SQL Server databases with customizable file layout and growth settings",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDatabase View Source Matthew Darwin (@evoDBA, naturalselectiondba.wordpress.com) , Chrissy LeMaire (@cl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates new SQL Server databases with customizable file layout and growth settings 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. The 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't provided, it inherits sensible defaults from the model database to ensure new databases start with appropriate baseline configurations. Supports 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. Syntax New-DbaDatabase [-SqlInstance] [[-SqlCredential] ] [[-Name] ] [[-Collation] ] [[-RecoveryModel] ] [[-Owner] ] [[-DataFilePath] ] [[-LogFilePath] ] [[-PrimaryFilesize] ] [[-PrimaryFileGrowth] ] [[-PrimaryFileMaxSize] ] [[-LogSize] ] [[-LogGrowth] ] [[-LogMaxSize] ] [[-SecondaryFilesize] ] [[-SecondaryFileGrowth] ] [[-SecondaryFileMaxSize] ] [[-SecondaryFileCount] ] [[-DefaultFileGroup] ] [[-DataFileSuffix] ] [[-LogFileSuffix] ] [[-SecondaryDataFileSuffix] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a randomly named database (random-N) on instance sql1 PS C:\\> New-DbaDatabase -SqlInstance sql1 Example 2: Creates a database named dbatools and a database named dbachecks on sql1 PS C:\\> New-DbaDatabase -SqlInstance sql1 -Name dbatools, dbachecks Example 3: Creates two databases, multidb and multidb2, on 3 instances (sql1, sql2 and sql3) and sets the secondary data... PS C:\\> New-DbaDatabase -SqlInstance sql1, sql2, sql3 -Name multidb, multidb2 -SecondaryFilesize 20 -SecondaryFileGrowth 20 -LogSize 20 -LogGrowth 20 Creates 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 Example 4: Creates a database named nondefault and places data files in in the M:\\data directory and log files in... PS C:\\> New-DbaDatabase -SqlInstance sql1 -Name nondefault -DataFilePath M:\\Data -LogFilePath 'L:\\Logs with spaces' -SecondaryFileCount 2 Creates a database named nondefault and places data files in in the M:\\data directory and log files in \"L:\\Logs with spaces\". Creates a secondary group with 2 files in the Secondary filegroup. Example 5: Creates a new database named newDb on the sql1 instance and sets the file sizes, max sizes, and growth as... PS C:\\> $databaseParams = @{ >> SqlInstance = \"sql1\" >> Name = \"newDb\" >> LogSize = 32 >> LogMaxSize = 512 >> PrimaryFilesize = 64 >> PrimaryFileMaxSize = 512 >> SecondaryFilesize = 64 >> SecondaryFileMaxSize = 512 >> LogGrowth = 32 >> PrimaryFileGrowth = 64 >> SecondaryFileGrowth = 64 >> DataFileSuffix = \"_PRIMARY\" >> LogFileSuffix = \"_Log\" >> SecondaryDataFileSuffix = \"_MainData\" >> } >> New-DbaDatabase @databaseParams Creates 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: newDb_PRIMARY newDb_Log newDb_MainData_1 (Secondary filegroup files) Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 database with a randomly generated name like \"random-12345\". | Property | Value | | --- | --- | | Alias | Database | | Required | False | | Pipeline | false | | Default Value | | -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 cultural sorting requirements different from the server default. If not specified, inherits the server's default collation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RecoveryModel Sets the recovery model which determines how transaction log backups work and how much data loss is acceptable. Simple recovery model doesn't require log backups but limits point-in-time recovery, Full enables complete point-in-time recovery with log backups, BulkLogged offers a compromise for bulk operations. If not specified, inherits from the model database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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 must already exist on the SQL Server instance. If not specified, the connecting user becomes the database owner. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 specified, uses the SQL Server instance's default data directory. The function will create the directory if it doesn't exist. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 specified, uses the SQL Server instance's default log directory. The function will create the directory if it doesn't exist. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 size is smaller than the model database's primary file, the model size is used instead to maintain minimum requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 disk space problems in production environments. If not specified, inherits the model database's growth settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 processes or data imports. If set smaller than the initial file size, the initial size becomes the maximum. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 transaction volume and backup frequency - larger logs for high-activity databases or infrequent log backups. If not specified, uses the model database's log size. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 high-activity periods. Consider setting this to handle your typical transaction volume between log backups. If not specified, uses the model database's growth settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Consider 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 balanced I/O distribution. If not specified and secondary files are created, uses the model database's file size. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 to disable autogrowth for controlled file management. Fixed MB increments provide predictable growth behavior. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 files will use this same maximum size limit to maintain consistency across the filegroup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 storage configuration and available CPU cores when determining the file count - typically one file per CPU core up to the number of available drives. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 filegroup. Setting the secondary filegroup as default directs new objects to use the optimized multi-file configuration for better performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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 differentiate between environments (like \"_PROD\" or \"_DEV\"). If not specified, no suffix is added. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 data files. Defaults to \"_log\" if not specified, creating files like \"MyDatabase_log.ldf\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | _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 + SecondaryDataFileSuffix + \"_1.ndf\". Use descriptive suffixes like \"_Data\" or \"_Indexes\" to indicate the intended use of the secondary filegroup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Database Returns one Database object for each database successfully created on the target SQL Server instance(s). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Name of the newly created database Status: Current database status (Normal for a new database) IsAccessible: Boolean indicating if the database is currently accessible RecoveryModel: Database recovery model (Simple, Full, or BulkLogged as specified) LogReuseWaitStatus: Status of transaction log reuse Size: Database size in megabytes (MB) Compatibility: Database compatibility level Collation: Database collation setting (as specified) Owner: Database owner login name (as specified) Encrypted: Boolean indicating if Transparent Data Encryption is enabled LastFullBackup: DateTime of last full backup (null for new database) LastDiffBackup: DateTime of last differential backup (null for new database) LastLogBackup: DateTime of last transaction log backup (null for new database) Additional properties available via Select-Object * from the SMO Database object include all standard database properties such as MirroringPartner, MirroringRole, PrimaryFilePath, and others documented in the SQL Server Management Objects (SMO) reference. &nbsp;"
  },
  {
    "name": "New-DbaDbAsymmetricKey",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbAsymmetricKey",
    "popularityRank": 635,
    "synopsis": "Creates RSA asymmetric keys in SQL Server databases for encryption and digital signing",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbAsymmetricKey View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates RSA asymmetric keys in SQL Server databases for encryption and digital signing 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. Syntax New-DbaDbAsymmetricKey [[-SqlInstance] ] [[-SqlCredential] ] [[-Name] ] [[-Database] ] [[-SecurePassword] ] [[-Owner] ] [[-KeySource] ] [[-KeySourceType] ] [[-InputObject] ] [[-Algorithm] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: You will be prompted to securely enter your password, then an asymmetric key will be created in the master... PS C:\\> New-DbaDbAsymmetricKey -SqlInstance Server1 You 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. Example 2: Suppresses all prompts to install but prompts to securely enter your password and creates an asymmetric key... PS C:\\> New-DbaDbAsymmetricKey -SqlInstance Server1 -Database db1 -Confirm:$false Suppresses all prompts to install but prompts to securely enter your password and creates an asymmetric key in the 'db1' database Example 3: Installs the key pair held in NewKey.snk into the enctest database creating an AsymmetricKey called... PS C:\\> New-DbaDbAsymmetricKey -SqlInstance Server1 -Database enctest -KeySourceType File -KeySource c:\\keys\\NewKey.snk -Name BackupKey -Owner KeyOwner Installs the key pair held in NewKey.snk into the enctest database creating an AsymmetricKey called BackupKey, which will be owned by KeyOwner Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies the name for the asymmetric key object within the database. Defaults to the database name if not provided. Choose meaningful names that reflect the key's purpose, such as 'TDE_Key' or 'BackupKey' for easier identification. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target database where the asymmetric key will be created. Defaults to master database if not specified. Use this when creating encryption keys for specific user databases rather than system-wide keys. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | master | -SecurePassword Provides a password to encrypt the asymmetric key's private key. If omitted, the database master key protects the private key. Use this when you need explicit password control or when the database master key is not available. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -Owner Specifies the database user who will own the asymmetric key. Defaults to the current user if not specified. The specified user must already exist in the target database before creating the key. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -KeySource Specifies the path or name of the external key source (file, executable, or SQL assembly name). The path must be accessible by the SQL Server service account when using File or Executable types. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -KeySourceType Specifies the type of external key source when importing existing keys. Valid values are Executable, File, or SqlAssembly. Required when using KeySource parameter to import keys from external files rather than generating new ones. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Executable,File,SqlAssembly | -InputObject Accepts database objects from Get-DbaDatabase through the pipeline for batch key creation. Use this when creating asymmetric keys across multiple databases in a single operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Algorithm Sets the RSA encryption algorithm strength for newly generated keys. Valid options are Rsa512, Rsa1024, Rsa2048, Rsa3072, or Rsa4096. Defaults to Rsa2048 which provides good security for most scenarios. Higher bit strengths offer stronger encryption but slower performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Rsa2048 | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.AsymmetricKey Returns one AsymmetricKey object for each asymmetric key successfully created in the target database(s). Display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database containing the asymmetric key Name: The name of the asymmetric key Owner: The database user who owns the key KeyEncryptionAlgorithm: The RSA algorithm used (Rsa512, Rsa1024, Rsa2048, Rsa3072, or Rsa4096) KeyLength: The key length in bits (512, 1024, 2048, 3072, or 4096) PrivateKeyEncryptionType: How the private key is encrypted (Password, MasterKey, or None) Thumbprint: The SHA-1 hash of the public key for identification Additional 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 Name), and State (current SMO object state). &nbsp;"
  },
  {
    "name": "New-DbaDbCertificate",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbCertificate",
    "popularityRank": 283,
    "synopsis": "Creates a new database certificate for encryption and security purposes",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbCertificate View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a new database certificate for encryption and security purposes 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. Syntax New-DbaDbCertificate [[-SqlInstance] ] [[-SqlCredential] ] [[-Name] ] [[-Database] ] [[-Subject] ] [[-StartDate] ] [[-ExpirationDate] ] [-ActiveForServiceBrokerDialog] [[-SecurePassword] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: You will be prompted to securely enter your password, then a certificate will be created in the master... PS C:\\> New-DbaDbCertificate -SqlInstance Server1 You 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. Example 2: Suppresses all prompts to install but prompts to securely enter your password and creates a certificate in... PS C:\\> New-DbaDbCertificate -SqlInstance Server1 -Database db1 -Confirm:$false Suppresses all prompts to install but prompts to securely enter your password and creates a certificate in the 'db1' database Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies the name for the certificate. Defaults to the database name if not provided. Use descriptive names that indicate the certificate's purpose, such as 'TDE_Certificate' or 'ColumnEncryption_Cert'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database where the certificate will be created. Defaults to master if not specified. Use this when you need certificates in specific databases for TDE, column-level encryption, or Service Broker security. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | master | -Subject Specifies the certificate subject field for identification purposes. Defaults to '[DatabaseName] Database Certificate'. Use meaningful subjects like 'CN=MyApp TDE Certificate' to help identify certificate purposes in production environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartDate Specifies when the certificate becomes valid for use. Defaults to the current date and time. Set future start dates when you need to prepare certificates in advance for scheduled encryption implementations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-Date) | -ExpirationDate Specifies when the certificate expires and becomes invalid. Defaults to 5 years from the start date. Plan expiration dates carefully as expired certificates will prevent access to encrypted data and require certificate renewal procedures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $StartDate.AddYears(5) | -ActiveForServiceBrokerDialog Enables the certificate for Service Broker dialog security and message encryption. Disabled by default. Use this when implementing Service Broker applications that require encrypted message communication between services. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SecurePassword Specifies a password to encrypt the certificate's private key. If not provided, the database master key protects the certificate. Use passwords when you need to backup/restore certificates across instances or when the database master key is not available. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase for pipeline operations. Use this to create certificates across multiple databases efficiently by piping database objects from Get-DbaDatabase. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Certificate Returns one Certificate object for each certificate created in the specified database. The certificate object contains all the configuration properties defined during creation including expiration dates, encryption settings, and Service Broker dialog status. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the certificate Name: The name of the certificate Subject: The subject field of the certificate for identification purposes StartDate: The date and time when the certificate becomes valid ActiveForServiceBrokerDialog: Boolean indicating if the certificate is active for Service Broker dialog security ExpirationDate: The date and time when the certificate expires Issuer: The issuer of the certificate LastBackupDate: The date and time of the most recent backup of the certificate Owner: The owner or principal that owns the certificate PrivateKeyEncryptionType: The encryption type used for the private key (None, Password, or MasterKey) Serial: The serial number of the certificate Additional properties available (from SMO Certificate object): ID: The unique identifier for the certificate Thumbprint: The SHA-1 hash of the certificate CreateDate: The date and time when the certificate was created Sid: The security identifier (SID) of the certificate owner State: The current state of the SMO object (Existing, Creating, Pending, etc.) All properties from the base SMO Certificate object are accessible using Select-Object * even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "New-DbaDbDataGeneratorConfig",
    "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",
    "category": "Advanced Features",
    "tags": [
      "datageneration",
      "database"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbDataGeneratorConfig",
    "popularityRank": 435,
    "synopsis": "Creates JSON configuration files for generating realistic test data in SQL Server database tables",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbDataGeneratorConfig View Source Sander Stad (@sqlstad, sqlstad.nl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates JSON configuration files for generating realistic test data in SQL Server database tables 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. These 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. The 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. Read more here: https://sachabarbs.wordpress.com/2018/06/11/bogus-simple-fake-data-tool/ https://github.com/bchavez/Bogus Syntax New-DbaDbDataGeneratorConfig [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Table] ] [-ResetIdentity] [-TruncateTable] [[-Rows] ] [-Path] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Process all tables and columns for database DB1 on instance SQLDB1 PS C:\\> New-DbaDbDataGeneratorConfig -SqlInstance SQLDB1 -Database DB1 -Path C:\\Temp\\clone Example 2: Process only table Customer with all the columns PS C:\\> New-DbaDbDataGeneratorConfig -SqlInstance SQLDB1 -Database DB1 -Table Customer -Path C:\\Temp\\clone Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Path Specifies the directory where JSON configuration files will be saved. Files are named using the pattern \"servername.databasename.DataGeneratorConfig.json\". Choose a location accessible to your development team since these config files will be used by Invoke-DbaDbDataGenerator to create the actual test data. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for data generation configuration creation. Accepts multiple database names. Use this when you need to create test data configs for specific databases instead of all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Specifies which tables to include in the data generation configuration. Accepts multiple table names and supports wildcards. Use this when you only need test data for specific tables rather than analyzing the entire database schema. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ResetIdentity Controls whether identity columns should reset to their seed values when generating test data. When enabled, identity values start from the original seed. Use this when you need predictable, consistent identity values across test data generation runs instead of continuing from existing maximum values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -TruncateTable Enables table truncation before inserting generated test data. When specified, existing data is removed before populating with fake data. Use this when you need clean test environments or want to replace all existing data rather than appending to current table contents. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Rows Sets the number of test data rows to generate for each table in the configuration. Defaults to 1000 rows per table. Adjust this based on your testing needs - use smaller values for development environments or larger values for performance testing scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1000 | -Force Allows the function to create the specified Path directory if it doesn't exist. Without this switch, the function will fail if the target directory is missing. Use this when setting up new test data workflows where the output directory structure hasn't been established yet. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.IO.FileInfo Returns file information for each JSON configuration file that was successfully written to disk. Properties: Name: The filename of the generated configuration file (format: servername.databasename.DataGeneratorConfig.json) FullName: The complete file path where the configuration was saved Length: The size of the JSON file in bytes CreationTime: The datetime when the file was created LastWriteTime: The datetime when the file was last written DirectoryName: The directory path containing the configuration file The output object allows you to verify which configuration files were created and their locations for use with Invoke-DbaDbDataGenerator. &nbsp;"
  },
  {
    "name": "New-DbaDbEncryptionKey",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbEncryptionKey",
    "popularityRank": 343,
    "synopsis": "Creates database encryption keys for Transparent Data Encryption (TDE)",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbEncryptionKey View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates database encryption keys for Transparent Data Encryption (TDE) 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. Syntax New-DbaDbEncryptionKey [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-EncryptorName] ] [[-Type] ] [[-EncryptionAlgorithm] ] [[-InputObject] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates an Aes256 encryption key for the pubs database on sql01 PS C:\\> $dbs = Get-DbaDatabase -SqlInstance sql01 -Database pubs PS C:\\> $db | New-DbaDbEncryptionKey Creates 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. Prompts for confirmation. Example 2: Creates an Aes192 encryption key for the pubs database on sql01 using the certiciated named &quot;sql01 cert&quot; in... PS C:\\> New-DbaDbEncryptionKey -SqlInstance sql01 -Database db1 -EncryptorName \"sql01 cert\" -EncryptionAlgorithm Aes192 -Confirm:$false Creates an Aes192 encryption key for the pubs database on sql01 using the certiciated named \"sql01 cert\" in master. Does not prompt for confirmation. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database where the encryption key will be created to enable Transparent Data Encryption. This is the user database you want to encrypt, not the master database where certificates are stored. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | master | -EncryptorName Specifies the name of the certificate or asymmetric key in the master database to encrypt the database encryption key. If not provided, the function automatically selects an appropriate certificate from master (requires exactly one non-system certificate to exist). For asymmetric keys, the key must reside on an extensible key management provider like Azure Key Vault or Hardware Security Module. | Property | Value | | --- | --- | | Alias | Certificate,CertificateName | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies whether to use a Certificate or AsymmetricKey from the master database as the encryptor. Certificates are more common for TDE implementations, while asymmetric keys are typically used with external key management providers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Certificate | | Accepted Values | Certificate,AsymmetricKey | -EncryptionAlgorithm Specifies the symmetric encryption algorithm used for the database encryption key. Aes256 provides the strongest encryption and is recommended for production environments, while Aes128 offers faster performance. TripleDes is legacy and should be avoided for new implementations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Aes256 | | Accepted Values | Aes128,Aes192,Aes256,TripleDes | -InputObject Accepts database objects from Get-DbaDatabase to create encryption keys for multiple databases. Use this when you need to enable TDE on several databases across one or more SQL Server instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Force Bypasses the safety check that prevents creating encryption keys with unbackup certificates, which could lead to unrecoverable data loss. Also creates the specified certificate automatically if it doesn't exist in the master database. Use this only in development environments or when you have verified certificate backups exist through other means. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.DatabaseEncryptionKey Returns 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 returned for that database. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the encryption key CreateDate: DateTime when the encryption key was created EncryptionAlgorithm: The encryption algorithm used (Aes128, Aes192, Aes256, or TripleDes) EncryptionState: Current encryption state (Encrypted, EncryptionInProgress, DecryptionInProgress, or EncryptionUnsupported) EncryptionType: Type of encryptor used (ServerCertificate or ServerAsymmetricKey) EncryptorName: Name of the certificate or asymmetric key protecting this encryption key ModifyDate: DateTime when the encryption key was last modified OpenedDate: DateTime when the encryption key was last opened RegenerateDate: DateTime when the encryption key was last regenerated SetDate: DateTime when the encryption key was last set Thumbprint: Thumbprint hash of the certificate protecting this encryption key All properties from the base SMO DatabaseEncryptionKey object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaDbFileGroup",
    "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.",
    "category": "Database Operations",
    "tags": [
      "storage",
      "data",
      "file",
      "filegroup"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbFileGroup",
    "popularityRank": 566,
    "synopsis": "Creates new filegroups in SQL Server databases for custom data storage organization.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbFileGroup View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates new filegroups in SQL Server databases for custom data storage organization. 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. Syntax New-DbaDbFileGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-FileGroup] ] [[-FileGroupType] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates the HRFG1 filegroup on the TestDb database on the sqldev1 instance with the default options for the... PS C:\\> New-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 Creates the HRFG1 filegroup on the TestDb database on the sqldev1 instance with the default options for the filegroup. Example 2: Creates a filestream filegroup named HRFG1 on the TestDb database on the sqldev1 instance PS C:\\> New-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -FileGroupType FileStreamDataFileGroup Example 3: Creates a MemoryOptimized data filegroup named HRFG1 on the TestDb database on the sqldev1 instance PS C:\\> New-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -FileGroupType MemoryOptimizedDataFileGroup Example 4: Passes in the TestDB database via pipeline and creates the HRFG1 filegroup on the TestDb database on the... PS C:\\> Get-DbaDatabase -SqlInstance sqldev1 -Database TestDb | New-DbaDbFileGroup -FileGroup HRFG1 Passes in the TestDB database via pipeline and creates the HRFG1 filegroup on the TestDb database on the sqldev1 instance. Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database(s) where the new filegroup will be created. Supports multiple database names for bulk operations. Use this when you need to create the same filegroup structure across multiple databases for consistency. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileGroup Sets the name for the new filegroup being created. The name must be unique within the database and follow SQL Server naming conventions. Use descriptive names like 'HR_Data' or 'Archive_FG' to indicate the data's purpose or department for better organization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 In-Memory OLTP tables. Most scenarios use the default RowsFileGroup unless you're specifically implementing FILESTREAM or In-Memory OLTP features. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | RowsFileGroup | | Accepted Values | 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. Useful when working with multiple databases that match specific criteria rather than specifying database names directly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.FileGroup Returns one FileGroup object per filegroup created. If creation fails or is skipped (e.g., filegroup already exists), no object is returned for that filegroup. Properties (all from SMO FileGroup object with added connection context): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Parent: The parent Database object reference FileGroupType: Type of filegroup (RowsFileGroup, FileStreamFileGroup, or MemoryOptimizedFileGroup) Name: Name of the filegroup (the value specified in -FileGroup parameter) Size: Total size of the filegroup in kilobytes AbsolutePhysicalName: Absolute physical name of the filegroup DefaultFileGroup: Boolean indicating if this is the default filegroup IsDefault: Boolean indicating if this is the default filegroup State: State of the filegroup (Normal, Offline, Defunct) Files: Collection of DataFile objects in the filegroup All properties from the base SMO FileGroup object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaDbMailAccount",
    "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.",
    "category": "Utilities",
    "tags": [
      "databasemail",
      "dbmail",
      "mail"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbMailAccount",
    "popularityRank": 244,
    "synopsis": "Creates a new Database Mail account for sending emails from SQL Server",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbMailAccount View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a new Database Mail account for sending emails from SQL 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. Syntax New-DbaDbMailAccount [-SqlInstance] [[-SqlCredential] ] [-Account] [[-DisplayName] ] [[-Description] ] [-EmailAddress] [[-ReplyToAddress] ] [[-MailServer] ] [[-Port] ] [-EnableSSL] [-UseDefaultCredentials] [[-UserName] ] [[-Password] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new database mail account with the email address admin@ad.local on sql2017 named &quot;The DBA Team&quot;... PS C:\\> $account = New-DbaDbMailAccount -SqlInstance sql2017 -Account 'The DBA Team' -EmailAddress admin@ad.local -MailServer smtp.ad.local Creates 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. Example 2: Creates a new database mail account configured for Office 365 with SSL and authentication on sql2017 PS C:\\> $splatAccount = @{ >> SqlInstance = 'sql2017' >> Account = 'Office365Alerts' >> EmailAddress = 'alerts@company.com' >> MailServer = 'smtp.office365.com' >> Port = 587 >> EnableSSL = $true >> UserName = 'alerts@company.com' >> Password = (ConvertTo-SecureString 'app-password' -AsPlainText -Force) >> } PS C:\\> New-DbaDbMailAccount @splatAccount Example 3: Creates a mail account that uses Windows integrated authentication (the SQL Server service account) for an... PS C:\\> $splatAccount = @{ >> SqlInstance = 'sql2017' >> Account = 'DomainRelay' >> EmailAddress = 'sqlserver@company.local' >> MailServer = 'smtp.company.local' >> UseDefaultCredentials = $true >> } PS C:\\> New-DbaDbMailAccount @splatAccount Creates a mail account that uses Windows integrated authentication (the SQL Server service account) for an internal domain mail relay. Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -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. Choose a descriptive name that identifies the account's purpose, such as 'MaintenanceAlerts' or 'ReportDelivery'. | Property | Value | | --- | --- | | Alias | Name | | Required | True | | Pipeline | false | | Default Value | | -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. Use addresses that recipients will recognize and trust, such as 'sqlserver@company.com' or 'dba-alerts@domain.local'. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DisplayName Sets the friendly name that appears in the 'From' field of outgoing emails. Recipients see this name instead of the raw account name. Defaults to the Account name if not specified. Use descriptive names like 'SQL Server Alerts' or 'DBA Team Notifications'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $Account | -Description Provides optional documentation text describing the account's purpose and usage. This helps other DBAs understand when and how the account should be used. Consider including details like which jobs or applications use this account and any special configuration requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Useful when you want replies to go to a monitored mailbox like 'dba-team@company.com' rather than the automated sender address. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. If not specified, uses the SQL Server instance name as the mail server. The function validates that the mail server exists unless -Force is used. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Port Specifies the TCP port number used to connect to the SMTP server. Common values are 25 (standard SMTP), 465 (SMTPS), and 587 (SMTP with STARTTLS). Use 587 for Office 365 and Gmail which require STARTTLS. If not specified, the default port of 25 is used. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableSSL Enables SSL/TLS encryption for the SMTP connection. Required for connecting to Office 365 (smtp.office365.com:587) and Gmail (smtp.gmail.com:587). When enabled, the connection uses STARTTLS to upgrade to an encrypted connection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UseDefaultCredentials Configures the mail account to use Windows integrated security (the SQL Server service account credentials) for SMTP authentication. Use this for internal mail relays in Windows domains that support Windows Authentication. Cannot be combined with UserName/Password. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UserName Specifies the username for SMTP authentication when connecting to mail servers that require credentials. For Office 365, use the full email address (e.g., 'alerts@company.com'). For Gmail, use the Gmail address. Requires the -Password parameter to be specified as well. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Password Specifies the password for SMTP authentication as a SecureString. Used in combination with -UserName for Basic authentication. Create with: ConvertTo-SecureString 'yourpassword' -AsPlainText -Force For Office 365, use an app-specific password if multi-factor authentication is enabled on the account. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Bypasses the mail server existence validation and creates the Database Mail account even if the specified SMTP server cannot be found or verified. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Mail.MailAccount Returns a newly created MailAccount object from the specified SQL Server instance. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: Unique identifier for the mail account Name: Name of the mail account DisplayName: Friendly name that appears in the 'From' field of emails Description: Description of the account's purpose EmailAddress: Sender email address for outgoing messages ReplyToAddress: Alternate email address for replies IsBusyAccount: Boolean indicating if the account is currently processing emails MailServers: Collection of mail servers associated with this account Additional properties available (from SMO MailAccount object): Parent: Reference to the parent SqlMail object State: Current state of the object (Existing, Creating, Pending, Dropping, etc.) Urn: The Uniform Resource Name of the mail account object All properties from the base SMO object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaDbMailProfile",
    "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.",
    "category": "Utilities",
    "tags": [
      "databasemail",
      "dbmail",
      "mail"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbMailProfile",
    "popularityRank": 278,
    "synopsis": "Creates a new Database Mail profile for organizing SQL Server email notifications",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbMailProfile View Source Ian Lanham (@ilanham) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a new Database Mail profile for organizing SQL Server email notifications 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. Syntax New-DbaDbMailProfile [-SqlInstance] [[-SqlCredential] ] [-Profile] [[-Description] ] [[-MailAccountName] ] [[-MailAccountPriority] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new database mail profile PS C:\\> $profile = New-DbaDbMailProfile -SqlInstance sql2017 -Profile 'The DBA Team' Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Profile Specifies the name for the new Database Mail profile. Profile names must be unique within each SQL Server instance. Use descriptive names like 'DBA Alerts', 'Application Notifications', or 'Backup Reports' to organize different types of email notifications. | Property | Value | | --- | --- | | Alias | Name | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Description Provides a detailed description explaining the purpose or intended use of the Database Mail profile. This helps document what types of emails will be sent through this profile, making it easier for other DBAs to understand the profile's purpose. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MailAccountName Specifies an existing Database Mail account to associate with this profile during creation. The mail account must already exist on the SQL Server instance and will be used to send emails through this profile. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MailAccountPriority Sets the priority level for the associated mail account within the profile, with 1 being the highest priority. Lower priority accounts serve as failover options when higher priority accounts are unavailable. Defaults to 1 if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Mail.MailProfile Returns one MailProfile object for the Database Mail profile that was created. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: The unique identifier for the Database Mail profile Name: The name of the Database Mail profile Description: The description of the Database Mail profile (if provided) IsBusyProfile: Boolean indicating if the profile is currently processing mail Additional properties available (from SMO MailProfile object): Parent: Reference to parent SqlMail object Urn: The Uniform Resource Name of the profile State: Current state of the object (Existing, Creating, etc.) MailAccountMemberships: Collection of mail accounts associated with this profile &nbsp;"
  },
  {
    "name": "New-DbaDbMaskingConfig",
    "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",
    "category": "Utilities",
    "tags": [
      "masking",
      "datamasking"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbMaskingConfig",
    "popularityRank": 219,
    "synopsis": "Scans database tables to detect sensitive data and creates a JSON configuration file for data masking",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbMaskingConfig View Source Sander Stad (@sqlstad, sqlstad.nl) , Chrissy LeMaire (@cl, netnerds.net) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Scans database tables to detect sensitive data and creates a JSON configuration file for data masking 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. The 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. The 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. Note that the following column and data types are not currently supported: Identity ForeignKey Computed Hierarchyid Geography Geometry Xml Read more here: https://sachabarbs.wordpress.com/2018/06/11/bogus-simple-fake-data-tool/ https://github.com/bchavez/Bogus Syntax New-DbaDbMaskingConfig [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Table] ] [[-Column] ] [-Path] [[-Locale] ] [[-CharacterString] ] [[-SampleCount] ] [[-KnownNameFilePath] ] [[-PatternFilePath] ] [-ExcludeDefaultKnownName] [-ExcludeDefaultPattern] [-Force] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Process all tables and columns for database DB1 on instance SQLDB1 PS C:\\> New-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Path C:\\Temp\\clone Example 2: Process only table Customer with all the columns PS C:\\> New-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Table Customer -Path C:\\Temp\\clone Example 3: Process only table Customer and only the column named &quot;City&quot; PS C:\\> New-DbaDbMaskingConfig -SqlInstance SQLDB1 -Database DB1 -Table Customer -Column City -Path C:\\Temp\\clone Required Parameters -Path Path where to save the generated JSON files. Th naming convention will be \"servername.databasename.tables.json\" | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Databases to process through | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Tables to process. By default all the tables will be processed | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Column Columns to process. By default all the columns will be processed | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Locale Set the local to enable certain settings in the masking | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | en | -CharacterString The characters to use in string data. 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' by default | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 | -SampleCount Amount of rows to sample to make an assessment. The default is 100 | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 100 | -KnownNameFilePath Points to a file containing the custom known names | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PatternFilePath Points to a file containing the custom patterns | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDefaultKnownName Excludes the default known names | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeDefaultPattern Excludes the default patterns | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Forcefully execute commands when needed | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Used for piping the values from Invoke-DbaDbPiiScan | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.IO.FileInfo Returns 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 no sensitive data is detected, nothing is returned. File naming convention: Default: \"servername.databasename.DataMaskingConfig.json\" With table filter (1-4 tables): \"servername.databasename.table1-table2.DataMaskingConfig.json\" With table filter (5+ tables): \"servername.databasename.Tables_yyyyMMddHHmmss.DataMaskingConfig.json\" The returned FileInfo object includes standard properties: Name: The generated filename FullName: The complete file path Length: File size in bytes CreationTime: When the configuration file was created LastWriteTime: When the configuration file was last modified The JSON file structure contains: Name: Database name Type: \"DataMaskingConfiguration\" Tables: Array of table objects, each containing: Name: Table name Schema: Table schema Columns: Array of column masking specifications HasUniqueIndex: Boolean indicating if table has unique indexes FilterQuery: Optional query to filter which rows get masked This configuration file is consumed by Invoke-DbaDbDataMasking to perform the actual data masking operations. &nbsp;"
  },
  {
    "name": "New-DbaDbMasterKey",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbMasterKey",
    "popularityRank": 433,
    "synopsis": "Creates a database master key for encryption operations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbMasterKey View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a database master key for encryption operations 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. Syntax New-DbaDbMasterKey [[-SqlInstance] ] [[-SqlCredential] ] [[-Credential] ] [[-Database] ] [[-SecurePassword] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: You will be prompted to securely enter your password, then a master key will be created in the master... PS C:\\> New-DbaDbMasterKey -SqlInstance Server1 You 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. Example 2: You will be prompted by a credential interface to securely enter your password, then a master key will be... PS C:\\> New-DbaDbMasterKey -SqlInstance Server1 -Credential usernamedoesntmatter You 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. Example 3: Suppresses all prompts to install but prompts in th console to securely enter your password and creates a... PS C:\\> New-DbaDbMasterKey -SqlInstance Server1 -Database db1 -Confirm:$false Suppresses all prompts to install but prompts in th console to securely enter your password and creates a master key in the 'db1' database Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Provides an alternative way to supply the master key password using a PSCredential object. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database where the master key will be created. Defaults to master database if not specified. Use this when implementing encryption features like TDE or Always Encrypted in specific user databases rather than just the system master database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | master | -SecurePassword Provides the password used to encrypt the database master key as a SecureString object. If not specified, you'll 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. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from the pipeline, typically from Get-DbaDatabase. Use this when you want to create master keys across multiple databases in a single pipeline operation or when working with pre-filtered database collections. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.MasterKey Returns one MasterKey object for the database where the master key was created. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name where the master key was created CreateDate: DateTime when the master key was created DateLastModified: DateTime when the master key was last modified IsEncryptedByServer: Boolean indicating if the master key is encrypted by the server Additional properties available (from SMO MasterKey object): Urn: The Uniform Resource Name of the master key State: Current state of the object (Existing, Creating, etc.) Parent: Reference to parent database object &nbsp;"
  },
  {
    "name": "New-DbaDbRole",
    "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.",
    "category": "Utilities",
    "tags": [
      "role",
      "user"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbRole",
    "popularityRank": 249,
    "synopsis": "Creates new database roles in one or more SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbRole View Source Claudio Silva (@ClaudioESSilva), claudioessilva.eu Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates new database roles in one or more SQL Server databases. 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. Syntax New-DbaDbRole [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Role] ] [[-Owner] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Will create a new role named dbExecuter within db1 on sql2017a instance PS C:\\> New-DbaDbRole -SqlInstance sql2017a -Database db1 -Role 'dbExecuter' Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to create the new role(s) in. Accepts wildcards for pattern matching. Use this when you need to create roles in specific databases instead of all databases on the instance. If unspecified, the role will be created in all accessible databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to exclude from role creation when processing all databases. Use this to skip system databases or specific user databases where the role shouldn't be created. Particularly useful when creating standardized roles across most but not all databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Role Specifies the name(s) of the custom database role(s) to create. Use meaningful names that reflect the role's intended permissions like 'AppReadOnly' or 'ReportUsers'. The function will create each specified role in all target databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Owner Specifies the database principal that will own the new role. Defaults to 'dbo' if not specified. Use this when you need a specific user or role to own the new database role for security or organizational requirements. The owner must exist in each target database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase for role creation. Use this for advanced filtering or when working with databases from multiple instances. This parameter allows you to chain Get-DbaDatabase with specific filters before creating roles. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.DatabaseRole Returns one DatabaseRole object for each role created. One role is created per Role parameter value in each target database. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the newly created database role Parent: The name of the database containing the role Owner: The database principal that owns the role (dbo by default, or custom owner if specified) Additional properties available (from SMO DatabaseRole object): ID: Unique identifier for the role CreateDate: DateTime when the role was created DateLastModified: DateTime when the role was last modified All properties from the base SMO DatabaseRole object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaDbSchema",
    "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.",
    "category": "Database Operations",
    "tags": [
      "schema",
      "database"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbSchema",
    "popularityRank": 483,
    "synopsis": "Creates new database schemas with specified ownership for organizing objects and implementing security boundaries.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbSchema View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates new database schemas with specified ownership for organizing objects and implementing security boundaries. 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. Syntax New-DbaDbSchema [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Schema] ] [[-SchemaOwner] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates the TestSchema1 schema in the example1 database in the localhost instance PS C:\\> New-DbaDbSchema -SqlInstance localhost -Database example1 -Schema TestSchema1 Creates the TestSchema1 schema in the example1 database in the localhost instance. The dbo user will be the owner of the schema. Example 2: Creates the TestSchema1 and TestSchema2 schemas in the example1 database in the localhost instance and... PS C:\\> New-DbaDbSchema -SqlInstance localhost -Database example1 -Schema TestSchema1, TestSchema2 -SchemaOwner dbatools Creates the TestSchema1 and TestSchema2 schemas in the example1 database in the localhost instance and assigns the dbatools user as the owner of the schemas. Example 3: Creates the TestSchema1 and TestSchema2 schemas in the example1 database in the localhost and... PS C:\\> New-DbaDbSchema -SqlInstance localhost, localhost\\sql2017 -Database example1 -Schema TestSchema1, TestSchema2 -SchemaOwner dbatools Creates 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. Example 4: Passes in the example1 db via pipeline and creates the TestSchema1 and TestSchema2 schemas and assigns the... PS C:\\> Get-DbaDatabase -SqlInstance localhost, localhost\\sql2017 -Database example1 | New-DbaDbSchema -Schema TestSchema1, TestSchema2 -SchemaOwner dbatools Passes in the example1 db via pipeline and creates the TestSchema1 and TestSchema2 schemas and assigns the dbatools user as the owner of the schemas. Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target database(s) where the new schemas will be created. Accepts multiple database names. Required when using SqlInstance parameter, and supports wildcards for pattern matching across database names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Specifies the name(s) of the schema(s) to create within the target databases. Accepts multiple schema names for batch creation. Schema names must be valid SQL Server identifiers and will fail if they already exist in the target database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SchemaOwner Specifies the database user who will own the created schema(s). Must be an existing user in the target database. When omitted, the schema owner defaults to 'dbo'. Use this to implement security boundaries or assign schemas to application users. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase via pipeline input, eliminating the need to specify SqlInstance and Database parameters. Use this approach when you need to work with a pre-filtered set of databases or want to chain multiple dbatools commands together. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Schema Returns one Schema object for each schema created. One schema is created per Schema parameter value in each target database. Properties: Name: The name of the newly created schema Owner: The database user that owns the schema (dbo by default, or custom owner if SchemaOwner is specified) Parent: Reference to the parent Database object CreateDate: DateTime when the schema was created State: The current state of the schema object (Existing, Creating, Pending, etc.) Urn: The Uniform Resource Name of the schema object All properties from the base SMO Schema object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaDbSequence",
    "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't exist and supports SQL Server 2012 and higher.",
    "category": "Utilities",
    "tags": [
      "data",
      "sequence",
      "table"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbSequence",
    "popularityRank": 663,
    "synopsis": "Creates a new sequence object in SQL Server databases with configurable properties and data types.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbSequence View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a new sequence object in SQL Server databases with configurable properties and data types. 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't exist and supports SQL Server 2012 and higher. Syntax New-DbaDbSequence [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [-Sequence] [[-Schema] ] [[-IntegerType] ] [[-StartWith] ] [[-IncrementBy] ] [[-MinValue] ] [[-MaxValue] ] [-Cycle] [[-CacheSize] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new sequence TestSequence in the TestDB database on the sqldev01 instance PS C:\\> New-DbaDbSequence -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence -StartWith 10000 -IncrementBy 10 Creates a new sequence TestSequence in the TestDB database on the sqldev01 instance. The sequence will start with 10000 and increment by 10. Example 2: Creates a new sequence TestSequence in the TestDB database on the sqldev01 instance PS C:\\> New-DbaDbSequence -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence -Cycle Creates a new sequence TestSequence in the TestDB database on the sqldev01 instance. The sequence will cycle the numbers. Example 3: Using a pipeline this command creates a new bigint sequence named TestSchema.TestSequence in the TestDB... PS C:\\> Get-DbaDatabase -SqlInstance sqldev01 -Database TestDB | New-DbaDbSequence -Sequence TestSequence -Schema TestSchema -IntegerType bigint Using a pipeline this command creates a new bigint sequence named TestSchema.TestSequence in the TestDB database on the sqldev01 instance. Required Parameters -Sequence Specifies the name of the sequence object to create. Must be unique within the target schema. Use descriptive names like 'OrderNumber' or 'InvoiceID' to indicate the sequence's purpose. | Property | Value | | --- | --- | | Alias | Name | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target database(s) where the sequence will be created. Accepts multiple database names. Required when using SqlInstance parameter to specify which databases should contain the new sequence. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Specifies the schema where the sequence will be created. Defaults to 'dbo' if not specified. The function will automatically create the schema if it doesn't exist in the target database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | dbo | -IntegerType Specifies the data type for the sequence values. Defaults to 'bigint' for maximum range. Supports system types (tinyint, smallint, int, bigint) and user-defined integer types using 'schema.typename' format. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | bigint | -StartWith Sets the initial value for the sequence. Defaults to 1 if not specified. Use higher starting values like 10000 when you need to reserve lower numbers or maintain existing numbering schemes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1 | -IncrementBy Controls how much the sequence increases with each call to NEXT VALUE FOR. Defaults to 1. Use negative values for descending sequences or larger increments like 10 for spaced numbering. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 1 | -MinValue Sets the lowest value the sequence can generate. When omitted, uses the data type's minimum value. Specify this to prevent sequences from generating values below a certain threshold. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaxValue Sets the highest value the sequence can generate. When omitted, uses the data type's maximum value. Define this to limit sequence values or enable cycling at a specific upper bound. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Cycle Enables the sequence to restart from MinValue after reaching MaxValue (or vice versa for descending sequences). Use this for sequences that should continuously cycle through a range of values rather than stopping at the boundary. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CacheSize Controls how many sequence values SQL Server pre-allocates in memory for performance. Set to 0 for NO CACHE. Higher cache sizes improve performance for frequently accessed sequences but may cause gaps if the instance restarts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -InputObject Accepts database objects from Get-DbaDatabase via pipeline input. Use this for pipeline operations when you want to create sequences across multiple databases returned by Get-DbaDatabase. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Sequence Returns one Sequence object for each sequence successfully created. The returned object represents the newly created SQL Server sequence definition with its configuration properties. Default display properties (via Select-DefaultView): ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database containing the sequence Schema: The schema where the sequence is created Name: The name of the sequence object DataType: The data type of values the sequence will generate (e.g., bigint, int, tinyint, smallint) StartValue: The initial value the sequence will return on first use IncrementValue: The amount the sequence will increase (or decrease if negative) with each NEXT VALUE FOR call Additional properties available (from SMO Sequence object): CurrentValue: The current value that will be returned by the next NEXT VALUE FOR call MinValue: The minimum value the sequence can generate MaxValue: The maximum value the sequence can generate IsCycleEnabled: Boolean indicating whether the sequence will cycle from MaxValue back to MinValue CacheSize: The number of sequence values pre-allocated in memory (0 means no cache) SequenceCacheType: The cache behavior setting (DefaultCache, NoCache, or CacheWithSize) Parent: Reference to the parent Database SMO object Urn: The Uniform Resource Name (URN) identifying the sequence in the SMO object hierarchy State: The state of the SMO object (Existing, Creating, Altering, Dropping, etc.) All properties from the base SMO Sequence object are accessible even though only default properties are displayed without using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaDbSnapshot",
    "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.",
    "category": "Database Operations",
    "tags": [
      "snapshot",
      "restore",
      "database"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbSnapshot",
    "popularityRank": 269,
    "synopsis": "Creates database snapshots for point-in-time recovery and testing scenarios",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbSnapshot View Source Simone Bizzotto (@niphold) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates database snapshots for point-in-time recovery and testing scenarios 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. The 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. Syntax New-DbaDbSnapshot [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-AllDatabases] [[-Name] ] [[-NameSuffix] ] [[-Path] ] [-Force] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates snapshot for HR and Accounting, returning a custom object displaying Server, Database... PS C:\\> New-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting Creates snapshot for HR and Accounting, returning a custom object displaying Server, Database, DatabaseCreated, SnapshotOf, SizeMB, DatabaseCreated, PrimaryFilePath, Status, Notes Example 2: Creates snapshot named &quot;HR_snap&quot; for HR PS C:\\> New-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR -Name HR_snap Example 3: Creates snapshot named &quot;fool_HR_snap&quot; for HR PS C:\\> New-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR -NameSuffix 'fool_{0}_snap' Example 4: Creates snapshots for HR and Accounting databases, storing files under the F:\\snapshotpath\\ dir PS C:\\> New-DbaDbSnapshot -SqlInstance sqlserver2014a -Database HR, Accounting -Path F:\\snapshotpath Example 5: Creates a snapshot for the database df on sql2016 PS C:\\> Get-DbaDatabase -SqlInstance sql2016 -Database df | New-DbaDbSnapshot Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to create snapshots for. Accepts an array of database names. Use this when you need snapshots for specific databases rather than all databases on the instance. Cannot be used together with AllDatabases parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from snapshot creation when using AllDatabases. Useful when you want to snapshot most databases but skip certain ones like development or staging databases. Accepts an array of database names to exclude from the operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllDatabases Creates snapshots for all user databases on the instance that support snapshotting. Automatically excludes system databases (master, model, tempdb), snapshots, and databases with memory-optimized filegroups. Use this when you need to create snapshots for disaster recovery or before major maintenance operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Name Sets a custom name for the database snapshot. Only works when targeting a single database. Use this when you need a meaningful snapshot name like 'Sales_PreUpgrade' instead of the default timestamped name. For multiple databases, use NameSuffix parameter instead to avoid naming conflicts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NameSuffix Customizes the suffix appended to database names when creating snapshots. Defaults to yyyyMMdd_HHmmss format. Use simple strings like '_PrePatch' or templates with {0} placeholder where {0} represents the database name. Examples: '_BeforeMaintenance' creates 'HR_BeforeMaintenance', or 'Snap_{0}_v1' creates 'Snap_HR_v1'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory where snapshot files will be stored. Defaults to the same location as the source database files. Use this when you need snapshots on different storage for performance or capacity reasons. The SQL Server service account must have write access to the specified path. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Creates partial snapshots for databases containing FILESTREAM filegroups. FILESTREAM data is excluded and marked offline in the snapshot. Use this when you need to snapshot databases with FILESTREAM for testing or point-in-time analysis of non-FILESTREAM data. Warning: Databases cannot be restored from partial snapshots due to the missing FILESTREAM data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database objects from Get-DbaDatabase for pipeline operations. Enables scenarios like filtering databases with specific criteria before creating snapshots. Example: Get-DbaDatabase -SqlInstance sql01 | Where-Object Size -gt 1000 | New-DbaDbSnapshot | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts for confirmation of every step. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Database Returns one Database object for each snapshot successfully created. The returned object represents the newly created database snapshot with its configuration and usage properties. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the database snapshot SnapshotOf: The name of the base database from which this snapshot was created (alias for DatabaseSnapshotBaseName) CreateDate: DateTime when the snapshot was created DiskUsage: The amount of disk space consumed by the snapshot (formatted as dbasize object: KB, MB, GB, TB, etc.) Additional properties available (from SMO Database object): DatabaseSnapshotBaseName: The name of the source database IsDatabaseSnapshot: Boolean indicating if the database is a snapshot (always $true for snapshots) SnapshotIsolationState: Snapshot isolation setting DatabaseGuid: Unique identifier for the database Owner: Database owner login name Compatibility: Database compatibility level IsAccessible: Boolean indicating if the snapshot is accessible Status: Current status of the snapshot database Collation: The database collation All properties from the base SMO Database object are accessible via Select-Object * even though only default properties are displayed without using the -Property parameter. &nbsp;"
  },
  {
    "name": "New-DbaDbSynonym",
    "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.",
    "category": "Database Operations",
    "tags": [
      "synonym",
      "database"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbSynonym",
    "popularityRank": 607,
    "synopsis": "Creates database synonyms to provide alternate names for tables, views, procedures, and other database objects.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbSynonym View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates database synonyms to provide alternate names for tables, views, procedures, and other database objects. 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. Syntax New-DbaDbSynonym [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Synonym] ] [[-Schema] ] [[-BaseServer] ] [[-BaseDatabase] ] [[-BaseSchema] ] [-BaseObject] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Will create a new synonym named synObj1 in db1 database in dbo schema on sql2017a instance for Obj1 object in... PS C:\\> New-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Synonym synObj1 -BaseObject Obj1 Will create a new synonym named synObj1 in db1 database in dbo schema on sql2017a instance for Obj1 object in the same database. Example 2: Will create a new synonym named synObj1 in db1 database in dbo schema on sql2017a instance for Obj1 object in... PS C:\\> New-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Synonym synObj1 -BaseObject Obj1 Will create a new synonym named synObj1 in db1 database in dbo schema on sql2017a instance for Obj1 object in the same database. Example 3: Will create a new synonym named synObj1 within dbo schema in db1 database on sql2017a instance for Obj1... PS C:\\> New-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Schema sch1 -Synonym synObj1 -BaseObject Obj1 Will create a new synonym named synObj1 within dbo schema in db1 database on sql2017a instance for Obj1 object in the same database. Example 4: Will create a new synonym named synObj1 within sch1 schema in db1 database on sql2017a instance for Obj1... PS C:\\> New-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Schema sch1 -Synonym synObj1 -BaseObject Obj1 -BaseSchema bSch2 Will 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. Example 5: Will create a new synonym named synObj1 within sch1 schema in db1 database on sql2017a instance for Obj1... PS C:\\> New-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Schema sch1 -Synonym synObj1 -BaseObject Obj1 -BaseSchema bSch2 -BaseDatabase bDb3 Will create a new synonym named synObj1 within sch1 schema in db1 database on sql2017a instance for Obj1 object within bSch2 schema in bDb3 database. Example 6: Will create a new synonym named synObj1 within sch1 schema in db1 database on sql2017a instance for Obj1... PS C:\\> New-DbaDbSynonym -SqlInstance sql2017a -Database db1 -Schema sch1 -Synonym synObj1 -BaseObject Obj1 -BaseSchema bSch2 -BaseDatabase bDb3 -BaseServer bSrv4 Will 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. Example 7: Will create a new synonym named synObj1 within dbo schema in all user databases on sql2017a instance for Obj1... PS C:\\> Get-DbaDatabase -SqlInstance sql2017a -ExcludeSystem | New-DbaDbSynonym -Synonym synObj1 -BaseObject Obj1 Will create a new synonym named synObj1 within dbo schema in all user databases on sql2017a instance for Obj1 object in the respective databases. Required Parameters -BaseObject The name of the database object that the synonym will reference. Supports tables, views, stored procedures, functions, and other schema-scoped objects. This is the actual object that users will access through the synonym name, enabling abstraction and simplified references. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to create the synonym in. Accepts wildcards for pattern matching. When omitted, synonyms will be created in all accessible databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from synonym creation when processing multiple databases. Useful when you want to create synonyms across most databases but skip system databases or specific user databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Synonym The name of the synonym to create. This becomes the alternate name that applications and users will reference. Choose meaningful names that follow your organization's naming conventions and make object access more intuitive. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema The schema where the synonym will be created. Defaults to 'dbo' if not specified. Consider using application-specific schemas to organize synonyms logically and control access through schema permissions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | dbo | -BaseServer The linked server name when creating cross-server synonyms. Requires BaseDatabase and BaseSchema parameters. Use this to create synonyms that reference objects on remote SQL Server instances through established linked server connections. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BaseDatabase The database containing the target object that the synonym will reference. Requires BaseSchema when specified. Use this for cross-database synonyms or when creating synonyms on linked servers to reference objects in specific databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -BaseSchema The schema containing the target object that the synonym will reference. Required when BaseDatabase is specified, ensuring the synonym points to the correct object in complex multi-schema environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase for creating synonyms across multiple databases. Useful for batch operations when you need to create the same synonym in multiple databases selected by specific criteria. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Synonym Returns one Synonym object for each synonym created. The object includes added properties from the parent SQL Server and database objects for connection context. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the synonym (ParentName) Name: The name of the synonym Schema: The schema where the synonym is created (default: dbo) BaseServer: The linked server name for cross-server synonyms, or null for same-server synonyms BaseDatabase: The target database for the synonym reference, or null if referencing same database BaseSchema: The target schema for the synonym reference BaseObject: The name of the database object the synonym references Additional properties available (from SMO Synonym object): CreateDate: DateTime when the synonym was created Urn: The Uniform Resource Name of the synonym object State: The current state of the SMO object (Existing, Creating, etc.) Parent: Reference to the parent database object All properties from the base SMO Synonym object are accessible using Select-Object * even though only the default properties are displayed by default. &nbsp;"
  },
  {
    "name": "New-DbaDbTable",
    "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't exist, it will be created automatically.",
    "category": "Utilities",
    "tags": [
      "table"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbTable",
    "popularityRank": 182,
    "synopsis": "Creates database tables with columns and constraints using PowerShell hashtables or SMO objects",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbTable View Source Chrissy LeMaire (@cl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates database tables with columns and constraints using PowerShell hashtables or SMO objects 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't exist, it will be created automatically. Syntax New-DbaDbTable [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Name] ] [[-Schema] ] [[-ColumnMap] ] [[-ColumnObject] ] [-AnsiNullsStatus] [-ChangeTrackingEnabled] [[-DataSourceName] ] [[-Durability] {SchemaOnly | SchemaAndData}] [[-ExternalTableDistribution] {Sharded | Replicated | RoundRobin | None}] [[-FileFormatName] ] [[-FileGroup] ] [[-FileStreamFileGroup] ] [[-FileStreamPartitionScheme] ] [[-FileTableDirectoryName] ] [[-FileTableNameColumnCollation] ] [-FileTableNamespaceEnabled] [[-HistoryTableName] ] [[-HistoryTableSchema] ] [-IsExternal] [-IsFileTable] [-IsMemoryOptimized] [-IsSystemVersioned] [[-Location] ] [[-LockEscalation] {Table | Disable | Auto}] [[-Owner] ] [[-PartitionScheme] ] [-QuotedIdentifierStatus] [[-RejectSampleValue] ] [[-RejectType] {Value | Percentage | None}] [[-RejectValue] ] [[-RemoteDataArchiveDataMigrationState] {Disabled | PausedOutbound | PausedInbound | Outbound | Inbound | Paused}] [-RemoteDataArchiveEnabled] [[-RemoteDataArchiveFilterPredicate] ] [[-RemoteObjectName] ] [[-RemoteSchemaName] ] [[-RemoteTableName] ] [-RemoteTableProvisioned] [[-ShardingColumnName] ] [[-TextFileGroup] ] [-TrackColumnsUpdatedEnabled] [[-HistoryRetentionPeriod] ] [[-HistoryRetentionPeriodUnit] {Day | Week | Month | Year | Undefined | Infinite}] [[-DwTableDistribution] {Undefined | None | Hash | Replicate | RoundRobin}] [[-RejectedRowLocation] ] [-OnlineHeapOperation] [[-LowPriorityMaxDuration] ] [-DataConsistencyCheck] [[-LowPriorityAbortAfterWait] {None | Blockers | Self}] [[-MaximumDegreeOfParallelism] ] [-IsNode] [-IsEdge] [-IsVarDecimalStorageFormatEnabled] [-Passthru] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new table on sql2017 in tempdb with the name testtable and one column PS C:\\> $col = @{ >> Name = 'test' >> Type = 'varchar' >> MaxLength = 20 >> Nullable = $true >> } PS C:\\> New-DbaDbTable -SqlInstance sql2017 -Database tempdb -Name testtable -ColumnMap $col Example 2: Creates a new table on sql2017 in tempdb with the name testtable and two columns PS C:\\> $cols = @( ) >> $cols += @{ >> Name = 'Id' >> Type = 'varchar' >> MaxLength = 36 >> DefaultExpression = 'NEWID()' >> } >> $cols += @{ >> Name = 'Since' >> Type = 'datetime2' >> DefaultString = '2021-12-31' >> } PS C:\\> New-DbaDbTable -SqlInstance sql2017 -Database tempdb -Name testtable -ColumnMap $cols Creates a new table on sql2017 in tempdb with the name testtable and two columns. Uses \"DefaultExpression\" to interpret the value \"NEWID()\" as an expression regardless of the data type of the column. Uses \"DefaultString\" to interpret the value \"2021-12-31\" as a string regardless of the data type of the column. Example 3: Creates a new table on sql2017 in tempdb with the name testtable and ten columns PS C:\\> # Create collection >> $cols = @() >> # Add columns to collection >> $cols += @{ >> Name = 'testId' >> Type = 'int' >> Identity = $true >> } >> $cols += @{ >> Name = 'test' >> Type = 'varchar' >> MaxLength = 20 >> Nullable = $true >> } >> $cols += @{ >> Name = 'test2' >> Type = 'int' >> Nullable = $false >> } >> $cols += @{ >> Name = 'test3' >> Type = 'decimal' >> MaxLength = 9 >> Nullable = $true >> } >> $cols += @{ >> Name = 'test4' >> Type = 'decimal' >> Precision = 8 >> Scale = 2 >> Nullable = $false >> } >> $cols += @{ >> Name = 'test5' >> Type = 'Nvarchar' >> MaxLength = 50 >> Nullable = $false >> Default = 'Hello' >> DefaultName = 'DF_Name_test5' >> } >> $cols += @{ >> Name = 'test6' >> Type = 'int' >> Nullable = $false >> Default = '0' >> } >> $cols += @{ >> Name = 'test7' >> Type = 'smallint' >> Nullable = $false >> Default = 100 >> } >> $cols += @{ >> Name = 'test8' >> Type = 'Nchar' >> MaxLength = 3 >> Nullable = $false >> Default = 'ABC' >> } >> $cols += @{ >> Name = 'test9' >> Type = 'char' >> MaxLength = 4 >> Nullable = $false >> Default = 'XPTO' >> } >> $cols += @{ >> Name = 'test10' >> Type = 'datetime' >> Nullable = $false >> Default = 'GETDATE()' >> } PS C:\\> New-DbaDbTable -SqlInstance sql2017 -Database tempdb -Name testtable -ColumnMap $cols Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database where the new table will be created. Accepts multiple database names to create the same table across several databases. Use this when you need to deploy identical table structures to multiple databases in your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies the name for the new table. Must be a valid SQL Server identifier. You can also pass a bracket-quoted name or a two-part schema.table name. Specify the target database with -Database or by piping in a database object. Use standard naming conventions like avoiding spaces and reserved keywords for better maintainability. | Property | Value | | --- | --- | | Alias | Table | | Required | False | | Pipeline | false | | Default Value | | -Schema Specifies the schema where the table will be created. Defaults to 'dbo' if not specified. Use this to organize tables by functional area or security requirements. The schema will be created automatically if it doesn't exist. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | dbo | -ColumnMap Defines table columns using PowerShell hashtables with properties like Name, Type, MaxLength, Nullable, Default, Identity, etc. This is the primary method for specifying column structure when you need simple, declarative table creation. See examples for supported hashtable properties. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ColumnObject Accepts pre-built SMO Column objects for advanced scenarios requiring complex column configurations. Use this when you need features not supported by ColumnMap hashtables, such as computed columns or advanced constraints. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AnsiNullsStatus Controls ANSI_NULLS setting for the table, affecting how null comparisons are handled in queries. Enable this to ensure ANSI-compliant null handling behavior, which is recommended for modern applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ChangeTrackingEnabled Enables SQL Server Change Tracking on the table to monitor data modifications. Use this when you need to track which rows have been inserted, updated, or deleted for synchronization scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DataSourceName Specifies the external data source name for external tables in SQL Server 2016+ or Azure SQL. Required when creating external tables that reference data in Hadoop, Azure Blob Storage, or other external systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Durability Sets the durability level for memory-optimized tables (SCHEMA_AND_DATA or SCHEMA_ONLY). Use SCHEMA_ONLY for temporary data that doesn't need to persist across server restarts, or SCHEMA_AND_DATA for permanent memory-optimized tables. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExternalTableDistribution Specifies the distribution method for external tables in Azure SQL Data Warehouse or Parallel Data Warehouse. Choose between HASH, ROUND_ROBIN, or REPLICATE based on your query patterns and data size requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileFormatName Specifies the external file format name for external tables that read from files. Required when creating external tables that reference structured files like CSV, Parquet, or ORC in external storage systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileGroup Specifies the filegroup where the table data will be stored. Defaults to the database's default filegroup. Use this to control storage placement for performance optimization or to separate tables across different storage devices. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileStreamFileGroup Specifies the FILESTREAM filegroup for tables that store large binary data as files. Required when creating tables with FILESTREAM columns for storing documents, images, or other large binary objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileStreamPartitionScheme Specifies the partition scheme for FILESTREAM data in partitioned tables. Use this when you need to partition FILESTREAM data across multiple filegroups for performance or maintenance benefits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileTableDirectoryName Sets the directory name for FileTable functionality, allowing Windows file system access to table data. Specify a meaningful name that will appear as a folder in the Windows file system when accessing the table through the file share. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileTableNameColumnCollation Specifies the collation for the name column in FileTable to control file name sorting and comparison. Use a case-insensitive collation for Windows-compatible file name handling in FileTable scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileTableNamespaceEnabled Enables the FileTable namespace, allowing file system access through Windows APIs. Set to true when you want applications to access table data through standard file operations like copy, move, and delete. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -HistoryTableName Specifies the name of the history table for system-versioned temporal tables. Required when creating temporal tables that automatically track all data changes for point-in-time queries and auditing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -HistoryTableSchema Specifies the schema for the history table in system-versioned temporal tables. Use this to organize history tables in a separate schema for better security and maintenance separation from current data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IsExternal Creates an external table that references data stored outside SQL Server. Use this for querying data in Azure Blob Storage, Hadoop, or other external systems without importing the data into SQL Server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IsFileTable Creates a FileTable that combines relational data with Windows file system access. Enable this when you need applications to store and manage documents through both T-SQL and standard Windows file operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IsMemoryOptimized Creates an In-Memory OLTP table stored entirely in memory for high-performance scenarios. Use this for tables requiring extremely high transaction throughput with low latency, typically in OLTP workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IsSystemVersioned Creates a temporal table that automatically tracks all data changes with system-generated timestamps. Enable this for auditing requirements or when you need to query historical versions of data at any point in time. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Location Specifies the location path for external tables pointing to files or directories. Required for external tables to define where the actual data files are stored in the external system. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LockEscalation Controls when SQL Server escalates row or page locks to table locks (TABLE, AUTO, or DISABLE). Set to DISABLE for high-concurrency scenarios where table-level locks would cause blocking, or AUTO for default behavior. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Owner Specifies the table owner, typically a database user or role with appropriate permissions. Use this to set explicit ownership for security or administrative purposes, though schema-contained objects are generally preferred. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PartitionScheme Specifies the partition scheme for horizontally partitioning large tables across multiple filegroups. Use this for very large tables to improve query performance and enable parallel maintenance operations on partition boundaries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -QuotedIdentifierStatus Controls QUOTED_IDENTIFIER setting for the table, affecting how double quotes are interpreted in queries. Enable this to use double quotes for identifiers containing spaces or reserved words, following ANSI SQL standards. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -RejectSampleValue Sets the sample size for reject value calculations in external tables with error handling. Specify the number of rows to sample when determining if reject thresholds have been exceeded during external data access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RejectType Defines how reject values are calculated for external tables (VALUE or PERCENTAGE). Use VALUE for absolute row count limits or PERCENTAGE for proportional error thresholds when accessing external data sources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RejectValue Sets the maximum number or percentage of rejected rows allowed when querying external tables. Configure this to control query behavior when encountering data quality issues in external data sources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RemoteDataArchiveDataMigrationState Controls the data migration state for Stretch Database tables (INBOUND, OUTBOUND, or PAUSED). Use this to manage how historical data is migrated between on-premises SQL Server and Azure SQL Database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RemoteDataArchiveEnabled Enables Stretch Database functionality to automatically migrate cold data to Azure SQL Database. Use this for tables with historical data that can be moved to lower-cost cloud storage while remaining queryable. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -RemoteDataArchiveFilterPredicate Defines the filter function determining which rows are eligible for Stretch Database migration. Specify a function that returns 1 for rows to migrate, typically based on date criteria for archiving old data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RemoteObjectName Specifies the name of the remote table or object for Stretch Database or external table scenarios. Use this when the remote table name differs from the local table name in federated or hybrid configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RemoteSchemaName Specifies the schema name in the remote database for Stretch Database tables. Define this when the remote Azure SQL Database uses a different schema structure than your local database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RemoteTableName Sets the table name in the remote Azure SQL Database for Stretch Database functionality. Specify this when you want the archived data to use a different table name in the cloud storage location. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RemoteTableProvisioned Indicates whether the remote table for Stretch Database has already been created in Azure SQL Database. Set to true if the remote table structure already exists, preventing automatic provisioning during setup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ShardingColumnName Specifies the column used for sharding data distribution in Azure SQL Database elastic pools. Define the column that determines how rows are distributed across multiple database shards for horizontal scaling. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TextFileGroup Specifies the filegroup for storing text, ntext, and image columns in SQL Server versions before 2016. Use this for legacy applications requiring separate storage for large text data, though newer data types are recommended. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TrackColumnsUpdatedEnabled Enables column-level change tracking to identify which specific columns were modified. Use this when you need granular change information beyond just knowing that a row was updated, useful for selective synchronization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -HistoryRetentionPeriod Sets the retention period for temporal table history data before automatic cleanup. Specify the number of time units (days, months, years) to retain historical data for compliance and storage management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -HistoryRetentionPeriodUnit Defines the time unit for history retention period (DAYS, WEEKS, MONTHS, or YEARS). Use this with HistoryRetentionPeriod to control how long temporal table history is preserved before automatic deletion. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DwTableDistribution Specifies the distribution strategy for data warehouse tables (HASH, ROUND_ROBIN, or REPLICATE). Choose HASH for large fact tables, ROUND_ROBIN for staging tables, or REPLICATE for small dimension tables in analytical workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RejectedRowLocation Specifies where to store rows that exceed reject thresholds when querying external tables. Define a location for storing problematic rows for later analysis and data quality troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OnlineHeapOperation Enables online operations for heap tables during index creation or rebuilding. Use this to minimize blocking and maintain table availability during maintenance operations on tables without clustered indexes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LowPriorityMaxDuration Sets the maximum time in minutes for low-priority lock waits during online operations. Specify how long online operations should wait for locks before taking alternative action to balance performance and availability. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -DataConsistencyCheck Enables data consistency validation during online index operations. Use this to ensure data integrity is maintained during concurrent modifications to tables undergoing maintenance operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LowPriorityAbortAfterWait Defines the action to take when low-priority operations exceed their maximum wait duration. Choose how to handle lock conflicts: continue waiting, abort the operation, or kill blocking transactions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaximumDegreeOfParallelism Limits the number of processors used during table operations like index creation. Set this to control resource usage and prevent single operations from consuming all available CPU cores. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -IsNode Creates a node table for SQL Server 2017+ Graph Database functionality. Enable this when building graph databases where the table will store entities and their properties for relationship modeling. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IsEdge Creates an edge table for SQL Server 2017+ Graph Database functionality to store relationships. Enable this when building graph databases where the table will store connections between node tables. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IsVarDecimalStorageFormatEnabled Enables variable-length decimal storage format to reduce storage space for decimal and numeric columns. Use this for tables with many decimal columns containing leading zeros or small values to optimize storage efficiency. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Passthru Returns the T-SQL script for table creation instead of executing it immediately. Use this to review, modify, or save table creation scripts before deployment, or to generate scripts for version control. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database objects piped from Get-DbaDatabase for creating tables across multiple databases. Use this in pipeline scenarios where you want to apply table creation to a filtered set of databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.String (when -Passthru is specified) Returns the T-SQL CREATE TABLE script as a string for review or version control before deployment. Microsoft.SqlServer.Management.Smo.Table (default) Returns one Table object for each table successfully created. The table object includes all configured columns, constraints, indexes, and table properties. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Database containing the table Schema: Schema containing the table Name: Name of the table Rows: Number of rows in the table (0 for newly created tables) Created: DateTime when the table was created LastModified: DateTime when the table was last modified Additional properties available (from SMO Table object): FileGroup: Filegroup where the table data is stored AnsiNullsStatus: Boolean indicating if ANSI_NULLS is enabled QuotedIdentifierStatus: Boolean indicating if QUOTED_IDENTIFIER is enabled ChangeTrackingEnabled: Boolean indicating if change tracking is enabled IsMemoryOptimized: Boolean indicating if table is memory-optimized IsSystemVersioned: Boolean indicating if table is system-versioned temporal table IsFileTable: Boolean indicating if table is a FileTable IsExternal: Boolean indicating if table is an external table TrackColumnsUpdatedEnabled: Boolean indicating if column-level change tracking is enabled &nbsp;"
  },
  {
    "name": "New-DbaDbTransfer",
    "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.",
    "category": "Utilities",
    "tags": [
      "general",
      "transfer",
      "object"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbTransfer",
    "popularityRank": 252,
    "synopsis": "Creates a configured SMO Transfer object for copying database objects between SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbTransfer View Source Kirill Kravtsov (@nvarscar) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a configured SMO Transfer object for copying database objects between SQL Server instances Description Returns a configured SMO Transfer object that defines what database objects to copy and how to copy them between SQL Server instances. This 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. Useful for database migrations, environment refreshes, or selective object deployment where you need to copy specific tables, views, stored procedures, users, or other database objects. Supports copying schema only, data only, or both, with configurable batch sizes and timeout values for large data transfers. Syntax New-DbaDbTransfer [[-SqlInstance] ] [[-SqlCredential] ] [[-DestinationSqlInstance] ] [[-DestinationSqlCredential] ] [[-Database] ] [[-DestinationDatabase] ] [[-BatchSize] ] [[-BulkCopyTimeOut] ] [[-ScriptingOption] ] [[-InputObject] ] [-CopyAllObjects] [[-CopyAll] ] [-SchemaOnly] [-DataOnly] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Creates a transfer object that, when invoked, would copy all tables from database sql1.mydb to sql2.mydb PS C:\\> New-DbaDbTransfer -SqlInstance sql1 -Destination sql2 -Database mydb -CopyAll Tables Example 2: Creates a transfer object to copy specific tables from database sql1.mydb to sql2.mydb PS C:\\> Get-DbaDbTable -SqlInstance sql1 -Database MyDb -Table a, b, c | New-DbaDbTransfer -SqlInstance sql1 -Destination sql2 -Database mydb Optional Parameters -SqlInstance Source SQL Server instance name. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. You must have appropriate permissions to create the specified objects on the target server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instance. Accepts PowerShell credential objects created with Get-Credential. Only SQL Server authentication is supported for the destination connection. When not specified, uses Windows Authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the source database containing the objects to transfer. This database must exist on the source SQL Server instance. Use this to define which database serves as the source for the transfer operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationDatabase Specifies the target database where objects will be transferred. The database should already exist on the destination instance. When not specified, uses the same database name as the source database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $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. Larger batch sizes improve performance but use more memory. Smaller batches reduce memory pressure but may slow transfer speed. Default is 50,000 rows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Increase this value when transferring large tables or working with slower network connections. Default is 5000 seconds. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 5000 | -ScriptingOption Provides custom scripting options that control how database objects are scripted during the transfer. Must be created using New-DbaScriptingOption. Use this to control object scripting behavior such as including permissions, check constraints, triggers, or indexes in the transfer. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts specific database objects (tables, views, stored procedures, etc.) to transfer via pipeline input from other dbatools commands. Use this to transfer only selected objects instead of entire object types. Objects must be SMO objects from the source database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -CopyAllObjects Includes all transferable database objects in the transfer operation, regardless of object type. This is the broadest transfer scope available. Use this for complete database migrations or when you need to transfer everything except system objects and data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CopyAll Specifies which types of database objects to include in the transfer operation. You can specify multiple object types to transfer specific categories. Common values include Tables, Views, StoredProcedures, UserDefinedFunctions, Users, and Roles for typical database migrations. Use this for selective transfers instead of copying all objects. Allowed values: 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 | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this for setting up database structure in development environments or when data will be loaded separately. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DataOnly Transfers only table data without creating or modifying database object structures. Assumes that tables and other objects already exist on the destination. Use this for data refresh scenarios where the database schema is already in place and you only need to update the data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Management.Smo.Transfer Returns a single configured SMO Transfer object that defines what database objects to copy and how to copy them to a destination SQL Server instance. The returned object is not executed - you must call .TransferData() on it or pipe it to Invoke-DbaDbTransfer to perform the actual transfer operation. Default properties configured based on parameters: BatchSize: Number of rows to transfer in each batch (rows) BulkCopyTimeOut: Timeout in seconds for bulk copy operations CopyAllObjects: Boolean indicating if all transferable objects are included CopyAll[ObjectType]: Individual boolean properties for each object type (CopyAllTables, CopyAllViews, CopyAllStoredProcedures, etc.) Options: Scripting options controlling how objects are scripted (from -ScriptingOption parameter) ObjectList: Collection of specific objects to transfer (populated from InputObject pipeline parameter) DestinationServer: Target SQL Server instance name DestinationDatabase: Target database name on destination instance DestinationServerConnection: ServerConnection object configured for destination with SSL/TLS settings from source DestinationLoginSecure: Boolean indicating if destination uses integrated security (True) or SQL authentication (False) DestinationLogin: Username for SQL Server authentication on destination (only set if not using integrated security) DestinationPassword: Password for SQL Server authentication on destination (only set if not using integrated security) CopyData: Boolean indicating if table data will be copied (False when -SchemaOnly specified) CopySchema: Boolean indicating if database object schema will be copied (False when -DataOnly specified) When -SchemaOnly is specified: CopyData property is set to False (schema only, no data) When -DataOnly is specified: CopySchema property is set to False (data only, assumes objects exist on destination) The Transfer object maintains all SMO Transfer properties and can be further customized by modifying returned object properties before calling TransferData(). &nbsp;"
  },
  {
    "name": "New-DbaDbUser",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "user"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDbUser",
    "popularityRank": 53,
    "synopsis": "Creates database users with support for SQL logins, contained users, and Azure AD authentication.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDbUser View Source Frank Henninger (@osiris687) , Andreas Jordan (@JordanOrdix), ordix.de Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates database users with support for SQL logins, contained users, and Azure AD authentication. 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. Syntax New-DbaDbUser [-SqlInstance] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-IncludeSystem] -User -ExternalProvider [-DefaultSchema ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] New-DbaDbUser [-SqlInstance] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-IncludeSystem] -User -SecurePassword [-DefaultSchema ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] New-DbaDbUser [-SqlInstance] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-IncludeSystem] -User [-DefaultSchema ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] New-DbaDbUser [-SqlInstance] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-IncludeSystem] [-User ] -Login [-DefaultSchema ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new sql user named user1 for the login user1 in the database DB1 PS C:\\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Login user1 Example 2: Creates a new sql user named user1 without login in the database DB1 PS C:\\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User user1 Example 3: Creates a new sql user named user1 for the login login1 in the database DB1 PS C:\\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User user1 -Login login1 Example 4: Creates a new sql user named user1 for the login login1 in the database DB1 and specifies the default schema... PS C:\\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User user1 -Login Login1 -DefaultSchema schema1 Creates a new sql user named user1 for the login login1 in the database DB1 and specifies the default schema to be schema1. Example 5: Creates a new sql user named &#39;claudio@*****.onmicrosoft.com&#39; mapped to Azure Active Directory (AAD) in the... PS C:\\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User \"claudio@**.onmicrosoft.com\" -ExternalProvider Creates a new sql user named 'claudio@**.onmicrosoft.com' mapped to Azure Active Directory (AAD) in the database DB1. Example 6: Creates a new contained sql user named user1 in the database DB1 with the password specified PS C:\\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Username user1 -Password (ConvertTo-SecureString -String \"DBATools\" -AsPlainText -Force) Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -User Sets the name of the database user to be created. Required for contained users, external provider users, and users without logins. If not specified when using -Login, the user name will match the login name. | Property | Value | | --- | --- | | Alias | Username | | Required | True | | Pipeline | false | | Default Value | | -Login Maps the database user to an existing SQL Server login for authentication. The login must already exist on the instance before creating the user. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | Password | | Required | True | | Pipeline | false | | Default Value | | -ExternalProvider Creates a user for Azure Active Directory authentication in Azure SQL databases or SQL Server with AAD integration. The User parameter should contain the full AAD principal name (user@domain.com or groupname). | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | False | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to create the user in. Accepts multiple database names separated by commas. If not specified, the user will be created in all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from user creation when processing all databases on an instance. Use this to skip databases where you don't want the user created, such as read-only or archived databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSystem Creates the user in system databases (master, model, msdb, tempdb) in addition to user databases. Typically used when creating maintenance or administrative users that need access to system databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DefaultSchema Sets the default schema that will be used when the user creates objects without specifying a schema. Defaults to 'dbo' if not specified. The schema must already exist in the target database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | dbo | -Force Drops and recreates the user if it already exists in the database. Use this when you need to reset a user's properties or when automation scripts need to ensure a clean user state. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.User Returns one User object for each user created, with one object per database when creating users in multiple databases. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name where the user was created Name: The name of the created database user LoginType: Type of login this user is based on (WindowsLogin, SqlLogin, Certificate, AsymmetricKey, etc.) Login: The login name the user is mapped to (null for contained users or external provider users) AuthenticationType: Authentication type used (SqlLogin for SQL authenticated, WindowsLogin, Certificate, AsymmetricKey, ExternalUser for AAD, None for NoLogin users) DefaultSchema: The default schema for this user (configured via -DefaultSchema parameter, defaults to 'dbo') Additional properties available from SMO User object (via Select-Object ): ID: Object ID of the user Owner: Principal that owns this user State: Current object state (Existing, Creating, Pending, Dropping) Urn: Unified Resource Name for the object Properties: Collection of object properties Conditional properties based on user type:** When created with -Login parameter: User has a login property set to the mapped login When created with -SecurePassword parameter: User is a contained database user with no login mapping When created with -ExternalProvider switch: User is an Azure AD external provider user with AuthenticationType = ExternalUser Output 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 same user name but different Database property values. &nbsp;"
  },
  {
    "name": "New-DbaDiagnosticAdsNotebook",
    "description": "Converts Glenn Berry's 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's useful for performance troubleshooting and health monitoring.",
    "category": "Advanced Features",
    "tags": [
      "community",
      "glennberry",
      "notebooks",
      "azuredatastudio"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDiagnosticAdsNotebook",
    "popularityRank": 439,
    "synopsis": "Generates a Jupyter Notebook containing Glenn Berry's SQL Server diagnostic queries for Azure Data Studio",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDiagnosticAdsNotebook View Source Gianluca Sartori (@spaghettidba) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Generates a Jupyter Notebook containing Glenn Berry's SQL Server diagnostic queries for Azure Data Studio Description Converts Glenn Berry's 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's useful for performance troubleshooting and health monitoring. Syntax New-DbaDiagnosticAdsNotebook [[-SqlInstance] ] [[-SqlCredential] ] [[-TargetVersion] ] [-Path] [-IncludeDatabaseSpecific] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new Jupyter Notebook named &quot;myNotebook&quot; based on the version of diagnostic queries found at... PS C:\\> New-DbaDiagnosticAdsNotebook -SqlInstance localhost -Path c:\\temp\\myNotebook.ipynb Creates a new Jupyter Notebook named \"myNotebook\" based on the version of diagnostic queries found at localhost Example 2: Creates a new Jupyter Notebook named &quot;myNotebook&quot; based on the version &quot;2016SP2&quot; of diagnostic queries PS C:\\> New-DbaDiagnosticAdsNotebook -TargetVersion 2016SP2 -Path c:\\temp\\myNotebook.ipynb Example 3: Creates a new Jupyter Notebook named &quot;myNotebook&quot; based on the version &quot;2017&quot; of diagnostic queries... PS C:\\> New-DbaDiagnosticAdsNotebook -TargetVersion 2017 -Path c:\\temp\\myNotebook.ipynb -IncludeDatabaseSpecific Creates a new Jupyter Notebook named \"myNotebook\" based on the version \"2017\" of diagnostic queries, including database-specific queries Required Parameters -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. The generated notebook can be opened in Azure Data Studio or any Jupyter-compatible environment for executing Glenn Berry's diagnostic queries. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. Defaults to the default instance on localhost. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 current connection. Must be one of \"2005\", \"2008\", \"2008R2\", \"2012\", \"2014\", \"2016\", \"2016SP2\", \"2017\", \"2019\", \"2022\", \"AzureSQLDatabase\". Cannot be used together with SqlInstance parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 2005,2008,2008R2,2012,2014,2016,2016SP2,2017,2019,2022,AzureSQLDatabase | -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. Use this when you need detailed analysis of individual databases rather than just server-wide diagnostics. Defaults to $false. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.IO.FileInfo Returns the file information object for the created Jupyter Notebook (.ipynb) file. The file contains Glenn Berry's SQL Server diagnostic queries formatted as executable cells in a Jupyter Notebook that can be opened and run in Azure Data Studio. Properties: FullName: The complete file path where the notebook was created Name: The filename of the notebook (.ipynb file) DirectoryName: The directory path where the notebook is located Length: The file size in bytes CreationTime: DateTime when the notebook file was created LastWriteTime: DateTime when the notebook file was last modified &nbsp;"
  },
  {
    "name": "New-DbaDirectory",
    "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.",
    "category": "Utilities",
    "tags": [
      "storage",
      "path",
      "directory",
      "folder"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaDirectory",
    "popularityRank": 490,
    "synopsis": "Creates directories on SQL Server machines using the SQL Server service account",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaDirectory View Source Stuart Moore Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates directories on SQL Server machines using the SQL Server service account 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. Syntax New-DbaDirectory [-SqlInstance] [-Path] [[-SqlCredential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: If the SQL Server instance sqlcluster can create the path L:\\MSAS12.MSSQLSERVER\\OLAP it will do and return... PS C:\\> New-DbaDirectory -SqlInstance sqlcluster -Path L:\\MSAS12.MSSQLSERVER\\OLAP If 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. Example 2: If the SQL Server instance sqlcluster can create the path L:\\MSAS12.MSSQLSERVER\\OLAP it will do and return... PS C:\\> $credential = Get-Credential PS C:\\> New-DbaDirectory -SqlInstance sqlcluster -SqlCredential $credential -Path L:\\MSAS12.MSSQLSERVER\\OLAP If 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 Required Parameters -SqlInstance The SQL Server you want to run the test on. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Path Specifies the full directory path to create on the SQL Server machine using the SQL Server service account. Use this when you need to create backup directories, database file paths, or log shipping folders where SQL Server needs access. The function will check if the path already exists and skip creation if it does. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance specified in -SqlInstance, providing the directory creation status for each instance. Properties: Server: The SQL Server instance name that was targeted for directory creation Path: The full directory path that was created on the SQL Server machine Created: Boolean ($true or $false) indicating whether the directory was successfully created The 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). &nbsp;"
  },
  {
    "name": "New-DbaEndpoint",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "endpoint"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaEndpoint",
    "popularityRank": 426,
    "synopsis": "Creates SQL Server endpoints for database mirroring, Service Broker, SOAP, or T-SQL communication.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaEndpoint View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates SQL Server endpoints for database mirroring, Service Broker, SOAP, or T-SQL communication. 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. Syntax New-DbaEndpoint [-SqlInstance] [[-SqlCredential] ] [[-Name] ] [[-Type] ] [[-Protocol] ] [[-Role] ] [[-EndpointEncryption] ] [[-EncryptionAlgorithm] ] [[-AuthenticationOrder] ] [[-Certificate] ] [[-IPAddress] ] [[-Port] ] [[-SslPort] ] [[-Owner] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a database mirroring endpoint on localhost\\sql2017 which using the default port PS C:\\> New-DbaEndpoint -SqlInstance localhost\\sql2017 -Type DatabaseMirroring Example 2: Creates a database mirroring endpoint on localhost\\sql2017 which uses alternative port 5055 PS C:\\> New-DbaEndpoint -SqlInstance localhost\\sql2017 -Type DatabaseMirroring -Port 5055 Example 3: Creates a database mirroring endpoint on localhost\\sql2017 which binds only on ipaddress 192.168.0.15 and... PS C:\\> New-DbaEndpoint -SqlInstance localhost\\sql2017 -Type DatabaseMirroring -IPAddress 192.168.0.15 -Port 5055 Creates a database mirroring endpoint on localhost\\sql2017 which binds only on ipaddress 192.168.0.15 and port 5055 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies the name for the new endpoint. Defaults to hadr_endpoint for DatabaseMirroring endpoints. Required when creating ServiceBroker, Soap, or TSql endpoints as these need unique names for identification. | Property | Value | | --- | --- | | Alias | Endpoint | | Required | False | | Pipeline | false | | Default Value | | -Type Defines the endpoint type to create. DatabaseMirroring endpoints enable availability groups and database mirroring. ServiceBroker enables message queuing, Soap creates web service endpoints, and TSql allows remote connections. Defaults to DatabaseMirroring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | DatabaseMirroring | | Accepted Values | DatabaseMirroring,ServiceBroker,Soap,TSql | -Protocol Sets the communication protocol for the endpoint. TCP is standard for database mirroring and availability groups. Use Http for SOAP endpoints, NamedPipes for local connections, or SharedMemory for same-machine communication. Defaults to Tcp. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Tcp | | Accepted Values | 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. Partner restricts to principal/mirror roles only, Witness allows witness-only, None disables mirroring roles. Defaults to All. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | All | | Accepted Values | All,None,Partner,Witness | -EndpointEncryption Controls whether encryption is enforced for endpoint connections. Required forces all connections to use encryption. Supported allows both encrypted and unencrypted connections, Disabled prevents encryption. Defaults to Required for security. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Required | | Accepted Values | Disabled,Required,Supported | -EncryptionAlgorithm Sets the encryption algorithm used to secure endpoint communications. AES provides the strongest security. RC4 options are available for backward compatibility but are less secure. Use None only when encryption is disabled. Defaults to Aes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Aes | | Accepted Values | Aes,AesRC4,None,RC4,RC4Aes | -AuthenticationOrder Defines the authentication methods and their priority order for endpoint connections. Negotiate automatically chooses the best available method. Use certificate options when requiring certificate-based authentication, or specific methods like Kerberos for domain environments. Defaults to Negotiate. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. The certificate must already exist in the master database and provides certificate-based authentication for enhanced security. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IPAddress Sets which IP address the endpoint listens on for incoming connections. Use 0.0.0.0 to listen on all available interfaces. Specify a particular IP address to restrict connections to that interface only, useful for multi-homed servers. Defaults to 0.0.0.0 (all interfaces). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when you need a specific port for firewall rules or standardization across instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -SslPort Sets the SSL port number for HTTPS endpoints when using HTTP protocol. Only applicable for Soap endpoints using HTTPS. Required when creating secure web service endpoints that need encrypted communication over HTTP. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Owner Sets the SQL Server login that owns the endpoint. The owner has full control permissions on the endpoint. Defaults to the sa account if available, otherwise uses the current connection's login for ownership. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.EndPoint Returns 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 communication settings. Default display properties (via Select-DefaultView from Get-DbaEndpoint): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the endpoint (e.g., hadr_endpoint for DatabaseMirroring) Type: The endpoint type (DatabaseMirroring, ServiceBroker, Soap, TSql) Protocol: The communication protocol (Tcp, NamedPipes, Http, Via, SharedMemory) Owner: The SQL Server login that owns the endpoint IsAdminOnly: Boolean indicating if the endpoint is restricted to administrators only Additional properties available (from SMO EndPoint object): EndpointType: The type of endpoint (same as Type) ProtocolType: The protocol type enumeration value Parent: Reference to the parent Server object State: The current state of the endpoint object (Existing, Creating, Pending, etc.) Urn: The Uniform Resource Name for the endpoint Protocol: The Protocol object containing TCP, HTTP, Named Pipes configuration details Payload: The Payload object containing endpoint-specific configuration (DatabaseMirroring, ServiceBroker, Soap, TSql) All properties from the base SMO EndPoint object are accessible using Select-Object * even though only default properties are displayed without that cmdlet. &nbsp;"
  },
  {
    "name": "New-DbaFirewallRule",
    "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 = 'SQL Server default instance' or 'SQL Server instance <InstanceName>'\n    Name        = 'SQL Server default instance' or 'SQL Server instance <InstanceName>'\n    Group       = 'SQL Server'\n    Enabled     = 'True'\n    Direction   = 'Inbound'\n    Protocol    = 'TCP'\n    Program     = '<Path ending with MSSQL\\Binn\\sqlservr.exe>'\n\nWith -RuleType Port, the firewall rule for the instance itself will have the following configuration (parameters for New-NetFirewallRule):\n\n    DisplayName = 'SQL Server default instance' or 'SQL Server instance <InstanceName>'\n    Name        = 'SQL Server default instance' or 'SQL Server instance <InstanceName>'\n    Group       = 'SQL Server'\n    Enabled     = 'True'\n    Direction   = 'Inbound'\n    Protocol    = 'TCP'\n    LocalPort   = '<Port>'\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 = 'SQL Server Browser'\n    Name        = 'SQL Server Browser'\n    Group       = 'SQL Server'\n    Enabled     = 'True'\n    Direction   = 'Inbound'\n    Protocol    = 'Any'\n    Program     = '<Path ending with sqlbrowser.exe>'\n\nWith -RuleType Port, the firewall rule for the SQL Server Browser will have the following configuration (parameters for New-NetFirewallRule):\n\n    DisplayName = 'SQL Server Browser'\n    Name        = 'SQL Server Browser'\n    Group       = 'SQL Server'\n    Enabled     = 'True'\n    Direction   = 'Inbound'\n    Protocol    = 'UDP'\n    LocalPort   = '1434'\n\nThe firewall rule for the dedicated admin connection (DAC) will have the following configuration (parameters for New-NetFirewallRule):\n\n    DisplayName = 'SQL Server default instance (DAC)' or 'SQL Server instance <InstanceName> (DAC)'\n    Name        = 'SQL Server default instance (DAC)' or 'SQL Server instance <InstanceName> (DAC)'\n    Group       = 'SQL Server'\n    Enabled     = 'True'\n    Direction   = 'Inbound'\n    Protocol    = 'TCP'\n    LocalPort   = '<Port>' (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 = 'SQL Server default instance (DatabaseMirroring)' or 'SQL Server instance <InstanceName> (DatabaseMirroring)'\n    Name        = 'SQL Server default instance (DatabaseMirroring)' or 'SQL Server instance <InstanceName> (DatabaseMirroring)'\n    Group       = 'SQL Server'\n    Enabled     = 'True'\n    Direction   = 'Inbound'\n    Protocol    = 'TCP'\n    LocalPort   = '5022' (can be overwritten by using the parameter Configuration)",
    "category": "Utilities",
    "tags": [
      "network",
      "connection",
      "firewall"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaFirewallRule",
    "popularityRank": 431,
    "synopsis": "Creates Windows firewall rules for SQL Server instances to allow network connectivity",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "New-DbaFirewallRule View Source Andreas Jordan (@JordanOrdix), ordix.de Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates Windows firewall rules for SQL Server instances to allow network connectivity Description Creates inbound Windows firewall rules for SQL Server instances, Browser service, and Dedicated Admin Connection (DAC) to allow network connectivity. This 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. By default, the function creates program-based firewall rules that target SQL Server executables (sqlservr.exe, sqlbrowser.exe). This 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. Alternatively, you can use -RuleType Port to create traditional port-based firewall rules. This is a wrapper around New-NetFirewallRule executed remotely on the target computer via Invoke-Command2. Both DisplayName and Name are set to the same value to ensure unique rule identification and prevent duplicates. All rules use the \"SQL Server\" group for easy management with Get-DbaFirewallRule. The functionality is currently limited. Help to extend the functionality is welcome. As long as you can read this note here, there may be breaking changes in future versions. So please review your scripts using this command after updating dbatools. With -RuleType Program (default), the firewall rule for the instance itself will have the following configuration (parameters for New-NetFirewallRule): DisplayName = 'SQL Server default instance' or 'SQL Server instance ' Name = 'SQL Server default instance' or 'SQL Server instance ' Group = 'SQL Server' Enabled = 'True' Direction = 'Inbound' Protocol = 'TCP' Program = ' ' With -RuleType Port, the firewall rule for the instance itself will have the following configuration (parameters for New-NetFirewallRule): DisplayName = 'SQL Server default instance' or 'SQL Server instance ' Name = 'SQL Server default instance' or 'SQL Server instance ' Group = 'SQL Server' Enabled = 'True' Direction = 'Inbound' Protocol = 'TCP' LocalPort = ' ' With -RuleType Program (default), the firewall rule for the SQL Server Browser will have the following configuration (parameters for New-NetFirewallRule): DisplayName = 'SQL Server Browser' Name = 'SQL Server Browser' Group = 'SQL Server' Enabled = 'True' Direction = 'Inbound' Protocol = 'Any' Program = ' ' With -RuleType Port, the firewall rule for the SQL Server Browser will have the following configuration (parameters for New-NetFirewallRule): DisplayName = 'SQL Server Browser' Name = 'SQL Server Browser' Group = 'SQL Server' Enabled = 'True' Direction = 'Inbound' Protocol = 'UDP' LocalPort = '1434' The firewall rule for the dedicated admin connection (DAC) will have the following configuration (parameters for New-NetFirewallRule): DisplayName = 'SQL Server default instance (DAC)' or 'SQL Server instance (DAC)' Name = 'SQL Server default instance (DAC)' or 'SQL Server instance (DAC)' Group = 'SQL Server' Enabled = 'True' Direction = 'Inbound' Protocol = 'TCP' LocalPort = ' ' (typically 1434 for a default instance, but will be fetched from ERRORLOG) The firewall rule for the DAC will only be created if the DAC is configured for listening remotely. Use `Set-DbaSpConfigure -SqlInstance SRV1 -Name RemoteDacConnectionsEnabled -Value 1` to enable remote DAC before running this command. The firewall rule for database mirroring or Availability Groups will have the following configuration (parameters for New-NetFirewallRule): DisplayName = 'SQL Server default instance (DatabaseMirroring)' or 'SQL Server instance (DatabaseMirroring)' Name = 'SQL Server default instance (DatabaseMirroring)' or 'SQL Server instance (DatabaseMirroring)' Group = 'SQL Server' Enabled = 'True' Direction = 'Inbound' Protocol = 'TCP' LocalPort = '5022' (can be overwritten by using the parameter Configuration) Syntax New-DbaFirewallRule [-SqlInstance] [[-Credential] ] [[-Type] ] [[-RuleType] ] [[-Configuration] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Automatically configures the needed firewall rules for both the default instance and the instance named TEST... PS C:\\> New-DbaFirewallRule -SqlInstance SRV1, SRV1\\TEST Automatically configures the needed firewall rules for both the default instance and the instance named TEST on SRV1. By default, creates program-based rules targeting the SQL Server executables, allowing the instances to work regardless of port configuration changes. Example 2: Creates port-based firewall rules instead of the default program-based rules PS C:\\> New-DbaFirewallRule -SqlInstance SRV1, SRV1\\TEST -RuleType Port Creates port-based firewall rules instead of the default program-based rules. This creates traditional TCP/UDP port rules for the instances. Example 3: Automatically configures the needed firewall rules for both the default instance and the instance named TEST... PS C:\\> New-DbaFirewallRule -SqlInstance SRV1, SRV1\\TEST -Configuration @{ Profile = 'Domain' } Automatically configures the needed firewall rules for both the default instance and the instance named TEST on SRV1, but configures the firewall rule for the domain profile only. Example 4: Creates or recreates the firewall rule for the instance TEST on SRV1 PS C:\\> New-DbaFirewallRule -SqlInstance SRV1\\TEST -Type Engine -Force -Confirm:$false Creates or recreates the firewall rule for the instance TEST on SRV1. Does not prompt for confirmation. Example 5: Creates the firewall rule for database mirroring or Availability Groups on the default instance on SQL01... PS C:\\> New-DbaFirewallRule -SqlInstance SQL01 -Type DatabaseMirroring Creates the firewall rule for database mirroring or Availability Groups on the default instance on SQL01 using the default port 5022. Example 6: Creates the firewall rule for database mirroring or Availability Groups on the default instance on SQL02... PS C:\\> New-DbaFirewallRule -SqlInstance SQL02 -Type DatabaseMirroring -Configuration @{ LocalPort = '5023' } Creates the firewall rule for database mirroring or Availability Groups on the default instance on SQL02 using the custom port 5023. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Credential object used to connect to the Computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies which firewall rule types to create for SQL Server network access. Use this when you need to create specific rules instead of the automatic detection behavior. Valid values are Engine (SQL Server instance), Browser (SQL Server Browser service), DAC (Dedicated Admin Connection) and DatabaseMirroring (database mirroring or Availability Groups). When omitted, the function automatically creates Engine rules plus Browser rules for non-default ports and DAC rules when remote DAC is enabled. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Valid values are Program (targets sqlservr.exe and sqlbrowser.exe executables) and Port (targets TCP/UDP port numbers). Defaults to Program, which allows instances to work regardless of port configuration changes (named instances on different ports, default instances on non-standard ports). Use Port when you need traditional port-based rules or when Program-based rules cannot be created. Note: DAC and DatabaseMirroring rules are always port-based regardless of this setting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Program | | Accepted Values | Program,Port | -Configuration Provides custom settings to override the default firewall rule configuration when calling New-NetFirewallRule. Use this when you need to restrict rules to specific network profiles (Domain, Private, Public) or modify other advanced firewall settings. Common examples include @{Profile = 'Domain'} to limit rules to domain networks only, or @{RemoteAddress = '192.168.1.0/24'} to restrict source IPs. The Name, DisplayName, and Group parameters are reserved and will be ignored if specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Forces recreation of firewall rules that already exist by deleting and recreating them. Use this when you need to update existing rules with new settings or when troubleshooting connectivity issues. Without this switch, the function will warn you about existing rules and skip their creation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per firewall rule created, providing comprehensive details about the rule configuration and creation status. Default display properties (via Select-DefaultView): ComputerName: The name of the computer where the firewall rule was created InstanceName: The SQL Server instance name; $null for Browser rules SqlInstance: The full SQL Server instance name (computer\\instance); $null for Browser rules DisplayName: The display name of the firewall rule (e.g., 'SQL Server default instance', 'SQL Server Browser') Type: The type of firewall rule created (Engine, Browser, DAC, DatabaseMirroring) Successful: Boolean indicating if the rule creation was successful Status: Human-readable status message describing the outcome (e.g., 'The rule was successfully created.', 'The desired rule already exists. Use -Force to remove and recreate the rule.') Protocol: The protocol type of the rule (TCP, UDP, or Any) LocalPort: The TCP/UDP port number for port-based rules; $null for Program-based rules Program: The executable program path for Program-based rules; $null for Port-based rules *Additional properties available (using Select-Object ):** Name: The internal name of the firewall rule (same as DisplayName) RuleConfig: Complete hashtable containing all New-NetFirewallRule parameters used to create the rule Details: PSCustomObject containing remote command execution details with properties: Successful: Boolean indicating overall success status CimInstance: The CIM instance object returned by New-NetFirewallRule Warning: Warning messages from rule creation (if any) Error: Error messages from rule creation (if any) Exception: Exception details if an error occurred (if any) &nbsp;"
  },
  {
    "name": "New-DbaLinkedServer",
    "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.",
    "category": "Utilities",
    "tags": [
      "linkedserver",
      "server"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaLinkedServer",
    "popularityRank": 475,
    "synopsis": "Creates a new linked server connection to remote SQL Server instances or heterogeneous data sources.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaLinkedServer View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a new linked server connection to remote SQL Server instances or heterogeneous data sources. 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. Syntax New-DbaLinkedServer [[-SqlInstance] ] [[-SqlCredential] ] [[-LinkedServer] ] [[-ServerProduct] ] [[-Provider] ] [[-DataSource] ] [[-Location] ] [[-ProviderString] ] [[-Catalog] ] [[-SecurityContext] ] [[-SecurityContextRemoteUser] ] [[-SecurityContextRemoteUserPassword] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new linked server named linkedServer1 on the sql01 instance PS C:\\> New-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 -ServerProduct mssql -Provider MSOLEDBSQL -DataSource sql02 Creates 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. Example 2: Creates a new linked server named linkedServer1 on the sql01 instance PS C:\\> Connect-DbaInstance -SqlInstance sql01 | New-DbaLinkedServer -LinkedServer linkedServer1 -ServerProduct mssql -Provider MSOLEDBSQL -DataSource sql02 Creates 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 via pipeline. Example 3: Creates a new linked server named linkedServer1 on the sql01 instance PS C:\\> New-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 -ServerProduct mssql -Provider MSOLEDBSQL -DataSource sql02 -SecurityContext CurrentSecurityContext Creates 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 are not explicitly mapped to the remote server will use the current login's security context. Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LinkedServer Specifies the name for the new linked server object in SQL Server. This name must be unique on the SQL Server instance. Use a descriptive name that identifies the remote data source or its purpose to help other DBAs understand the connection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ServerProduct Specifies the product name of the remote data source as it appears in sys.servers.product column. Common values include 'SQL Server' for SQL Server instances, 'Oracle' for Oracle databases, or custom names for other OLE DB data sources. This is primarily used for documentation and identification purposes in system views. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Provider Specifies the OLE DB provider used to connect to the remote data source. For SQL Server, use 'MSOLEDBSQL' or 'MSOLEDBSQL19' (recommended) - SQL Server Native Client (SQLNCLI) is deprecated and removed from SQL Server 2022 and SSMS 19. Other common providers include 'OraOLEDB.Oracle' for Oracle or 'Microsoft.ACE.OLEDB.12.0' for Access databases. The provider must be installed and registered on the SQL Server instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DataSource Specifies the network name or connection string for the remote data source. For SQL Server instances, this is typically the server name or server\\instance format. For other data sources, this could be a TNS name for Oracle or a file path for file-based sources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Location Specifies the physical location information for the data source, typically used for documentation purposes. This parameter is rarely required for most linked server configurations and is primarily used with specific OLE DB providers. Leave empty unless specifically required by your data source provider. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ProviderString Specifies additional connection properties passed directly to the OLE DB provider. Use this for provider-specific settings like connection pooling, timeouts, or authentication options that cannot be set through other parameters. The format and available options depend on the specific OLE DB provider being used. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Catalog Specifies the default database or catalog name to use when connecting to the remote data source. For SQL Server linked servers, this sets the default database context for queries that don't specify a database name. This is equivalent to the 'Initial Catalog' connection property in connection strings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 connection behavior for a login that is not explicitly mapped. 'NoConnection' means that a connection will not be made. 'WithoutSecurityContext' means the connection will be made without using a security context. 'CurrentSecurityContext' means the connection will be made using the login's current security context. 'SpecifiedSecurityContext' means the specified username and password will be used. The default value is 'WithoutSecurityContext'. For more details see the Microsoft documentation for sp_addlinkedsrvlogin and also review the SSMS Security tab of the linked server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | WithoutSecurityContext | | Accepted Values | 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 are sent to the SQL Server instance in plain text. Check with your security administrator before using this parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts SQL Server SMO objects from the pipeline, typically from Connect-DbaInstance. This allows you to create linked servers on multiple instances by piping server connections to this function. Use this when you need to create the same linked server configuration across multiple SQL Server instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.LinkedServer Returns one LinkedServer object for each linked server successfully created on the target SQL Server instance(s). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Name of the linked server DataSource: Network name or connection string for the remote data source ProviderName: OLE DB provider used to connect to the remote data source ProductName: Product name of the remote data source LinkedServerLogins: Number of login mappings configured for this linked server Additional properties available (from SMO LinkedServer object): Catalog: Default database or catalog name on the remote data source Location: Physical location information for the data source ProviderString: Additional connection properties passed to the OLE DB provider RpcEnabled: Boolean indicating if remote procedure calls are enabled RpcOut: Boolean indicating if outgoing RPC calls are allowed ConnectTimeout: Connection timeout in seconds QueryTimeout: Query timeout in seconds IsPublisher: Boolean indicating if the linked server is a replication publisher IsSubscriber: Boolean indicating if the linked server is a replication subscriber IsDistributor: Boolean indicating if the linked server is a replication distributor &nbsp;"
  },
  {
    "name": "New-DbaLinkedServerLogin",
    "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.",
    "category": "Utilities",
    "tags": [
      "linkedserver",
      "server"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaLinkedServerLogin",
    "popularityRank": 305,
    "synopsis": "Creates authentication mappings between local and remote logins for linked server connections.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaLinkedServerLogin View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates authentication mappings between local and remote logins for linked server connections. 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. Syntax New-DbaLinkedServerLogin [[-SqlInstance] ] [[-SqlCredential] ] [[-LinkedServer] ] [[-LocalLogin] ] [[-RemoteUser] ] [[-RemoteUserPassword] ] [-Impersonate] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new linked server login and maps the local login testuser1 to the remote login testuser2 PS C:\\> New-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -LocalLogin localUser1 -RemoteUser remoteUser1 -RemoteUserPassword Creates 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. NOTE: 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 sp_addlinkedsrvlogin for more details. Example 2: Creates a mapping for all local logins on sql01 to connect using their own credentials to the linked server... PS C:\\> New-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -Impersonate Creates a mapping for all local logins on sql01 to connect using their own credentials to the linked server linkedServer1. Example 3: &lt;password&gt; Creates a new linked server login and maps the local login testuser1 to the remote login testuser2 PS C:\\> Get-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 | New-DbaLinkedServerLogin -LinkedServer linkedServer1 -LocalLogin testuser1 -RemoteUser testuser2 -RemoteUserPassword Creates 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 linkedServer1 instance is passed in via pipeline. NOTE: 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 sp_addlinkedsrvlogin for more details. Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LinkedServer Specifies the name of the linked server where the login mapping will be created. Required when using SqlInstance parameter. Use this to target specific linked servers when you have multiple configured on the same SQL instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LocalLogin Specifies the local SQL Server login that needs access to the linked server. Required in all scenarios. This is the login name that exists on your local SQL instance and will be mapped to credentials on the remote server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RemoteUser Specifies the login name to use on the remote server for authentication. Use with RemoteUserPassword to create explicit credential mapping. When omitted with Impersonate disabled, the mapping will fail unless the same login exists on both servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RemoteUserPassword Provides the password for the RemoteUser as a secure string. Required when mapping to a different remote login. WARNING: Passwords are transmitted to SQL Server in plain text - consult your security team before using in production environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Impersonate Enables pass-through authentication where local login credentials are used to authenticate to the remote server. Use this for trusted domain environments where the same login exists on both servers, eliminating the need to store remote passwords. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts linked server objects from Get-DbaLinkedServer pipeline input. Use this to efficiently configure login mappings across multiple linked servers retrieved from Get-DbaLinkedServer. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.LinkedServerLogin Returns one LinkedServerLogin object for each newly created linked server login mapping. The returned object represents the login mapping that was created, retrieved from Get-DbaLinkedServerLogin after creation. Properties include: Name: The local SQL Server login name that was mapped RemoteUser: The remote login name on the linked server (if credential mapping was used) Impersonate: Boolean indicating whether impersonation is enabled (pass-through authentication) Parent: Reference to the parent LinkedServer object DateLastModified: Timestamp of when the login mapping was last modified State: SMO object state (Existing, Creating, Pending, etc.) &nbsp;"
  },
  {
    "name": "New-DbaLogin",
    "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.",
    "category": "Security",
    "tags": [
      "login"
    ],
    "verb": "New",
    "popular": true,
    "url": "/New-DbaLogin",
    "popularityRank": 36,
    "synopsis": "Creates SQL Server logins for authentication with configurable security policies and mapping options",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaLogin View Source Kirill Kravtsov (@nvarscar) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates SQL Server logins for authentication with configurable security policies and mapping options 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. Syntax New-DbaLogin [-SqlInstance] [-SqlCredential ] [[-Login] ] [-InputObject ] [-LoginRenameHashtable ] [[-SecurePassword] ] [-MapToCredential ] [-Sid ] [-DefaultDatabase ] [-Language ] [-PasswordExpirationEnabled] [-PasswordPolicyEnforced] [-PasswordMustChange] [-Disabled] [-DenyWindowsLogin] [-NewSid] [-ExternalProvider] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] New-DbaLogin [-SqlInstance] [-SqlCredential ] [-Login ] [-InputObject ] [-LoginRenameHashtable ] [-MapToAsymmetricKey ] [-MapToCredential ] [-Sid ] [-Disabled] [-DenyWindowsLogin] [-NewSid] [-ExternalProvider] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] New-DbaLogin [-SqlInstance] [-SqlCredential ] [-Login ] [-InputObject ] [-LoginRenameHashtable ] [-MapToCertificate ] [-MapToCredential ] [-Sid ] [-Disabled] [-DenyWindowsLogin] [-NewSid] [-ExternalProvider] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] New-DbaLogin [-SqlInstance] [-SqlCredential ] [-Login ] [-InputObject ] [-LoginRenameHashtable ] [-HashedPassword ] [-MapToCredential ] [-Sid ] [-DefaultDatabase ] [-Language ] [-PasswordExpirationEnabled] [-PasswordPolicyEnforced] [-Disabled] [-DenyWindowsLogin] [-NewSid] [-ExternalProvider] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: You will be prompted to securely enter the password for a login [Newlogin] PS C:\\> New-DbaLogin -SqlInstance Server1,Server2 -Login Newlogin You 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. Example 2: Creates a login on Server1\\sql1 with a predefined password PS C:\\> $securePassword = Read-Host \"Input password\" -AsSecureString PS C:\\> New-DbaLogin -SqlInstance Server1\\sql1 -Login Newlogin -SecurePassword $securePassword -PasswordPolicyEnforced -PasswordExpirationEnabled Creates a login on Server1\\sql1 with a predefined password. The login will have password and expiration policies enforced onto it. Example 3: Copies a login [Oldlogin] to the same instance sql1 with the same parameters (including password) PS C:\\> Get-DbaLogin -SqlInstance sql1 -Login Oldlogin | New-DbaLogin -SqlInstance sql1 -LoginRenameHashtable @{Oldlogin = 'Newlogin'} -Force -NewSid -Disabled:$false Copies 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 [Newlogin] will be removed prior to creation. Example 4: Copies logins [Login1] and [Login2] from instance sql1 to instance sql2, but enforces password and expiration... PS C:\\> Get-DbaLogin -SqlInstance sql1 -Login Login1,Login2 | New-DbaLogin -SqlInstance sql2 -PasswordPolicyEnforced -PasswordExpirationEnabled -DefaultDatabase tempdb -Disabled Copies 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] and will be created in a disabled state. Example 5: Creates a new Windows Authentication backed login on sql1 PS C:\\> New-DbaLogin -SqlInstance sql1 -Login domain\\user Creates a new Windows Authentication backed login on sql1. The login will be part of the public server role. Example 6: Creates two new Windows Authentication backed login on sql1 PS C:\\> New-DbaLogin -SqlInstance sql1 -Login domain\\user1, domain\\user2 -DenyWindowsLogin Creates two new Windows Authentication backed login on sql1. The logins would be denied from logging in. Example 7: Creates a new login named &#39;claudio@*****.onmicrosoft.com&#39; mapped to Azure Active Directory (AAD) PS C:\\> New-DbaLogin -SqlInstance sql1 -Login \"claudio@**.onmicrosoft.com\" -ExternalProvider Required Parameters -SqlInstance The target SQL Server(s) | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Specifies the name or names of the logins to create. Accepts arrays for bulk login creation. Use domain\\username format for Windows Authentication logins, or simple names for SQL Server logins. | Property | Value | | --- | --- | | Alias | Name,LoginName | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts login objects piped from Get-DbaLogin for copying existing logins to new instances. Preserves login properties including passwords, SIDs, and security settings from the source login. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -LoginRenameHashtable Maps original login names to new names when piping login objects between instances. Use format @{'OldLoginName' = 'NewLoginName'} to rename logins during the copy process. | Property | Value | | --- | --- | | Alias | Rename | | Required | False | | Pipeline | false | | Default Value | | -SecurePassword Sets the password for SQL Server Authentication logins as a secure string object. Required for new SQL logins unless using HashedPassword or copying from existing login objects. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -HashedPassword Provides a pre-hashed password string for SQL Server logins, allowing password preservation during migrations. Use this when copying logins between instances while maintaining the original password hash. | Property | Value | | --- | --- | | Alias | Hash,PasswordHash | | Required | False | | Pipeline | false | | Default Value | | -MapToCertificate Associates the login with a specific certificate for certificate-based authentication. Specify the certificate name that exists in the master database for secure key-based login access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MapToAsymmetricKey Links the login to an asymmetric key for public key authentication scenarios. Provide the asymmetric key name from master database to enable cryptographic login authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MapToCredential Connects the login to a server credential for accessing external resources or delegation scenarios. Specify the credential name to associate with the login for extended authentication capabilities. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Sid Forces a specific Security Identifier (SID) for the login instead of generating a new one. Essential for login migrations to preserve user-database mappings and avoid orphaned users. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DefaultDatabase Sets the initial database context when the login connects to SQL Server. Defaults to master if not specified; useful for directing users to their primary working database. | Property | Value | | --- | --- | | Alias | DefaultDB | | Required | False | | Pipeline | false | | Default Value | | -Language Configures the default language for the login's SQL Server session messages and formatting. Affects date formats, error messages, and other locale-specific behaviors for the login. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PasswordExpirationEnabled Enforces Windows password expiration policy for SQL Server logins when combined with password policy enforcement. Requires PasswordPolicyEnforced to be enabled; helps maintain consistent password aging across systems. | Property | Value | | --- | --- | | Alias | Expiration,CheckExpiration | | Required | False | | Pipeline | false | | Default Value | False | -PasswordPolicyEnforced Applies Windows password complexity requirements to SQL Server logins including length and character variety. Recommended for security compliance; works with domain password policies when available. | Property | Value | | --- | --- | | Alias | Policy,CheckPolicy | | Required | False | | Pipeline | false | | Default Value | False | -PasswordMustChange Forces the user to set a new password on their first login attempt after account creation. Automatically enables password policy and expiration enforcement as prerequisites for this security feature. | Property | Value | | --- | --- | | Alias | MustChange | | Required | False | | Pipeline | false | | Default Value | False | -Disabled Creates the login in a disabled state, preventing authentication until manually enabled. Useful for preparing accounts before users need access or temporarily suspending login capabilities. | Property | Value | | --- | --- | | Alias | Disable | | Required | False | | Pipeline | false | | Default Value | False | -DenyWindowsLogin Blocks Windows Authentication login access while preserving the login definition for future use. Creates the login but prevents actual authentication; often used for security policy enforcement. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NewSid Generates fresh SIDs when copying logins to the same instance or when SID conflicts exist. Prevents SID collision errors during login duplication and ensures unique security identifiers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExternalProvider Configures the login for Microsoft Entra authentication in Azure SQL Database, Azure SQL Managed Instance, or SQL Server 2022 and later. Use with Microsoft Entra user principal names or service principal names supported by the target platform. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Removes any existing login with the same name before creating the new one. Allows overwriting existing logins without manual cleanup; use carefully to avoid unintended access loss. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Login Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The login account name LoginType: The type of login (SqlLogin, WindowsUser, WindowsGroup, Certificate, AsymmetricKey, ExternalUser, or ExternalGroup) CreateDate: DateTime when the login was created LastLogin: DateTime of the most recent connection (null if never connected or SQL Server 2000) HasAccess: Boolean indicating if the login has permission to connect IsLocked: Boolean indicating if the login is currently locked due to failed authentication attempts IsDisabled: Boolean indicating if the login is disabled MustChangePassword: Boolean indicating if the login must change password on next connection Additional properties always available (from SMO Login object): SidString: Hexadecimal string representation of the login's Security Identifier (SID) Sid: Binary Security Identifier of the login DefaultDatabase: The default database for the login when connecting Language: The default language for the login's SQL Server session LoginMode: The authentication mode for the login PasswordExpirationEnabled: Boolean indicating if password expiration policy is enforced PasswordPolicyEnforced: Boolean indicating if Windows password complexity requirements are enforced DenyWindowsLogin: Boolean indicating if Windows Authentication is denied for this login IsSystemObject: Boolean indicating if the login is a system object IsExpired: Boolean indicating if the SQL Server login password has expired (SQL Server 2008+) All properties from the base SMO Login object are accessible using Select-Object . &nbsp;"
  },
  {
    "name": "New-DbaReplCreationScriptOptions",
    "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",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication",
      "script"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaReplCreationScriptOptions",
    "popularityRank": 578,
    "synopsis": "Creates replication article creation script options for controlling which database objects are replicated",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "New-DbaReplCreationScriptOptions View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates replication article creation script options for controlling which database objects are replicated 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. By 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. This 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. See https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.replication.creationscriptoptions for more information Syntax New-DbaReplCreationScriptOptions [[-Options] ] [-NoDefaults] [ ] &nbsp; Examples &nbsp; Example 1: Adds the stores table to the testPub publication from mssql1.pubs with the NonClusteredIndexes and Statistics... PS C:\\> $cso = New-DbaReplCreationScriptOptions -Options NonClusteredIndexes, Statistics PS C:\\> $article = @{ >> SqlInstance = 'mssql1' >> Database = 'pubs' >> PublicationName = 'testPub' >> Name = 'stores' >> CreationScriptOptions = $cso >> } PS C:\\> Add-DbaReplArticle @article -EnableException Adds the stores table to the testPub publication from mssql1.pubs with the NonClusteredIndexes and Statistics options set includes default options. Example 2: Adds the stores table to the testPub publication from mssql1.pubs with the ClusteredIndexes and Identity... PS C:\\> $cso = New-DbaReplCreationScriptOptions -Options ClusteredIndexes, Identity -NoDefaults PS C:\\> $article = @{ >> SqlInstance = 'mssql1' >> Database = 'pubs' >> PublicationName = 'testPub' >> Name = 'stores' >> CreationScriptOptions = $cso >> } PS C:\\> Add-DbaReplArticle @article -EnableException Adds the stores table to the testPub publication from mssql1.pubs with the ClusteredIndexes and Identity options set, excludes default options. Optional Parameters -Options Specifies which database object properties to include when creating replicated tables at subscribers. Controls what gets scripted beyond the basic table structure. Use this to add specific elements like NonClusteredIndexes, Statistics, CheckConstraints, or ForeignKeys that aren't included in the default set. Common values include Statistics for performance, NonClusteredIndexes for query optimization, or Triggers for business logic replication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoDefaults Excludes the standard replication options that SQL Server Management Studio applies automatically when adding articles. Use this when you need precise control over which schema elements are replicated and want to avoid the default behavior. Without this switch, includes PrimaryObject, CustomProcedures, Identity, KeepTimestamp, ClusteredIndexes, DriPrimaryKey, Collation, DriUniqueKeys, and constraint replication settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.Replication.CreationScriptOptions Returns a CreationScriptOptions enum instance that encapsulates the selected replication schema options. This object can be passed to Add-DbaReplArticle's CreationScriptOptions parameter to control which schema elements are replicated to subscribers. The object represents a combination of zero or more schema option flags, including: PrimaryObject: The table structure CustomProcedures: Custom stored procedures Identity: Identity column properties KeepTimestamp: Timestamp columns ClusteredIndexes: Clustered indexes NonClusteredIndexes: Non-clustered indexes DriPrimaryKey: Primary key constraints DriForeignKeys: Foreign key constraints DriUniqueKeys: Unique key constraints CheckConstraints: Check constraints Collation: Column-level collation MarkReplicatedCheckConstraintsAsNotForReplication: Check constraints marked as not for replication MarkReplicatedForeignKeyConstraintsAsNotForReplication: Foreign key constraints marked as not for replication Schema: Database schema association And 27+ additional replication schema options See https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.replication.creationscriptoptions for the complete list of available options. &nbsp;"
  },
  {
    "name": "New-DbaReplPublication",
    "description": "Creates a new replication publication on a SQL Server instance that's 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'll 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",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaReplPublication",
    "popularityRank": 584,
    "synopsis": "Creates a SQL Server replication publication for transactional, snapshot, or merge replication",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "New-DbaReplPublication View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a SQL Server replication publication for transactional, snapshot, or merge replication Description Creates a new replication publication on a SQL Server instance that's 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. Use 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'll typically add articles using Add-DbaReplArticle and create subscriptions on target servers. https://learn.microsoft.com/en-us/sql/relational-databases/replication/publish/create-a-publication?view=sql-server-ver16 Syntax New-DbaReplPublication [-SqlInstance] [[-SqlCredential] ] [-Database] [-Name] [-Type] [[-LogReaderAgentCredential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a transactional publication called PubFromPosh for the Northwind database on mssql1 PS C:\\> New-DbaReplPublication -SqlInstance mssql1 -Database Northwind -Name PubFromPosh -Type Transactional Example 2: Creates a snapshot publication called snapPub for the pubs database on mssql1 PS C:\\> New-DbaReplPublication -SqlInstance mssql1 -Database pubs -Name snapPub -Type Snapshot Example 3: Creates a merge publication called mergePub for the pubs database on mssql1 PS C:\\> New-DbaReplPublication -SqlInstance mssql1 -Database pubs -Name mergePub -Type Merge Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Database Specifies the database where the publication will be created and which contains the objects to be replicated. This database must already exist on the publisher instance and will be enabled for the specified replication type. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Name Sets the unique name for the publication within the database. Use a descriptive name that identifies the purpose or content of the publication, as this name will be referenced when creating subscriptions and managing replication. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Type Determines the replication method used for distributing data to subscribers. Transactional 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 resolution. Choose based on your data synchronization requirements and network constraints. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | | Accepted Values | Snapshot,Transactional,Merge | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LogReaderAgentCredential Specifies the Windows account credentials for the Log Reader Agent, which is required for Transactional and Snapshot replication types. This 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. Use a domain account with appropriate permissions to the publisher database and distributor. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Replication.TransPublication or Microsoft.SqlServer.Replication.MergePublication Returns one publication object for each newly created publication. The returned object type depends on the publication type specified: TransPublication for Transactional or Snapshot publications MergePublication for Merge publications Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance where the publication was created InstanceName: The SQL Server instance name SQLInstance: The full SQL Server instance object DatabaseName: The name of the database containing the publication Name: The name of the publication Type: The publication type (Transactional, Snapshot, or Merge) Articles: Collection of articles defined in the publication Subscriptions: Collection of subscriptions to this publication Additional properties available from SMO publication objects: Status: Current status of the publication (normal, inactive, etc.) HasSubscriptions: Boolean indicating if the publication has active subscriptions CreationDate: DateTime when the publication was created SnapshotAgentExists: Boolean indicating if a Snapshot Agent job exists LogReaderAgentExists: Boolean indicating if a Log Reader Agent job exists (transactional/snapshot only) Access all properties using Select-Object * to view complete publication configuration details from the SMO object. &nbsp;"
  },
  {
    "name": "New-DbaReplSubscription",
    "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't 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.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaReplSubscription",
    "popularityRank": 630,
    "synopsis": "Creates SQL Server replication subscriptions to distribute data from publisher to subscriber instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "New-DbaReplSubscription View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates SQL Server replication subscriptions to distribute data from publisher to subscriber instances. 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't 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. Syntax New-DbaReplSubscription [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [-SubscriberSqlInstance] [[-SubscriberSqlCredential] ] [[-SubscriptionDatabase] ] [-PublicationName] [[-SubscriptionSqlCredential] ] [-Type] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a push subscription from sql2017 to sql2019 for the pubs database PS C:\\> New-DbaReplSubscription -SqlInstance sql2017 -Database pubs -SubscriberSqlInstance sql2019 -SubscriptionDatabase pubs -PublicationName testPub -Type Push Example 2: Creates a pull subscription from sql2017 to sql2019 for the pubs database PS C:\\> New-DbaReplSubscription -SqlInstance sql2017 -Database pubs -SubscriberSqlInstance sql2019 -SubscriptionDatabase pubs -PublicationName testPub -Type Pull Required Parameters -SqlInstance The target publishing SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -SubscriberSqlInstance The target SQL Server instance that will receive the replicated data from the publisher. Can specify multiple instances to create subscriptions on several subscribers simultaneously. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -PublicationName The name of the existing publication on the publisher database that you want to subscribe to. This publication must already exist and be configured for the type of subscription you're creating. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Type Specifies whether to create a Push or Pull subscription for data synchronization. Push subscriptions are managed by the publisher and typically used for high-frequency replication, while Pull subscriptions are managed by the subscriber. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | | Accepted Values | Push,Pull | Optional Parameters -SqlCredential Login to the target publishing instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the source database on the publisher instance that contains the publication data to be replicated. This database must already contain the publication you're subscribing to. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SubscriberSqlCredential Login credentials for connecting to the subscriber SQL Server instance. Accepts PowerShell credentials (Get-Credential). Use this when the subscriber requires different authentication than the publisher connection. Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SubscriptionDatabase The destination database name on the subscriber instance where replicated data will be stored. If this database doesn't exist, it will be automatically created with default settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SubscriptionSqlCredential SQL Server credentials used by the replication agents to connect to the subscriber database during synchronization. These credentials are stored in the subscription properties and used by the Distribution or Merge Agent. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This function creates replication subscriptions but does not return output objects. The function performs the following operations: Validates or creates the subscription database on the subscriber instance Creates necessary database schemas on the subscriber if needed Configures Push or Pull subscription based on the -Type parameter Initializes the subscription and creates synchronization agent jobs To verify the subscription was created successfully, use Get-DbaReplSubscription with the same parameters: PS C:\\> Get-DbaReplSubscription -SqlInstance $SqlInstance -Database $Database -PublicationName $PublicationName This will return subscription objects showing: ComputerName: The publisher server name InstanceName: The publisher instance name SqlInstance: The publisher instance in domain\\instance format DatabaseName: The publishing database name PublicationName: The publication name Name: The subscription name SubscriberName: The subscriber instance name SubscriptionDBName: The subscription database name on subscriber SubscriptionType: Push or Pull indicating subscription type &nbsp;"
  },
  {
    "name": "New-DbaRgResourcePool",
    "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.",
    "category": "Utilities",
    "tags": [
      "resourcepool",
      "resourcegovernor"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaRgResourcePool",
    "popularityRank": 683,
    "synopsis": "Creates a Resource Governor resource pool to control CPU, memory, and I/O allocation for SQL Server workloads.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaRgResourcePool View Source John McCall (@lowlydba), lowlydba.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a Resource Governor resource pool to control CPU, memory, and I/O allocation for SQL Server workloads. Description Creates a new Resource Governor resource pool that defines specific limits for CPU, memory, and I/O resources on a SQL Server instance. Resource pools let you isolate different workloads by setting minimum and maximum thresholds for system resources, preventing one application from consuming all server resources. Supports both Internal pools (for SQL Server workloads) and External pools (for external processes like R Services). The Resource Governor is automatically reconfigured after pool creation unless you specify otherwise. Syntax New-DbaRgResourcePool -SqlInstance [-SqlCredential ] [-ResourcePool ] [-Type ] [-MaximumCpuPercentage ] [-MaximumMemoryPercentage ] [-SkipReconfigure] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] New-DbaRgResourcePool -SqlInstance [-SqlCredential ] [-ResourcePool ] [-Type ] [-MinimumCpuPercentage ] [-MaximumCpuPercentage ] [-CapCpuPercentage ] [-MinimumMemoryPercentage ] [-MaximumMemoryPercentage ] [-MinimumIOPSPerVolume ] [-MaximumIOPSPerVolume ] [-SkipReconfigure] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] New-DbaRgResourcePool -SqlInstance [-SqlCredential ] [-ResourcePool ] [-Type ] [-MaximumCpuPercentage ] [-MaximumMemoryPercentage ] [-MaximumProcesses ] [-SkipReconfigure] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a new resource pool named &quot;poolAdmin&quot; for the instance sql2016 PS C:\\> New-DbaRgResourcePool -SqlInstance sql2016 -ResourcePool \"poolAdmin\" Example 2: Creates a new resource pool named &quot;poolDeveloper&quot; for the instance dev1 on sq2012 PS C:\\> New-DbaRgResourcePool -SqlInstance sql2012\\dev1 -ResourcePool \"poolDeveloper\" -SkipReconfigure Creates a new resource pool named \"poolDeveloper\" for the instance dev1 on sq2012. Reconfiguration is skipped and the Resource Governor will not be able to use the new resource pool until it is reconfigured. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | Optional Parameters -SqlCredential Credential object used to connect to the Windows server as a different user | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ResourcePool Specifies the name of the resource pool to create. Pool names must be unique within the Resource Governor configuration. Use descriptive names that indicate the workload type, like 'ReportingPool' or 'BatchProcessingPool' for easier management. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies whether to create an Internal pool for SQL Server workloads or External pool for external processes like R Services. Internal pools control database workloads, while External pools manage machine learning and external script execution resources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Internal | | Accepted Values | Internal,External | -MinimumCpuPercentage Sets the guaranteed minimum CPU percentage reserved for this pool during CPU contention. Ranges from 0-100, defaults to 0. Use this to ensure critical workloads always get their required CPU resources, even when the server is under heavy load. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaximumCpuPercentage Sets the maximum CPU percentage this pool can consume during CPU contention. Ranges from 1-100, defaults to 100. Use this to prevent runaway queries or resource-intensive workloads from monopolizing server CPU resources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Unlike MaximumCpuPercentage, this enforces the limit even when CPU resources are idle. Requires SQL Server 2012 or later. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this to guarantee memory allocation for critical workloads that require consistent memory availability. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaximumMemoryPercentage Sets the maximum percentage of total server memory this pool can consume. Ranges from 1-100, defaults to 100. Use this to prevent memory-intensive operations from consuming all available server memory and affecting other workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 100 | -MinimumIOPSPerVolume Reserves a minimum number of IOPS per disk volume exclusively for this pool. Defaults to 0 (unlimited). Use this to guarantee disk I/O performance for workloads that require consistent data access speeds, such as OLTP systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaximumIOPSPerVolume Limits the maximum IOPS per disk volume that this pool can consume. Defaults to 0 (unlimited). Use this to prevent I/O-intensive workloads like batch processing or reporting from saturating disk subsystems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaximumProcesses Sets the maximum number of external processes allowed to run concurrently in this External pool. Specify 0 for unlimited. Use this to control how many R or Python scripts can execute simultaneously, preventing external processes from overwhelming the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -SkipReconfigure Skips the automatic Resource Governor reconfiguration that makes the new pool active immediately after creation. Use this when creating multiple pools in succession to avoid repeated reconfigurations, then manually reconfigure once at the end. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Automatically drops and recreates the resource pool if it already exists with the same name. Use this when you need to update an existing pool's configuration or ensure a clean pool creation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.ResourcePool (for Internal pools) Microsoft.SqlServer.Management.Smo.ExternalResourcePool (for External pools) Returns one resource pool object per pool created on the specified instance(s). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: The unique identifier for the resource pool Name: The name of the resource pool CapCpuPercentage: Absolute maximum CPU percentage limit (1-100) IsSystemObject: Boolean indicating if the pool is a system-defined pool MaximumCpuPercentage: Maximum CPU percentage during contention (1-100) MaximumIopsPerVolume: Maximum IOPS per disk volume (0 = unlimited) MaximumMemoryPercentage: Maximum memory percentage (1-100) MinimumCpuPercentage: Guaranteed minimum CPU percentage (0-100) MinimumIopsPerVolume: Guaranteed minimum IOPS per disk volume (0 = unlimited) MinimumMemoryPercentage: Guaranteed minimum memory percentage (0-100) WorkloadGroups: Collection of workload groups associated with this pool All properties from the base SMO ResourcePool or ExternalResourcePool objects are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaRgWorkloadGroup",
    "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.",
    "category": "Utilities",
    "tags": [
      "workloadgroup",
      "resourcegovernor"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaRgWorkloadGroup",
    "popularityRank": 681,
    "synopsis": "Creates a Resource Governor workload group within a specified resource pool to control SQL Server resource allocation.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaRgWorkloadGroup View Source John McCall (@lowlydba), lowlydba.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a Resource Governor workload group within a specified resource pool to control SQL Server resource allocation. 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. This 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. The 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. Syntax New-DbaRgWorkloadGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-WorkloadGroup] ] [[-ResourcePool] ] [[-ResourcePoolType] ] [[-Importance] ] [[-RequestMaximumMemoryGrantPercentage] ] [[-RequestMaximumCpuTimeInSeconds] ] [[-RequestMemoryGrantTimeoutInSeconds] ] [[-MaximumDegreeOfParallelism] ] [[-GroupMaximumRequests] ] [-SkipReconfigure] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a workload group &quot;groupAdmin&quot; in the resource pool named &quot;poolAdmin&quot; for the instance sql2016 PS C:\\> New-DbaRgWorkloadGroup -SqlInstance sql2016 -WorkloadGroup \"groupAdmin\" -ResourcePool \"poolAdmin\" Example 2: If &quot;groupAdmin&quot; exists, it is dropped and re-created in the default resource pool for the instance sql2016 PS C:\\> New-DbaRgWorkloadGroup -SqlInstance sql2016 -WorkloadGroup \"groupAdmin\" -Force Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | -SqlCredential Credential object used to connect to the Windows server as a different user | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -WorkloadGroup Specifies the name of the workload group to create within the resource pool. Use descriptive names that reflect the workload type, like 'ReportingQueries', 'ETLProcesses', or 'AdminTasks'. Each workload group acts as a container for classifying requests and applying specific resource limits and priorities. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ResourcePool Specifies which resource pool will contain the new workload group. Defaults to 'default' if not specified. Use this to organize workload groups within custom resource pools that have specific CPU and memory allocations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | default | -ResourcePoolType Determines whether to create the workload group in an Internal or External resource pool. Defaults to Internal. Use External for R/Python workloads or machine learning services; use Internal for standard SQL Server workloads like queries and stored procedures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Internal | | Accepted Values | Internal,External | -Importance Sets the relative priority for requests in this workload group when competing for CPU resources. Defaults to MEDIUM. Use HIGH for critical application queries, MEDIUM for normal operations, and LOW for background tasks like maintenance or reporting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | MEDIUM | | Accepted Values | LOW,MEDIUM,HIGH | -RequestMaximumMemoryGrantPercentage Limits how much memory any single query in this workload group can consume from the resource pool. Defaults to 25%. Lower this for concurrent workloads to prevent memory hogging, or increase it for data warehouse queries that need large memory grants for sorting and hashing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 25 | -RequestMaximumCpuTimeInSeconds Sets the maximum CPU time in seconds that any single request can consume before being terminated. Default of 0 means unlimited. Use this to prevent runaway queries from consuming excessive CPU, typically setting values between 300-3600 seconds depending on your workload requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RequestMemoryGrantTimeoutInSeconds Defines how long a query will wait for memory grants before timing out. Default of 0 means unlimited wait time. Set this to prevent queries from waiting indefinitely during memory pressure, typically using values like 60-300 seconds for interactive workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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's MAXDOP setting. Lower values prevent queries from consuming too many CPU cores, while higher values can improve performance for analytical workloads on servers with many cores. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -GroupMaximumRequests Limits the total number of concurrent requests that can execute simultaneously within this workload group. Default of 0 means unlimited. Use this to control concurrency for resource-intensive workloads, preventing too many expensive queries from running at once and overwhelming the system. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -SkipReconfigure Prevents automatic reconfiguration of Resource Governor after creating the workload group. Changes won't take effect until you manually run ALTER RESOURCE GOVERNOR RECONFIGURE. Use this when creating multiple workload groups in a batch to avoid repeated reconfigurations, but remember to reconfigure manually afterward. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Drops and recreates the workload group if it already exists, applying new configuration settings. Use this when you need to modify an existing workload group's properties, as Resource Governor workload groups cannot be altered once created. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.WorkloadGroup Returns one workload group object per workload group created within the specified resource pool(s). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: The unique identifier for the workload group Name: The name of the workload group ExternalResourcePoolName: Name of the external resource pool (for External pools only) GroupMaximumRequests: Maximum number of concurrent requests allowed in this group (0 = unlimited) Importance: Relative priority when competing for CPU resources (LOW, MEDIUM, or HIGH) IsSystemObject: Boolean indicating if the workload group is a system-defined group MaximumDegreeOfParallelism: Maximum number of processors for parallel execution (0 = server default) RequestMaximumCpuTimeInSeconds: Maximum CPU time in seconds per request (0 = unlimited) RequestMaximumMemoryGrantPercentage: Maximum memory grant percentage from the pool (1-100) RequestMemoryGrantTimeoutInSeconds: Maximum wait time in seconds for memory grants (0 = unlimited) All properties from the base SMO WorkloadGroup object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaScriptingOption",
    "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's formatted.\n\nSee https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.scriptingoptions.aspx for more information",
    "category": "Utilities",
    "tags": [
      "general",
      "script",
      "object"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaScriptingOption",
    "popularityRank": 136,
    "synopsis": "Creates a customizable SMO ScriptingOptions object for controlling T-SQL script generation",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaScriptingOption View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Outputs Synopsis Creates a customizable SMO ScriptingOptions object for controlling T-SQL script generation 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's formatted. See https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.scriptingoptions.aspx for more information Syntax New-DbaScriptingOption [ ] &nbsp; Examples &nbsp; Example 1: Exports Agent Jobs with the Scripting Options ScriptDrops/WithDependencies set to $false and... PS C:\\> $options = New-DbaScriptingOption PS C:\\> $options.ScriptDrops = $false PS C:\\> $options.WithDependencies = $false PS C:\\> $options.AgentAlertJob = $true PS C:\\> $options.AgentNotify = $true PS C:\\> Get-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript -ScriptingOptionObject $options Exports Agent Jobs with the Scripting Options ScriptDrops/WithDependencies set to $false and AgentAlertJob/AgentNotify set to true Outputs Microsoft.SqlServer.Management.Smo.ScriptingOptions Returns 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 scripting 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 output. Common properties include: ScriptDrops: Include DROP statements (Boolean) WithDependencies: Include dependent objects (Boolean) AgentAlertJob: Include SQL Agent Alert and Job information (Boolean) AgentNotify: Include SQL Agent notification (Boolean) Indexes: Include indexes (Boolean) Triggers: Include triggers (Boolean) Permissions: Include permissions (Boolean) TargetServerVersion: Target SQL Server version for compatibility See Microsoft.SqlServer.Management.Smo.ScriptingOptions documentation for complete property list. &nbsp;"
  },
  {
    "name": "New-DbaServerRole",
    "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.",
    "category": "Utilities",
    "tags": [
      "role"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaServerRole",
    "popularityRank": 450,
    "synopsis": "Creates custom server-level roles on SQL Server instances for role-based access control.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaServerRole View Source Claudio Silva (@ClaudioESSilva), claudioessilva.eu Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates custom server-level roles on SQL Server instances for role-based access control. 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. Syntax New-DbaServerRole [-SqlInstance] [[-SqlCredential] ] [[-ServerRole] ] [[-Owner] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Will create a new server role named dbExecuter and grant ownership to the login sa on sql2017a instance PS C:\\> New-DbaServerRole -SqlInstance sql2017a -ServerRole 'dbExecuter' -Owner sa Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ServerRole Specifies the name of the custom server-level role to create. Accepts multiple role names to create several roles in one operation. Use this when implementing role-based security models or when you need custom permission groups beyond the built-in server roles like sysadmin or dbcreator. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Owner Sets the login that will own the newly created server role. Defaults to 'dbo' if not specified. Specify a different owner when you need the role managed by a specific login for security or organizational requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.ServerRole Returns one ServerRole object for each newly created server-level role. The returned object is obtained from Get-DbaServerRole after successful role creation. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Role: The name of the server role Login: Array of logins/users that are members of this role Owner: The login that owns the server role IsFixedRole: Boolean indicating if this is a built-in fixed role (always $false for newly created roles) DateCreated: DateTime when the role was created DateModified: DateTime when the role was last modified Additional properties available (from SMO ServerRole object): ServerRole: Duplicate of Role property name Parent: Reference to parent SQL Server object State: SMO object state (Existing, Creating, Pending, etc.) Urn: The unified resource name of the role object Properties: Collection of property objects for the role PermissionSet: Permissions assigned to the role All properties from the base SMO ServerRole object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "New-DbaServiceMasterKey",
    "description": "Creates a service master key in the master database, which sits at the top of SQL Server's 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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaServiceMasterKey",
    "popularityRank": 543,
    "synopsis": "Creates a service master key in the master database for instance-level encryption hierarchy",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaServiceMasterKey View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a service master key in the master database for instance-level encryption hierarchy Description Creates a service master key in the master database, which sits at the top of SQL Server's 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. Syntax New-DbaServiceMasterKey [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [[-SecurePassword] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: You will be prompted to securely enter your Service Key password, then a master key will be created in the... PS C:\\> New-DbaServiceMasterKey -SqlInstance Server1 You 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. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Provides an alternative way to specify the service master key password using a PSCredential object. The password from the credential will be used to encrypt the service master key, offering a convenient method when you already have credentials stored. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecurePassword Specifies the password used to encrypt the service master key. Must be a SecureString object for security. Use this when you need to set a specific password for the service master key instead of being prompted interactively. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.MasterKey Returns one MasterKey object for each instance where the service master key was created in the master database. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Always \"master\" for service master keys CreateDate: DateTime when the service master key was created DateLastModified: DateTime when the service master key was last modified IsEncryptedByServer: Boolean indicating if the master key is encrypted by the server Additional properties available (from SMO MasterKey object): Urn: The Uniform Resource Name of the master key State: Current state of the object (Existing, Creating, etc.) Parent: Reference to parent database object &nbsp;"
  },
  {
    "name": "New-DbaSqlParameter",
    "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.",
    "category": "Utilities",
    "tags": [
      "utility",
      "query"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaSqlParameter",
    "popularityRank": 348,
    "synopsis": "Creates a SqlParameter object for use with parameterized queries and stored procedures.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaSqlParameter View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a SqlParameter object for use with parameterized queries and stored procedures. 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. Syntax New-DbaSqlParameter [[-CompareInfo] ] [[-DbType] ] [[-Direction] ] [-ForceColumnEncryption] [-IsNullable] [[-LocaleId] ] [[-Offset] ] [[-ParameterName] ] [[-Precision] ] [[-Scale] ] [[-Size] ] [[-SourceColumn] ] [-SourceColumnNullMapping] [[-SourceVersion] ] [[-SqlDbType] ] [[-SqlValue] ] [[-TypeName] ] [[-UdtTypeName] ] [[-Value] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Creates a SqlParameter object that can be used with Invoke-DbaQuery PS C:\\> New-DbaSqlParameter -ParameterName json_result -SqlDbType NVarChar -Size -1 -Direction Output Example 2: Creates an output parameter and uses it to invoke a stored procedure PS C:\\> $output = New-DbaSqlParameter -ParameterName json_result -SqlDbType NVarChar -Size -1 -Direction Output PS C:\\> Invoke-DbaQuery -SqlInstance localhost -Database master -CommandType StoredProcedure -Query my_proc -SqlParameter $output PS C:\\> $output.Value Optional Parameters -CompareInfo Defines how string comparisons are performed when this parameter is used in SQL operations. Controls case sensitivity, accent sensitivity, and other collation behaviors. Use this when you need specific string comparison rules that differ from the database's default collation settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use SqlDbType instead for SQL Server-specific operations, as it provides better type mapping and performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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). Required when creating output parameters for stored procedures that return values through parameters rather than result sets. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Input,Output,InputOutput,ReturnValue | -ForceColumnEncryption Enforces encryption of a parameter when using Always Encrypted. If SQL Server informs the driver that the parameter does not need to be encrypted, the query using the parameter will fail. This 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IsNullable Indicates whether the parameter can accept null values, but does not enforce null validation during query execution. This is primarily used for metadata purposes and DataAdapter operations, not for runtime null checking. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -LocaleId Specifies the locale identifier (LCID) that determines regional formatting conventions for the parameter value. Use this when working with locale-specific data formatting, particularly for date, time, and numeric values that need specific regional representation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Offset Specifies the starting position within the parameter value when working with binary or text data types. Useful when you need to read or write data starting from a specific byte position rather than the beginning of the value. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ParameterName Specifies the name of the parameter as it appears in the SQL query or stored procedure, including the '@' prefix. Must match exactly with parameter names defined in your SQL statements for proper parameter binding. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -Precision Defines the total number of digits for numeric data types like decimal or numeric columns. Required when working with precise financial calculations or when the target column has specific precision requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Scale Specifies the number of decimal places for numeric data types, working together with Precision. Essential for financial data and calculations where exact decimal representation is required to prevent rounding errors. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Size Defines the maximum length for variable-length data types like varchar, nvarchar, or varbinary columns. Use -1 for MAX data types (varchar(max), nvarchar(max)) to handle large text or binary data without size restrictions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -SourceColumn Maps the parameter to a specific column name in a DataTable or DataSet for bulk operations. Used primarily with DataAdapter operations when you need to map parameter values to specific columns during data updates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SourceColumnNullMapping Indicates whether the source column allows null values, helping SqlCommandBuilder generate correct UPDATE statements. Important for DataAdapter scenarios where the framework needs to understand column nullability for proper SQL generation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SourceVersion Specifies which version of data to use from a DataRow when the parameter value comes from a DataSet. Use 'Current' for modified data, 'Original' for unchanged data, or 'Proposed' for uncommitted changes during DataAdapter operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Original,Current,Proposed,Default | -SqlDbType Specifies the SQL Server data type for the parameter, ensuring proper type mapping and optimal performance. Prefer this over DbType for SQL Server operations as it provides exact type matching with SQL Server's native data types. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this when you need to handle SQL null values explicitly or work with SQL Server-specific type behaviors that differ from .NET types. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TypeName Specifies the user-defined table type name when passing DataTable objects as table-valued parameters to stored procedures. The type name must match a table type defined in the database schema and is essential for bulk data operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -UdtTypeName Specifies the name of a user-defined data type (UDT) or CLR type when working with custom SQL Server data types. Required when passing complex objects or custom data structures that extend beyond standard SQL Server data types. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Value Specifies the actual data value to pass to the SQL parameter, automatically handling type conversion from .NET to SQL types. The most commonly used parameter property for passing data into queries and stored procedures safely. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.Data.SqlClient.SqlParameter Returns 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 parameterized queries. Properties available on the returned object include: CompareInfo: String comparison rules for the parameter DbType: .NET data type from System.Data.DbType enumeration Direction: Parameter direction (Input, Output, InputOutput, or ReturnValue) ForceColumnEncryption: Boolean indicating Always Encrypted enforcement IsNullable: Boolean indicating if parameter accepts null values LocaleId: Integer locale identifier (LCID) for formatting Offset: Starting position within parameter value for binary/text data ParameterName: The name of the parameter (including '@' prefix) Precision: Total number of digits for numeric types Scale: Number of decimal places for numeric types Size: Maximum length for variable-length data types (use -1 for MAX) SourceColumn: Column name mapping for DataTable operations SourceColumnNullMapping: Boolean for DataAdapter null mapping SourceVersion: Data version selection (Original, Current, Proposed, Default) SqlDbType: SQL Server-specific data type SqlValue: Parameter value using SQL Server-specific types TypeName: User-defined table type name for table-valued parameters UdtTypeName: User-defined data type (UDT) or CLR type name Value: The actual parameter value passed to SQL &nbsp;"
  },
  {
    "name": "New-DbaSsisCatalog",
    "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't automatically create this catalog - it's 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't have to manually run SQL scripts or navigate through SQL Server Management Studio wizards.",
    "category": "Utilities",
    "tags": [
      "ssis",
      "ssisdb",
      "catalog"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaSsisCatalog",
    "popularityRank": 493,
    "synopsis": "Creates and enables the SSIS Catalog (SSISDB) database on SQL Server 2012+ instances",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "New-DbaSsisCatalog View Source Stephen Bennett, https://sqlnotesfromtheunderground.wordpress.com/ Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates and enables the SSIS Catalog (SSISDB) database on SQL Server 2012+ instances 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't automatically create this catalog - it's 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't have to manually run SQL scripts or navigate through SQL Server Management Studio wizards. Syntax New-DbaSsisCatalog [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [[-SecurePassword] ] [[-SsisCatalog] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates the SSIS Catalog on server DEV01 with the specified password PS C:\\> $SecurePassword = Read-Host -AsSecureString -Prompt \"Enter password\" PS C:\\> New-DbaSsisCatalog -SqlInstance DEV01 -SecurePassword $SecurePassword Example 2: Creates the SSIS Catalog on server DEV01 with the specified password in the credential prompt PS C:\\> New-DbaSsisCatalog -SqlInstance sql2016 -Credential usernamedoesntmatter Creates the SSIS Catalog on server DEV01 with the specified password in the credential prompt. As the example username suggets the username does not matter. This is simply an easier way to get a secure password. Required Parameters -SqlInstance SQL Server you wish to run the function on. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. This approach simplifies password input by allowing you to use Get-Credential, which presents a secure password prompt dialog. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 in SSISDB. Use Read-Host -AsSecureString or ConvertTo-SecureString to create this value securely without exposing the password in plain text. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -SsisCatalog Specifies the name for the SSIS catalog database that will be created. Defaults to 'SSISDB' which is the Microsoft standard name. Only change this if your organization has specific naming requirements, as most SSIS tooling and documentation assumes the standard SSISDB name. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | SSISDB | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SSIS Catalog successfully created, containing connection context and creation status. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) SsisCatalog: The name of the SSIS Catalog database that was created Created: Boolean indicating the catalog was successfully created (always $true when object is returned) &nbsp;"
  },
  {
    "name": "New-DbatoolsSupportPackage",
    "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't 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.",
    "category": "Advanced Features",
    "tags": [
      "module",
      "support"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbatoolsSupportPackage",
    "popularityRank": 628,
    "synopsis": "Creates a comprehensive diagnostic package for troubleshooting dbatools module issues and bugs.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbatoolsSupportPackage View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a comprehensive diagnostic package for troubleshooting dbatools module issues and bugs. 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. The 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. The package includes: Operating system and hardware information (CPU, RAM, OS version) PowerShell and .NET framework versions and loaded modules Your PowerShell command history from the current session dbatools internal message and error logs Complete console buffer contents (everything currently visible in your PowerShell window) Loaded assemblies and their versions Any additional variables you specify The output file is automatically created on your desktop (or home directory if desktop doesn't 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. Syntax New-DbatoolsSupportPackage [[-Path] ] [[-Variables] ] [-PassThru] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates a large support pack in order to help us troubleshoot stuff PS C:\\> New-DbatoolsSupportPackage Optional Parameters -Path Specifies the directory where the support package ZIP file will be created. Defaults to your desktop, or home directory if desktop doesn't exist. Use this when you need the diagnostic file saved to a specific location for easier access or compliance requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | \"$($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. Use this when specific variables contain connection strings, configuration settings, or data relevant to reproducing your issue. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PassThru Returns the FileInfo object for the created ZIP file instead of just displaying its location. Use this when you need to programmatically work with the support package file, such as uploading it automatically or getting its size. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.IO.FileInfo Returns a FileInfo object representing the created diagnostic support package ZIP file. Properties: 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) Name: The filename of the ZIP archive (e.g., dbatools_support_pack_2024_12_29-14_30_45.zip) DirectoryName: The directory path containing the ZIP file Directory: The parent directory object Length: The size of the ZIP file in bytes Exists: Boolean indicating the file exists ($true upon successful creation) CreationTime: DateTime when the file was created LastWriteTime: DateTime when the file was last modified LastAccessTime: DateTime when the file was last accessed The ZIP archive contains comprehensive diagnostic data for troubleshooting: Operating system and hardware information PowerShell and .NET framework versions Loaded modules, snapins (on Windows PowerShell), and assemblies Complete console buffer (all visible commands and output) PowerShell command history from the current session dbatools message and error logs Any additional variables specified via -Variables parameter Note: 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 displayed. &nbsp;"
  },
  {
    "name": "New-DbaXESession",
    "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.",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "New",
    "popular": false,
    "url": "/New-DbaXESession",
    "popularityRank": 486,
    "synopsis": "Creates a new Extended Events session object for programmatic configuration and deployment.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "New-DbaXESession View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Creates a new Extended Events session object for programmatic configuration and deployment. 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. Syntax New-DbaXESession [-SqlInstance] [[-SqlCredential] ] [-Name] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Returns a new XE Session object from sql2017 then adds an event, an action then creates it PS C:\\> $session = New-DbaXESession -SqlInstance sql2017 -Name XeSession_Test PS C:\\> $event = $session.AddEvent(\"sqlserver.file_written\") PS C:\\> $event.AddAction(\"package0.callstack\") PS C:\\> $session.Create() Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -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. Choose descriptive names that indicate the monitoring purpose, such as \"Query_Performance_Monitor\" or \"Security_Audit_Session\". | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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 the 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 Extended Events cmdlets. &nbsp;"
  },
  {
    "name": "Publish-DbaDacPackage",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "deployment",
      "dacpac",
      "bacpac"
    ],
    "verb": "Publish",
    "popular": false,
    "url": "/Publish-DbaDacPackage",
    "popularityRank": 144,
    "synopsis": "Deploys DACPAC or BACPAC files to SQL Server databases using the DacFx framework",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Publish-DbaDacPackage View Source Richie lee (@richiebzzzt) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Deploys DACPAC or BACPAC files to SQL Server databases using the DacFx framework 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. Syntax Publish-DbaDacPackage [-SqlInstance ] [-SqlCredential ] -Path -Database [-ConnectionString ] [-GenerateDeploymentReport] [-ScriptOnly] [-Type ] [-OutputPath ] [-IncludeSqlCmdVars] [-DacOption ] [-EnableException] [-DacFxPath ] [-WhatIf] [-Confirm] [ ] Publish-DbaDacPackage [-SqlInstance ] [-SqlCredential ] -Path [-PublishXml ] -Database [-ConnectionString ] [-GenerateDeploymentReport] [-ScriptOnly] [-Type ] [-OutputPath ] [-IncludeSqlCmdVars] [-EnableException] [-DacFxPath ] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Uses DacOption object to set Deployment Options and updates DB1 database on sql2016 from the db.dacpac dacpac... PS C:\\> $options = New-DbaDacOption -Type Dacpac -Action Publish PS C:\\> $options.DeployOptions.DropObjectsNotInSource = $true PS C:\\> Publish-DbaDacPackage -SqlInstance sql2016 -Database DB1 -DacOption $options -Path c:\\temp\\db.dacpac Uses 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. Example 2: Updates WideWorldImporters on sql2017 from the sql2016-WideWorldImporters.dacpac using the... PS C:\\> Publish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\\temp\\sql2016-WideWorldImporters.dacpac -PublishXml C:\\temp\\sql2016-WideWorldImporters-publish.xml -Confirm Updates WideWorldImporters on sql2017 from the sql2016-WideWorldImporters.dacpac using the sql2016-WideWorldImporters-publish.xml publish profile. Prompts for confirmation. Example 3: Creates a publish profile at C:\\temp\\sql2016-db2-publish.xml, exports the .dacpac to... PS C:\\> New-DbaDacProfile -SqlInstance sql2016 -Database db2 -Path C:\\temp PS C:\\> Export-DbaDacPackage -SqlInstance sql2016 -Database db2 | Publish-DbaDacPackage -PublishXml C:\\temp\\sql2016-db2-publish.xml -Database db1, db2 -SqlInstance sql2017 Creates a publish profile at C:\\temp\\sql2016-db2-publish.xml, exports the .dacpac to $home\\Documents\\sql2016-db2.dacpac. Does not prompt for confirmation. then publishes it to the sql2017 server database db2 Example 4: Publishes the dacpac using a specific dacfx library PS C:\\> $loc = \"C:\\Users\\bob\\source\\repos\\Microsoft.Data.Tools.Msbuild\\lib\\net46\\Microsoft.SqlServer.Dac.dll\" PS C:\\> Publish-DbaDacPackage -SqlInstance \"local\" -Database WideWorldImporters -Path C:\\temp\\WideWorldImporters.dacpac -PublishXml C:\\temp\\WideWorldImporters.publish.xml -DacFxPath $loc -Confirm Publishes the dacpac using a specific dacfx library. Prompts for confirmation. Example 5: Does not deploy the changes, but will generate the deployment script that would be executed against... PS C:\\> Publish-DbaDacPackage -SqlInstance sql2017 -Database WideWorldImporters -Path C:\\temp\\sql2016-WideWorldImporters.dacpac -PublishXml C:\\temp\\sql2016-WideWorldImporters-publish.xml -ScriptOnly Does not deploy the changes, but will generate the deployment script that would be executed against WideWorldImporters. Required Parameters -Path Specifies the filesystem path to the DACPAC or BACPAC file to deploy. The function automatically detects file type based on the extension. Use this to point to your compiled database project (.dacpac) or exported database backup with data (.bacpac). | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | -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. The database will be created if it doesn't exist, or updated to match the schema if it already exists. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Only SQL authentication is supported. When not specified, uses Trusted Authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this to control deployment behavior like dropping objects not in source, ignoring permissions, or setting variable values for different environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ConnectionString Specifies the connection string to connect to the target SQL Server instance. Alternative to using SqlInstance and SqlCredential parameters. Use this when you need specific connection properties or when connecting through alternative authentication methods not supported by SqlInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -GenerateDeploymentReport Creates an XML deployment report showing what changes were made during the deployment. The report is saved to the OutputPath directory. Use this for deployment auditing, troubleshooting failed deployments, or documenting changes applied to production databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ScriptOnly Generates the deployment script without executing it against the target database. The script is saved to the OutputPath directory for review. Use this for change approval processes, manual deployment scenarios, or to review what changes would be applied before executing them. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Type Specifies whether to deploy a DACPAC (schema only) or BACPAC (schema and data) file. Defaults to DACPAC. Use DACPAC for deploying database schema changes from development to production, or BACPAC for full database restore including data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Dacpac | | Accepted Values | 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. Use this to organize output files in a specific location for review, version control, or automated deployment processes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -IncludeSqlCmdVars Enables replacement of SqlCmd variables in the publish profile with their actual values during deployment. Use this when your deployment scripts or publish profile contain variables like $(Environment) or $(ServerName) that need to be substituted with environment-specific values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DacOption Specifies deployment options object controlling how the deployment behaves. Created using New-DbaDacOption with specific deployment settings. Use this to programmatically control deployment behavior instead of using a publish profile XML file, such as dropping objects not in source or ignoring permissions. | Property | Value | | --- | --- | | Alias | Option | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DacFxPath Specifies the path to a specific version of the Microsoft.SqlServer.Dac.dll library to use for deployment operations. Use this when you need a specific DacFx version for compatibility with your SQL Server version or to use features from a newer DacFx release. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database deployed, with properties varying based on the deployment type and options specified. Properties when deploying DACPAC (Type = 'Dacpac'): Default properties (always included): ComputerName: The computer name of the SQL Server instance (string) InstanceName: The SQL Server instance name (string) SqlInstance: The full SQL Server instance name in computer\\instance format (string) Database: The target database name (string) Dacpac: Path to the deployed DACPAC file (string) PublishXml: Path to the publish profile XML file used, if any (string) Result: Deployment result messages and status output (string) DeployOptions: The deployment options object used for the deployment, excluding SqlCommandVariableValues (object) SqlCmdVariableValues: Array of SqlCmd variable names that were applied (string[]) Additional properties when using -ScriptOnly or -GenerateDeploymentReport: DatabaseScriptPath: Full path to the generated database deployment script file (string) MasterDbScriptPath: Full path to the generated master database script file, if generated (string) DeploymentReport: Full path to the XML deployment report file (string) Properties when deploying BACPAC (Type = 'Bacpac'): ComputerName: The computer name of the SQL Server instance (string) InstanceName: The SQL Server instance name (string) SqlInstance: The full SQL Server instance name in computer\\instance format (string) Database: The target database name (string) Bacpac: Path to the deployed BACPAC file (string) Result: Deployment result messages and status output (string) DeployOptions: The deployment options object used for the import (object) &nbsp;"
  },
  {
    "name": "Read-DbaAuditFile",
    "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's 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't 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.",
    "category": "Security",
    "tags": [
      "xe",
      "audit",
      "security"
    ],
    "verb": "Read",
    "popular": false,
    "url": "/Read-DbaAuditFile",
    "popularityRank": 336,
    "synopsis": "Parses SQL Server audit files (.sqlaudit) into structured event data for security analysis and compliance reporting.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Read-DbaAuditFile View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Parses SQL Server audit files (.sqlaudit) into structured event data for security analysis and compliance reporting. 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's 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't 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. Syntax Read-DbaAuditFile [-Path] [-Raw] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns events from C:\\temp\\logins.sqlaudit PS C:\\> Read-DbaAuditFile -Path C:\\temp\\logins.sqlaudit Example 2: Returns events from all .sqlaudit files in C:\\temp\\audit PS C:\\> Get-ChildItem C:\\temp\\audit\\.sqlaudit | Read-DbaAuditFile Example 3: Reads remote Audit details by accessing the file over the admin UNC share PS C:\\> Get-DbaInstanceAudit -SqlInstance sql2014 -Audit LoginTracker | Read-DbaAuditFile Required Parameters -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. Supports 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 piping from other dbatools audit commands. | Property | Value | | --- | --- | | Alias | FullName | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Raw Returns the unprocessed enumeration object instead of structured PowerShell objects. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Object (when -Raw is specified) Returns the raw enumeration object containing unprocessed audit event data from Read-XEvent. PSCustomObject (default) Returns one object per audit event with the following standard properties: name: The name of the audit event (string) timestamp: The timestamp when the event occurred (datetime) Additional properties are dynamically added based on the audit file contents and include: Fields.: All field names present in the audit events (properties vary based on audit configuration) Actions.: All action names from the audit events with the action suffix only (e.g., 'session_id' from 'server_principal_name.session_id') The 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 given audit file. &nbsp;"
  },
  {
    "name": "Read-DbaBackupHeader",
    "description": "Uses SQL Server's 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's 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.",
    "category": "Backup & Restore",
    "tags": [
      "disasterrecovery",
      "backup",
      "restore"
    ],
    "verb": "Read",
    "popular": false,
    "url": "/Read-DbaBackupHeader",
    "popularityRank": 261,
    "synopsis": "Extracts backup metadata from SQL Server backup files without restoring them",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Read-DbaBackupHeader View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Extracts backup metadata from SQL Server backup files without restoring them Description Uses SQL Server's 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. The 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's built-in backup reading capabilities. Supports 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. Syntax Read-DbaBackupHeader [-SqlInstance] [[-SqlCredential] ] [-Path] [-Simple] [-FileList] [[-StorageCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Logs into sql2016 using Windows authentication and reads the local file on sql2016, S:\\backups\\mydb\\mydb.bak PS C:\\> Read-DbaBackupHeader -SqlInstance sql2016 -Path S:\\backups\\mydb\\mydb.bak Logs into sql2016 using Windows authentication and reads the local file on sql2016, S:\\backups\\mydb\\mydb.bak. If you are running this command on a workstation and connecting remotely, remember that sql2016 cannot access files on your own workstation. Example 2: Logs into sql2016 and reads two backup files - mydb.bak and otherdb.bak PS C:\\> Read-DbaBackupHeader -SqlInstance sql2016 -Path \\\\nas\\sql\\backups\\mydb\\mydb.bak, \\\\nas\\sql\\backups\\otherdb\\otherdb.bak Logs into sql2016 and reads two backup files - mydb.bak and otherdb.bak. The SQL Server service account must have rights to read this file. Example 3: Logs into the local workstation (or computer) and shows simplified output about C:\\temp\\myfile.bak PS C:\\> Read-DbaBackupHeader -SqlInstance . -Path C:\\temp\\myfile.bak -Simple Logs 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. Example 4: Displays detailed information about each of the datafiles contained in the backupset PS C:\\> $backupinfo = Read-DbaBackupHeader -SqlInstance . -Path C:\\temp\\myfile.bak PS C:\\> $backupinfo.FileList Example 5: Also returns detailed information about each of the datafiles contained in the backupset PS C:\\> Read-DbaBackupHeader -SqlInstance . -Path C:\\temp\\myfile.bak -FileList Example 6: Reads the two files and returns only backups larger than 100 MB PS C:\\> \"C:\\temp\\myfile.bak\", \"\\backupserver\\backups\\myotherfile.bak\" | Read-DbaBackupHeader -SqlInstance sql2016 | Where-Object { $_.BackupSize.Megabyte -gt 100 } Example 7: Gets a list of all .bak files on the \\\\nas\\sql share and reads the headers using the server named &quot;sql2016&quot; PS C:\\> Get-ChildItem \\\\nas\\sql\\*.bak | Read-DbaBackupHeader -SqlInstance sql2016 Gets 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. Example 8: Gets the backup header information from the SQL Server backup file stored at... PS C:\\> Read-DbaBackupHeader -SqlInstance sql2016 -Path https://dbatoolsaz.blob.core.windows.net/azbackups/restoretime/restoretime_201705131850.bak -StorageCredential AzureBackupUser Gets 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 Example 9: Gets the backup header information from the SQL Server backup file stored in an AWS S3 bucket PS C:\\> Read-DbaBackupHeader -SqlInstance sql2022 -Path s3://s3.us-west-2.amazonaws.com/mybucket/backups/mydb.bak -StorageCredential MyS3Credential Gets 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. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. The 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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Simple Returns a simplified output with only essential columns: DatabaseName, BackupFinishDate, RecoveryModel, BackupSize, CompressedBackupSize, DatabaseCreationDate, UserName, ServerName, SqlVersion, and BackupPath. Use this when you need a quick overview of backup files without the full 50+ columns of detailed metadata. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when planning restores to different locations or when you need to understand the file structure before performing a restore operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Required when reading backup files stored in Azure blob storage or S3. The credential must already exist on the target SQL Server instance. For Azure: The credential must contain valid Azure storage account keys or SAS tokens. For S3: The credential must use Identity = 'S3 Access Key' and Secret = 'AccessKeyID:SecretKeyID'. Requires SQL Server 2022 or higher. | Property | Value | | --- | --- | | Alias | AzureCredential,S3Credential | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Data.DataRow (default output) Returns one object per backup set found in the backup file. When -Simple is not specified, returns the full DataTable with backup header metadata including: Default properties: DatabaseName: Name of the database that was backed up BackupFinishDate: DateTime when the backup completed RecoveryModel: Database recovery model (Simple, Full, or BulkLogged) BackupSize: Size of the backup (dbasize object with Byte, KB, MB, GB properties) CompressedBackupSize: Size of the compressed backup if compression was used (dbasize object) DatabaseCreationDate: DateTime the database was created UserName: Login that performed the backup ServerName: SQL Server instance name where backup was created SqlVersion: SQL Server version string (e.g., \"SQL Server 2016\", \"SQL Server 2019\") BackupPath: Full path to the backup file FileList: Collection of backup file details (see -FileList for details) Additional properties from SMO Restore.ReadBackupHeader(): BackupType: Type of backup (Database, Differential, Log, etc.) BackupName: Name given to the backup set Position: Position of this backup set within the file (1 for first, 2 for second, etc.) DatabaseVersion: Internal database version number IsPassword: Whether the backup is password-protected (0 or 1) IsCopyOnly: Whether this is a copy-only backup (0 or 1) ContinuationFolk: Whether this is a continuation of a previous backup (0 or 1) HasBulkLoggedData: Whether the backup contains bulk-logged operations (0 or 1) IsSnapshot: Whether this is a snapshot backup (0 or 1) IsDamaged: Whether the backup is marked as damaged (0 or 1) StarTime: DateTime when backup started CompatibilityLevel: Compatibility level of the database SoftwareVendorId: Software vendor identifier SoftwareVersionMajor: Major version of SQL Server that created backup SoftwareVersionMinor: Minor version of SQL Server that created backup SoftwareVersionBuild: Build number of SQL Server that created backup MachineName: Computer name where backup was created Flags: Backup flags and options BindingId: Binding ID RecoveryFork: Recovery fork identifier Collation: Database collation FamilyGuid: Family GUID for backup family tracking HasBackupChecksums: Whether checksums are present (0 or 1) IsSealedBackup: Whether backup is sealed/complete (0 or 1) System.Data.DataRow (when -Simple is specified) Returns one object per backup set with only essential backup metadata columns: DatabaseName: Name of the database that was backed up BackupFinishDate: DateTime when the backup completed RecoveryModel: Database recovery model (Simple, Full, or BulkLogged) BackupSize: Size of the backup (dbasize object with Byte, KB, MB, GB properties) CompressedBackupSize: Size of the compressed backup (dbasize object) DatabaseCreationDate: DateTime the database was created UserName: Login that performed the backup ServerName: SQL Server instance name SqlVersion: SQL Server version string BackupPath: Full path to the backup file System.Data.DataRow (when -FileList is specified) Returns detailed information about each data and log file contained within the backup set(s): LogicalName: Logical name of the file as defined in the database PhysicalName: Physical file path where the file is stored Type: File type (D for Data, L for Log, etc.) FileGroupName: Filegroup that contains this file Size: Size of the file in bytes MaxSize: Maximum size of the file in bytes FileId: File ID number in the database CreateLsn: Log sequence number when file was created DropLsn: Log sequence number when file was dropped (if applicable) UniqueId: Unique identifier for the file ReadOnlyLsn: Log sequence number when file became read-only ReadWriteLsn: Log sequence number when file became read-write BackupSizeInBytes: Size of this file in the backup SourceBlockSize: Original block size when file was created FileGroupId: ID of the filegroup containing this file LogGroupGuid: Identifier for log group DifferentialBaseLsn: LSN of the differential base DifferentialBaseGuid: GUID of the differential base IsReadOnly: Whether the file is read-only (0 or 1) IsPresent: Whether the file is present in this backup (0 or 1) TdeThumbprint: Transparent Data Encryption thumbprint if applicable &nbsp;"
  },
  {
    "name": "Read-DbaTraceFile",
    "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's 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.",
    "category": "Performance",
    "tags": [
      "trace"
    ],
    "verb": "Read",
    "popular": false,
    "url": "/Read-DbaTraceFile",
    "popularityRank": 521,
    "synopsis": "Parses SQL Server trace files and extracts events for security auditing and performance analysis",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Read-DbaTraceFile View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Parses SQL Server trace files and extracts events for security auditing and performance analysis 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. The function can read both active trace files and archived trace files, including SQL Server's 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. Common 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. Syntax Read-DbaTraceFile [-SqlInstance] [[-SqlCredential] ] [[-Path] ] [[-Database] ] [[-Login] ] [[-Spid] ] [[-EventClass] ] [[-ObjectType] ] [[-ErrorId] ] [[-EventSequence] ] [[-TextData] ] [[-ApplicationName] ] [[-ObjectName] ] [[-Where] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Reads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server PS C:\\> Read-DbaTraceFile -SqlInstance sql2016 -Database master, tempdb -Path C:\\traces\\big.trc Reads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server. Filters only results that have master or tempdb as the DatabaseName. Example 2: Reads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server PS C:\\> Read-DbaTraceFile -SqlInstance sql2016 -Database master, tempdb -Path C:\\traces\\big.trc -TextData 'EXEC SP_PROCOPTION' Reads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server. Filters only results that have master or tempdb as the DatabaseName and that have 'EXEC SP_PROCOPTION' somewhere in the text. Example 3: Reads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server PS C:\\> Read-DbaTraceFile -SqlInstance sql2016 -Path C:\\traces\\big.trc -Where \"LinkedServerName = 'myls' and StartTime > '5/30/2017 4:27:52 PM'\" Reads the tracefile C:\\traces\\big.trc, stored on the sql2016 sql server. Filters only results where LinkServerName = myls and StartTime is greater than '5/30/2017 4:27:52 PM'. Example 4: Reads every trace file on sql2014 PS C:\\> Get-DbaTrace -SqlInstance sql2014 | Read-DbaTraceFile Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Path Specifies the full path to the trace file (.trc) on the SQL Server instance. When omitted, reads from the default system trace that automatically captures configuration changes and security events. Use this when analyzing specific trace files created by custom traces or archived default traces. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Database Filters trace events to show only those affecting specific databases by name. Use this to focus analysis on particular databases when investigating issues or tracking changes. Accepts multiple database names and supports wildcards for pattern matching. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Filters trace events to show only those performed by specific SQL Server logins. Essential for security investigations to track activities by suspected user accounts or service accounts. Accepts multiple login names for comprehensive user activity analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Spid Filters trace events to show only those from specific Session Process IDs (SPIDs). Useful for tracking all activities within particular database sessions or troubleshooting specific connection issues. Accepts multiple SPID values to monitor several concurrent sessions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EventClass Filters trace events by event class numbers to focus on specific types of database activities. Common values include login events (14), logout events (15), SQL statements (10-12), and security audit events (102-111). Use this to narrow analysis to particular event types like failed logins or DDL changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ObjectType Filters trace events by the type of database object being accessed or modified. Common values include tables, views, stored procedures, functions, and triggers. Use this when investigating changes to specific types of database objects during schema modifications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ErrorId Filters trace events to show only those with specific SQL Server error numbers. Common values include login failures (18456), permission denied (229), and deadlock victims (1205). Use this to focus on particular error conditions when troubleshooting recurring issues or security events. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EventSequence Filters trace events by their sequence number within the trace file. Use this to retrieve specific events when you know their exact sequence numbers from previous analysis. Helpful for pinpointing events that occurred at precise moments during an incident. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TextData Filters trace events by searching within the SQL statements or command text using pattern matching. Use this to find specific queries, stored procedure calls, or SQL commands that contain particular keywords. Supports partial text matching, making it ideal for finding all queries containing specific table names or SQL constructs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ApplicationName Filters trace events by the application name that initiated the database connection. Use this to isolate activities from specific applications like SQL Server Management Studio, custom applications, or services. Supports pattern matching to group similar application names or versions together. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ObjectName Filters trace events by the name of the database object being accessed or modified. Use this to track all operations against specific tables, views, procedures, or other database objects. Supports pattern matching to find objects with similar naming conventions or prefixes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Where Specifies a custom SQL WHERE clause for complex filtering beyond the standard parameters. Use this for advanced queries combining multiple conditions, date ranges, or custom logic that other parameters cannot achieve. Do not include the word \"WHERE\" - it is added automatically. Here are the available columns: TextData BinaryData DatabaseID TransactionID LineNumber NTUserName NTDomainName HostName ClientProcessID ApplicationName LoginName SPID Duration StartTime EndTime Reads Writes CPU Permissions Severity EventSubClass ObjectID Success IndexID IntegerData ServerName EventClass ObjectType NestLevel State Error Mode Handle ObjectName DatabaseName FileName OwnerName RoleName TargetUserName DBUserName LoginSid TargetLoginName TargetLoginSid ColumnPermissions LinkedServerName ProviderName MethodName RowCounts RequestID XactSequence EventSequence BigintData1 BigintData2 GUID IntegerData2 ObjectID2 Type OwnerID ParentName IsSystem Offset SourceDatabaseID SqlHandle SessionLoginName PlanHandle GroupID | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Data.DataRow Returns one object per trace event from the SQL Server trace file, with the following properties added by the command: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) All other properties come from fn_trace_gettable function, including: TextData: SQL statement or command text associated with the event BinaryData: Binary data captured for the event DatabaseID: Numeric identifier of the database DatabaseName: Name of the database affected by the event LoginName: SQL Server login that performed the event SPID: Session Process ID of the connection StartTime: DateTime when the event started EndTime: DateTime when the event ended Duration: Duration of the event in milliseconds Reads: Number of logical disk reads Writes: Number of logical disk writes CPU: CPU time consumed in milliseconds EventClass: Event class number (e.g., 10 for SQL:StmtCompleted, 14 for Login) EventSequence: Sequential number of the event ApplicationName: Name of the client application HostName: Name of the client computer ObjectName: Name of the database object being accessed ObjectType: Type of object being accessed Error: SQL Server error number if an error occurred Severity: Severity level of the error Success: Whether the operation succeeded (0 or 1) NestLevel: Nesting level of the stored procedure LineNumber: Line number within the batch or procedure TransactionID: Transaction identifier NTUserName: Windows domain and user name NTDomainName: Windows domain name ColumnPermissions: Column-level permissions being checked Permissions: Object permissions being checked State: Object state Mode: Lock mode (if applicable) Handle: Handle reference OwnerName: Name of the object owner RoleName: Database role name TargetUserName: Target user for impersonation operations DBUserName: Database user name LoginSid: SQL Server login SID TargetLoginName: Target login for security operations TargetLoginSid: Target login SID LinkedServerName: Name of linked server being accessed ProviderName: OLE DB provider name MethodName: OLE DB method name RowCounts: Number of rows affected RequestID: Batch request ID XactSequence: Transaction sequence number BigintData1: First 64-bit integer data BigintData2: Second 64-bit integer data GUID: Globally unique identifier IntegerData: Integer data value IntegerData2: Second integer data value ObjectID: Object ID number ObjectID2: Second object ID number EventSubClass: Event subclass number IndexID: Index ID ClientProcessID: Process ID of the client application ServerName: Name of the SQL Server instance Type: Type identifier OwnerID: Owner object ID ParentName: Parent object name IsSystem: Whether the object is a system object (0 or 1) Offset: Offset value for the event SourceDatabaseID: Source database ID SqlHandle: SQL handle reference SessionLoginName: Session login name PlanHandle: Query plan handle GroupID: Group ID for the event All properties are accessible using Select-Object * or standard pipeline operations. &nbsp;"
  },
  {
    "name": "Read-DbaTransactionLog",
    "description": "Uses SQL Server's 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.",
    "category": "Utilities",
    "tags": [
      "log",
      "logfile",
      "utility"
    ],
    "verb": "Read",
    "popular": false,
    "url": "/Read-DbaTransactionLog",
    "popularityRank": 346,
    "synopsis": "Retrieves raw transaction log records from a database using fn_dblog for forensic analysis and troubleshooting",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Read-DbaTransactionLog View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves raw transaction log records from a database using fn_dblog for forensic analysis and troubleshooting Description Uses SQL Server's 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. This 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. A 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. Syntax Read-DbaTransactionLog [-SqlInstance] [[-SqlCredential] ] [-Database] [-IgnoreLimit] [[-RowLimit] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Will read the contents of the transaction log of MyDatabase on SQL Server Instance sql2016 into the local... PS C:\\> $Log = Read-DbaTransactionLog -SqlInstance sql2016 -Database MyDatabase Will read the contents of the transaction log of MyDatabase on SQL Server Instance sql2016 into the local PowerShell object $Log Example 2: Will read the contents of the transaction log of MyDatabase on SQL Server Instance sql2016 into the local... PS C:\\> $Log = Read-DbaTransactionLog -SqlInstance sql2016 -Database MyDatabase -IgnoreLimit Will 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 Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Database Specifies the database whose transaction log records you want to analyze. The database must be online and in a normal state. Use this to target the specific database where you need to investigate transaction activity or perform forensic analysis. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IgnoreLimit Bypasses the built-in 0.5GB safety limit that prevents performance issues when reading large transaction logs. Use this when you need to analyze databases with large active logs, but be aware it may impact SQL Server performance during execution. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -RowLimit Limits the number of transaction log records returned by adding a TOP clause to the fn_dblog query. Use this when you only need recent transactions or want to prevent memory issues with very large logs. Automatically enables IgnoreLimit when specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject[] Returns 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. Common properties include: RecoveryUnitId: Identifier of the recovery unit LSN: Log Sequence Number identifying the position in the transaction log LOP: The log operation type (e.g., INSERT, DELETE, UPDATE, ALLOCATE, DEALLOCATE, etc.) Transaction ID: The transaction identifier BeginTime: When the operation began AllocUnitName: Name of the allocation unit affected RowIdentifier: Identifies the specific row affected DBFragId: Database fragmentation identifier XactId: Extended transaction ID XactOp: Extended transaction operation Context: Operation context flags AllocUnitId: Identifier of the allocation unit ObjectId: Object ID of the table or index IndexId: Index ID if applicable PrevPageLSN: LSN of the previous page in the log chain PageId: Page ID affected by the operation The 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. &nbsp;"
  },
  {
    "name": "Read-DbaXEFile",
    "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 reads files from remote servers via Windows admin shares (e.g. \\\\server\\C$\\...). This means the PowerShell session must be running as a Windows account with administrative access to the SQL Server host â€” SqlCredential alone is not sufficient. This approach is Windows-only; it does not work for Linux-hosted SQL Server or Docker containers.\n\nIf you only know the session name and not the file path, use the full pipeline:\nGet-DbaXESession | Get-DbaXESessionTarget | Get-DbaXESessionTargetFile | Read-DbaXEFile",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Read",
    "popular": false,
    "url": "/Read-DbaXEFile",
    "popularityRank": 312,
    "synopsis": "Parses Extended Events trace files (.xel/.xem) into structured PowerShell objects for analysis",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Read-DbaXEFile View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Parses Extended Events trace files (.xel/.xem) into structured PowerShell objects for analysis 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. Perfect 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. When using pipeline input from Get-DbaXESession, the function automatically skips the file currently being written to avoid access conflicts, and reads files from remote servers via Windows admin shares (e.g. \\\\server\\C$\\...). This means the PowerShell session must be running as a Windows account with administrative access to the SQL Server host â€” SqlCredential alone is not sufficient. This approach is Windows-only; it does not work for Linux-hosted SQL Server or Docker containers. If you only know the session name and not the file path, use the full pipeline: Get-DbaXESession | Get-DbaXESessionTarget | Get-DbaXESessionTargetFile | Read-DbaXEFile Syntax Read-DbaXEFile [-Path] [-Raw] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns events from C:\\temp\\deadocks.xel PS C:\\> Read-DbaXEFile -Path C:\\temp\\deadocks.xel Example 2: Returns events from all .xel files in C:\\temp\\xe PS C:\\> Get-ChildItem C:\\temp\\xe\\.xel | Read-DbaXEFile Example 3: Reads remote XEvents by accessing the file over the Windows admin share (e.g PS C:\\> Get-DbaXESession -SqlInstance sql2019 -Session deadlocks | Read-DbaXEFile Reads remote XEvents by accessing the file over the Windows admin share (e.g. \\\\sql2019\\C$\\...). Requires the PowerShell session to be running as a Windows account with administrative access to the sql2019 host. Does not work with Linux-hosted SQL Server or Docker containers. Example 4: Reads XEvents from a session by name without needing to know the file path in advance PS C:\\> Get-DbaXESession -SqlInstance sql2019 -Session deadlocks | Get-DbaXESessionTarget | Get-DbaXESessionTargetFile | Read-DbaXEFile Reads XEvents from a session by name without needing to know the file path in advance. Uses Get-DbaXESessionTarget and Get-DbaXESessionTargetFile to resolve the physical .xel files via Windows admin shares, then reads them. Requires the PowerShell session to be running as a Windows account with read access to the target files on the SQL Server host. If the session is still running, stop it first to force a rollover so the latest events are flushed to disk. Required Parameters -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, Get-DbaXESession, or Get-DbaXESessionTargetFile. When using session objects from Get-DbaXESession, automatically accesses files via Windows admin shares and skips the current file being written to prevent access conflicts. Requires the PowerShell session to be running as a Windows account with administrative access to the SQL Server host. | Property | Value | | --- | --- | | Alias | FullName | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -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 advanced programmatic processing. By default, events are converted to PSCustomObjects with all fields and actions as individual properties for easier analysis and reporting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Microsoft.SqlServer.XEvent.XELite.XEvent[] (when -Raw is specified) Returns the native XEvent objects from the XELite reader with full access to XEvent properties and methods for advanced programmatic processing. PSCustomObject[] (default) Returns 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: Standard properties: name: The name of the Extended Event timestamp: The timestamp when the event was captured Dynamic properties vary based on the Extended Events session configuration and captured actions: All unique field names from the XEvent.Fields collection appear as individual properties All unique action names from the XEvent.Actions collection appear as individual properties (action names are normalized to remove the leading package.action prefix) For 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 trace might include: client_principal_name, server_principal_name, statement, etc. Use Select-Object to see all properties returned in the results. &nbsp;"
  },
  {
    "name": "Read-XEvent",
    "description": null,
    "category": "Utilities",
    "tags": [],
    "verb": "Read",
    "popular": false,
    "url": "/Read-XEvent",
    "popularityRank": 0,
    "synopsis": "\r\nRead-XEvent [-FileName <string>] [-ConnectionString <string>] [-SessionName <string>] [<CommonParameters>]\r\n",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Read-XEvent View Source Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters Synopsis Read-XEvent [-FileName ] [-ConnectionString ] [-SessionName ] [ ] Description Syntax Read-XEventsyntaxItem ---------- {@{name= Read-XEvent; CommonParameters=True; WorkflowCommonParameters=False; parameter=System.Object[]}} &nbsp; Examples &nbsp; Optional Parameters -ConnectionString | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileName | Property | Value | | --- | --- | | Alias | FullName | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SessionName | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | &nbsp;"
  },
  {
    "name": "Register-DbatoolsConfig",
    "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.",
    "category": "Utilities",
    "tags": [
      "module"
    ],
    "verb": "Register",
    "popular": false,
    "url": "/Register-DbatoolsConfig",
    "popularityRank": 328,
    "synopsis": "Registers an existing configuration object in registry.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Register-DbatoolsConfig View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Registers an existing configuration object in registry. Description Registers an existing configuration object in registry. This allows simple persisting of settings across powershell consoles. It also can be used to generate a registry template, which can then be used to create policies. Syntax Register-DbatoolsConfig [-Config ] [-FullName ] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-EnableException] [ ] Register-DbatoolsConfig [-Module] [[-Name] ] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Retrieves all configuration items that that start with message.style PS C:\\> Get-DbatoolsConfig message.style. | Register-DbatoolsConfig Retrieves all configuration items that that start with message.style. and registers them in registry for the current user. Example 2: Retrieves the configuration item &quot;message.consoleoutput.disable&quot; and registers it in registry as the default... PS C:\\> Register-DbatoolsConfig -FullName \"message.consoleoutput.disable\" -Scope SystemDefault Retrieves the configuration item \"message.consoleoutput.disable\" and registers it in registry as the default setting for all users on this machine. Example 3: Retrieves all configuration items of the module Message, then registers them in registry to enforce them for... PS C:\\> Register-DbatoolsConfig -Module Message -Scope SystemMandatory Retrieves all configuration items of the module Message, then registers them in registry to enforce them for all users on the current system. Example 4: Set the &quot;sql.connection.trustcert&quot; configuration to be $true, and then use the -PassThru parameter to be able... PS C:\\> Set-DbatoolsConfig -FullName sql.connection.trustcert -Value $true -PassThru | Register-DbatoolsConfig Set the \"sql.connection.trustcert\" configuration to be $true, and then use the -PassThru parameter to be able to pipe the output and register them in registry for the current user. Required Parameters -Module Module name containing the configuration settings to register, such as \"Message\" or \"SqlInstance\". Use this to register all configuration settings for a particular dbatools module at once. Combine with -Name parameter to filter which settings within the module get registered. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -Config Configuration object(s) to persist to registry or file system for future PowerShell sessions. Accepts pipeline input from Get-DbatoolsConfig to save specific settings like connection timeouts or SSL preferences. Use this when you have configuration objects you want to make permanent across dbatools sessions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -FullName Complete configuration setting name to register, such as \"sql.connection.trustcert\" or \"message.consoleoutput.disable\". Specify this when you know the exact setting name and want to persist that specific configuration. Use Get-DbatoolsConfig to discover available configuration names in your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Name Filters which configuration settings get registered when used with -Module parameter. Supports wildcards. Use this to register only specific settings within a module rather than all module settings. Defaults to \"\" which includes all settings for the specified module. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | * | -Scope Determines where the configuration is stored and who can access it. UserDefault applies to current user only, while SystemDefault affects all users on the machine. Use UserMandatory or SystemMandatory to enforce settings that cannot be overridden by individual users. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UserDefault | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs None This 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 Get-DbatoolsConfig to verify that settings have been registered. &nbsp;"
  },
  {
    "name": "Remove-DbaAgDatabase",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgDatabase",
    "popularityRank": 103,
    "synopsis": "Removes databases from availability groups on SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgDatabase View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes databases from availability groups on SQL Server instances. 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. Syntax Remove-DbaAgDatabase [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-AvailabilityGroup] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all databases from the ag1 and ag2 availability groups on sqlserver2012 PS C:\\> Remove-DbaAgDatabase -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false Removes all databases from the ag1 and ag2 availability groups on sqlserver2012. Does not prompt for confirmation. Example 2: Removes the pubs database from the ag1 availability group on sqlserver2012 PS C:\\> Remove-DbaAgDatabase -SqlInstance sqlserver2012 -AvailabilityGroup ag1 -Database pubs -Confirm:$false Removes the pubs database from the ag1 availability group on sqlserver2012. Does not prompt for confirmation. Example 3: Removes the availability groups returned from the Get-DbaAvailabilityGroup function PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAgDatabase Removes the availability groups returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation. Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to remove from their availability groups. Accepts multiple database names as an array. Required when using SqlInstance parameter. Use this to target specific databases rather than removing all databases from an availability group. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Limits the operation to databases within specific availability groups. When specified, only databases belonging to these availability groups will be removed. Useful when you have databases with the same name across multiple availability groups and need to target specific groups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group database objects from Get-DbaAgDatabase or database objects from Get-DbaDatabase through the pipeline. This enables efficient batch operations and complex filtering scenarios using the pipeline. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database successfully removed from the availability group. Properties: ComputerName: The computer name of the SQL Server instance where the database was removed InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) AvailabilityGroup: The name of the availability group from which the database was removed Database: The name of the database that was removed Status: String indicating the operation result (\"Removed\") &nbsp;"
  },
  {
    "name": "Remove-DbaAgentAlert",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "alert"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgentAlert",
    "popularityRank": 660,
    "synopsis": "Removes SQL Server Agent alerts from specified instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgentAlert View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Server Agent alerts from specified instances. Description Deletes SQL Server Agent alerts that monitor for specific errors, performance conditions, or system events. Useful for cleaning up obsolete alerts, removing test configurations, or managing alert policies across multiple instances. Can remove specific alerts by name, exclude certain alerts, or work with piped input from Get-DbaAgentAlert for selective removal. Returns detailed results showing which alerts were successfully removed and any errors encountered. Syntax Remove-DbaAgentAlert [-SqlInstance] [-SqlCredential ] [-Alert ] [-ExcludeAlert ] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaAgentAlert -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all SQL Agent alerts on the localhost, localhost\\namedinstance instances PS C:\\> Remove-DbaAgentAlert -SqlInstance localhost, localhost\\namedinstance Example 2: Removes MyDatabaseAlert SQL Agent alert on the localhost PS C:\\> Remove-DbaAgentAlert -SqlInstance localhost -Alert MyDatabaseAlert Example 3: Using a pipeline this command gets all SQL Agent alerts on SRV1, lets the user select those to remove and... PS C:\\> Get-DbaAgentAlert -SqlInstance SRV1 | Out-GridView -Title 'Select SQL Agent alert(s) to drop' -OutputMode Multiple | Remove-DbaAgentAlert Using 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. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts SQL Agent alert objects from the pipeline, typically from Get-DbaAgentAlert. Use this for selective removal operations where you first query alerts with specific criteria and then remove the filtered results. Enables advanced scenarios like interactive selection using Out-GridView or complex filtering logic. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Alert Specifies the names of specific SQL Agent alerts to remove from the target instances. Use this when you need to remove particular alerts rather than all alerts on the server. Accepts an array of alert names for bulk removal operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeAlert Excludes specific SQL Agent alerts from removal when processing all alerts on an instance. Useful for bulk cleanup operations where you want to preserve certain critical alerts. Only applies when the Alert parameter is not specified, allowing you to remove all alerts except those listed here. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per alert removal attempt. Each object represents the status of removing a single SQL Agent alert from a SQL Server instance. Properties: ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The name of the SQL Server instance (service name) SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName Name: The name of the SQL Agent alert that was removed Status: Status message indicating the outcome of the removal (\"Dropped\" on success, or an error message on failure) IsRemoved: Boolean indicating whether the SQL Agent alert was successfully removed ($true) or failed ($false) &nbsp;"
  },
  {
    "name": "Remove-DbaAgentAlertCategory",
    "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't 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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "alert",
      "alertcategory"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgentAlertCategory",
    "popularityRank": 695,
    "synopsis": "Removes SQL Server Agent alert categories from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgentAlertCategory View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Server Agent alert categories from SQL Server instances. Description Removes custom alert categories from SQL Server Agent, useful for cleaning up unused organizational structures or standardizing alert management across environments. Any existing alerts that reference the removed category will automatically be reassigned to the [Uncategorized] category, so you don't need to manually update alert assignments before removal. The function works with both individual category names and accepts pipeline input from Get-DbaAgentAlertCategory for bulk operations. Returns detailed status information showing which categories were successfully removed and any that failed with error details. Syntax Remove-DbaAgentAlertCategory [-SqlInstance] [-SqlCredential ] [-Category ] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaAgentAlertCategory -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Remove the alert category Category 1 from the instance PS C:\\> Remove-DbaAgentAlertCategory -SqlInstance sql1 -Category 'Category 1' Example 2: Remove multiple alert categories from the instance PS C:\\> Remove-DbaAgentAlertCategory -SqlInstance sql1 -Category Category1, Category2, Category3 Example 3: Remove multiple alert categories from the multiple instances PS C:\\> Remove-DbaAgentAlertCategory -SqlInstance sql1, sql2, sql3 -Category Category1, Category2, Category3 Example 4: Using a pipeline this command gets all SQL Agent alert category(-ies) on SRV1, lets the user select those to... PS C:\\> Get-DbaAgentAlertCategory -SqlInstance SRV1 | Out-GridView -Title 'Select SQL Agent alert category(-ies) to drop' -OutputMode Multiple | Remove-DbaAgentAlertCategory Using 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). Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts alert category objects from Get-DbaAgentAlertCategory for pipeline-based operations. Use this when you need to filter or select categories interactively before removal, such as with Out-GridView. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Category Specifies the names of the alert categories to remove from SQL Server Agent. Accepts multiple category names for bulk removal. Use this to target specific custom categories you want to delete while keeping others intact. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per alert category removal attempt. Each object represents the status of removing a single alert category from a SQL Server instance. Properties: ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The name of the SQL Server instance (service name) SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName Name: The name of the alert category that was removed Status: Status message indicating the outcome of the removal (\"Dropped\" on success, or an error message on failure) IsRemoved: Boolean indicating whether the alert category was successfully removed ($true) or failed ($false) &nbsp;"
  },
  {
    "name": "Remove-DbaAgentJob",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgentJob",
    "popularityRank": 213,
    "synopsis": "Removes SQL Server Agent jobs from one or more instances with options to preserve history and schedules.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgentJob View Source Sander Stad (@sqlstad, sqlstad.nl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Server Agent jobs from one or more instances with options to preserve history and schedules. 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. Syntax Remove-DbaAgentJob [[-SqlInstance] ] [[-SqlCredential] ] [[-Job] ] [-KeepHistory] [-KeepUnusedSchedule] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the job from the instance with the name Job1 PS C:\\> Remove-DbaAgentJob -SqlInstance sql1 -Job Job1 Example 2: Removes the job but keeps the history PS C:\\> GetDbaAgentJob -SqlInstance sql1 -Job Job1 | Remove-DbaAgentJob -KeepHistory Example 3: Removes the job but keeps the unused schedules PS C:\\> Remove-DbaAgentJob -SqlInstance sql1 -Job Job1 -KeepUnusedSchedule Example 4: Removes the job from multiple servers PS C:\\> Remove-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job Job1 Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies the name of the SQL Server Agent job to remove. Accepts one or more job names. Use this when you know the specific job names you want to delete, rather than piping job objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -KeepHistory Preserves job execution history in the msdb.dbo.sysjobhistory tables when removing the job. Use this when you need to retain audit trails or troubleshooting information for compliance or analysis purposes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepUnusedSchedule Preserves job schedules that aren't used by other jobs when removing this job. Use this when you plan to reuse the schedule for new jobs or want to maintain schedule definitions for documentation purposes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts SQL Server Agent job objects from the pipeline, typically from Get-DbaAgentJob. Use this approach when you need to filter jobs with complex criteria before removal or when processing jobs from multiple instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per job removed, with the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The job name that was removed Status: The status of the removal operation (\"Dropped\" on success, or \"Failed. {error message}\" on failure) &nbsp;"
  },
  {
    "name": "Remove-DbaAgentJobCategory",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "jobcategory"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgentJobCategory",
    "popularityRank": 688,
    "synopsis": "Removes SQL Server Agent job categories from one or more instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgentJobCategory View Source Sander Stad (@sqlstad, sqlstad.nl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Server Agent job categories from one or more instances. Description Removes custom SQL Server Agent job categories that are no longer needed for job organization and management. This is useful when cleaning up obsolete categories after reorganizing jobs or migrating workloads between environments. Any jobs currently assigned to a removed category will automatically be reassigned to the default \"[Uncategorized (Local)]\" category. The function provides safety controls and detailed status reporting to ensure successful cleanup operations. Syntax Remove-DbaAgentJobCategory [-SqlInstance] [-SqlCredential ] [-Category ] [-CategoryType ] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaAgentJobCategory -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Remove the job category Category 1 from the instance PS C:\\> Remove-DbaAgentJobCategory -SqlInstance sql1 -Category 'Category 1' Example 2: Remove multiple job categories from the instance PS C:\\> Remove-DbaAgentJobCategory -SqlInstance sql1 -Category Category1, Category2, Category3 Example 3: Remove multiple job categories from the multiple instances PS C:\\> Remove-DbaAgentJobCategory -SqlInstance sql1, sql2, sql3 -Category Category1, Category2, Category3 Example 4: Using a pipeline this command gets all SQL Agent job category(-ies) on SRV1, lets the user select those to... PS C:\\> Get-DbaAgentJobCategory -SqlInstance SRV1 | Out-GridView -Title 'Select SQL Agent job category(-ies) to drop' -OutputMode Multiple | Remove-DbaAgentJobCategory Using 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). Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts SQL Agent job category objects from the pipeline, typically from Get-DbaAgentJobCategory. Use this for interactive category selection workflows or when you need to filter categories before removal using Get-DbaAgentJobCategory's filtering options. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Category Specifies the name of the SQL Agent job category to remove from the instance. Accepts multiple category names for batch operations. Use this when you need to clean up specific custom categories that are no longer needed for job organization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CategoryType Filters categories by their type: \"LocalJob\" for single-server jobs, \"MultiServerJob\" for multi-server administration jobs, or \"None\" for uncategorized jobs. Use this to target specific category types when cleaning up job organization structures. If omitted, all category types will be processed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | LocalJob,MultiServerJob,None | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per category removed, with the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The job category name that was removed Status: The status of the removal operation (\"Dropped\" on success, or an error message on failure) IsRemoved: Boolean indicating whether the category was successfully removed (true) or failed (false) &nbsp;"
  },
  {
    "name": "Remove-DbaAgentJobSchedule",
    "description": "Detaches one or more schedules from a SQL Server Agent job without deleting the schedule itself. This is equivalent to executing sp_detach_schedule in T-SQL.\n\nThis is particularly useful when a schedule is shared between multiple jobs and you need to stop a specific job from running on that schedule without affecting other jobs that use the same schedule. The schedule remains in SQL Server Agent and can be reattached to the job or attached to other jobs at any time.\n\nUse Set-DbaAgentJob with the -Schedule parameter to reattach a schedule to a job after detaching it.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "jobschedule",
      "schedule"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgentJobSchedule",
    "popularityRank": 0,
    "synopsis": "Detaches a schedule from a SQL Server Agent job without removing the schedule.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgentJobSchedule View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Detaches a schedule from a SQL Server Agent job without removing the schedule. Description Detaches one or more schedules from a SQL Server Agent job without deleting the schedule itself. This is equivalent to executing sp_detach_schedule in T-SQL. This is particularly useful when a schedule is shared between multiple jobs and you need to stop a specific job from running on that schedule without affecting other jobs that use the same schedule. The schedule remains in SQL Server Agent and can be reattached to the job or attached to other jobs at any time. Use Set-DbaAgentJob with the -Schedule parameter to reattach a schedule to a job after detaching it. Syntax Remove-DbaAgentJobSchedule [[-SqlInstance] ] [[-SqlCredential] ] [[-Job] ] [-Schedule] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Detaches the schedule named &#39;SharedSchedule&#39; from job &#39;Job1&#39; on sql1 PS C:\\> Remove-DbaAgentJobSchedule -SqlInstance sql1 -Job Job1 -Schedule SharedSchedule Detaches the schedule named 'SharedSchedule' from job 'Job1' on sql1. The schedule itself is not deleted and remains available for other jobs. Example 2: Detaches multiple schedules from a single job on sql1 PS C:\\> Remove-DbaAgentJobSchedule -SqlInstance sql1 -Job Job1 -Schedule Schedule1, Schedule2 Example 3: Detaches the schedule from job &#39;Job1&#39; on multiple SQL Server instances PS C:\\> Remove-DbaAgentJobSchedule -SqlInstance sql1, sql2 -Job Job1 -Schedule SharedSchedule Example 4: Detaches the schedule &#39;SharedSchedule&#39; from job &#39;Job1&#39; using pipeline input PS C:\\> Get-DbaAgentJob -SqlInstance sql1 -Job Job1 | Remove-DbaAgentJobSchedule -Schedule SharedSchedule Example 5: Detaches &#39;SharedSchedule&#39; from all jobs whose names start with &#39;Maintenance&#39; on sql1 PS C:\\> Get-DbaAgentJob -SqlInstance sql1 | Where-Object Name -like 'Maintenance*' | Remove-DbaAgentJobSchedule -Schedule SharedSchedule Required Parameters -Schedule The name of the schedule(s) to detach from the job. The schedule itself is not deleted; only the association between the job and schedule is removed. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job The name of the SQL Agent job(s) from which to detach the schedule. Required when using -SqlInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts job objects from the pipeline, typically from Get-DbaAgentJob output. Use this when you want to filter or retrieve jobs first, then pipe the results for schedule detachment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per detach operation, containing the result and details. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Job: The name of the job from which the schedule was detached Schedule: The name of the schedule that was detached ScheduleId: The numeric ID of the schedule ScheduleUid: The unique GUID identifier of the schedule Status: Result of the operation (\"Detached\" for success, or error message for failures) IsDetached: Boolean indicating if the schedule was successfully detached &nbsp;"
  },
  {
    "name": "Remove-DbaAgentJobStep",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "jobstep"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgentJobStep",
    "popularityRank": 568,
    "synopsis": "Removes specified job steps from SQL Server Agent jobs.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgentJobStep View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes specified job steps from SQL Server Agent jobs. 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. Syntax Remove-DbaAgentJobStep [-SqlInstance] [[-SqlCredential] ] [-Job] [-StepName] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Remove &#39;Step1&#39; from job &#39;Job1&#39; on sql1 PS C:\\> Remove-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 Example 2: Remove the job step from multiple jobs PS C:\\> Remove-DbaAgentJobStep -SqlInstance sql1 -Job Job1, Job2, Job3 -StepName Step1 Example 3: Remove the job step from the job on multiple servers PS C:\\> Remove-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1 Example 4: Remove the job step from the job on multiple servers using pipeline PS C:\\> sql1, sql2, sql3 | Remove-DbaAgentJobStep -Job Job1 -StepName Step1 Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Job Specifies the SQL Agent job(s) from which to remove the step. Accepts multiple job names for bulk operations. Use this when you need to remove the same step from multiple jobs, such as cleaning up outdated notification steps across maintenance jobs. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -StepName Specifies the exact name of the job step to remove from the specified jobs. Step names are case-sensitive and must match exactly. Use this when you need to remove specific steps like obsolete backup verification steps, deprecated notification steps, or failed job components. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This function does not return any objects. It performs the removal operation and returns no output to the pipeline. &nbsp;"
  },
  {
    "name": "Remove-DbaAgentOperator",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "operator"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgentOperator",
    "popularityRank": 646,
    "synopsis": "Removes SQL Server Agent operators from one or more instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgentOperator View Source Tracy Boggiano (@TracyBoggiano), databasesuperhero.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Server Agent operators from one or more instances. Description Removes SQL Server Agent operators from specified instances, cleaning up notification contacts that are no longer needed. Operators 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. The 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. Syntax Remove-DbaAgentOperator [-SqlInstance ] [-SqlCredential ] [-Operator ] [-ExcludeOperator ] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaAgentOperator [-SqlInstance ] [-SqlCredential ] [-Operator ] [-ExcludeOperator ] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: This removes an operator named DBA from the instance PS C:\\> Remove-DbaAgentOperator -SqlInstance sql01 -Operator DBA Example 2: Using a pipeline this command gets all SQL Agent operator(s) on SRV1, lets the user select those to remove... PS C:\\> Get-DbaAgentOperator -SqlInstance SRV1 | Out-GridView -Title 'Select SQL Agent operator(s) to drop' -OutputMode Multiple | Remove-DbaAgentOperator Using 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). Required Parameters -InputObject Accepts SQL Server Agent operator objects from Get-DbaAgentOperator for pipeline operations. This parameter enables filtering operators before removal and supports interactive selection workflows using Out-GridView. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Operator Specifies the SQL Server Agent operator names to remove from the instance. Accepts multiple operator names for bulk removal. Use this when you need to remove specific operators by name, such as when employees leave or contact information becomes outdated. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeOperator Specifies operator names to skip during removal operations. Useful when removing multiple operators but want to preserve certain ones. Use this to protect critical operators from accidental deletion when performing bulk removals or scripted cleanup operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per operator removal attempt with the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Name: The name of the operator that was removed Status: Status message indicating \"Dropped\" on success or error message on failure IsRemoved: Boolean indicating whether the operator was successfully removed (true) or removal failed (false) &nbsp;"
  },
  {
    "name": "Remove-DbaAgentProxy",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "proxy"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgentProxy",
    "popularityRank": 0,
    "synopsis": "Removes SQL Agent agent proxy(s).",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgentProxy View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Agent agent proxy(s). Description Removes the SQL Agent proxy(s) that have passed through the pipeline. If not used with a pipeline, Get-DbaAgentProxy will be executed with the parameters provided and the returned SQL Agent proxy(s) will be removed. Syntax Remove-DbaAgentProxy [-SqlInstance ] [-SqlCredential ] [-Proxy ] [-ExcludeProxy ] [-WhatIf] [-Confirm] [ ] Remove-DbaAgentProxy [-SqlInstance ] [-SqlCredential ] [-Proxy ] [-ExcludeProxy ] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all SQL Agent proxies on the localhost, localhost\\namedinstance instances PS C:\\> Remove-DbaAgentProxy -SqlInstance localhost, localhost\\namedinstance Example 2: Removes MyDatabaseProxy SQL Agent proxy on the localhost PS C:\\> Remove-DbaAgentProxy -SqlInstance localhost -Proxy MyDatabaseProxy Example 3: Using a pipeline this command gets all SQL Agent proxies on SRV1, lets the user select those to remove and... PS C:\\> Get-DbaAgentProxy -SqlInstance SRV1 | Out-GridView -Title 'Select SQL Agent proxy(s) to drop' -OutputMode Multiple | Remove-DbaAgentProxy Using 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. Required Parameters -InputObject Accepts SQL Agent proxy objects from the pipeline, typically from Get-DbaAgentProxy. Use this parameter set when you need to filter or select specific proxies before removal. Enables advanced scenarios like interactive selection through Out-GridView or complex filtering logic. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Proxy Specifies one or more SQL Agent proxy account names to remove. Accepts wildcards for pattern matching. Use this when you need to remove specific proxy accounts instead of all proxies on the instance. Common examples include service account proxies or job-specific proxy accounts that are no longer needed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeProxy Specifies one or more SQL Agent proxy account names to exclude from removal. Accepts wildcards for pattern matching. Use this when removing multiple proxies but want to preserve certain critical proxy accounts. Helpful for bulk cleanup operations while protecting production service account proxies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per proxy processed, containing removal status and details. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the SQL Agent proxy that was removed Status: Result of the removal operation (\"Dropped\" for success, or error message for failures) IsRemoved: Boolean indicating if the proxy was successfully removed ($true for success, $false for failures) &nbsp;"
  },
  {
    "name": "Remove-DbaAgentSchedule",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "schedule"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgentSchedule",
    "popularityRank": 506,
    "synopsis": "Removes SQL Server Agent schedules from one or more instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgentSchedule View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Server Agent schedules from one or more instances. 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. Syntax Remove-DbaAgentSchedule [[-SqlInstance] ] [[-SqlCredential] ] [[-Schedule] ] [[-ScheduleUid] ] [[-Id] ] [[-InputObject] ] [-EnableException] [-Force] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Remove the schedule weekly PS C:\\> Remove-DbaAgentSchedule -SqlInstance sql1 -Schedule weekly Example 2: Remove the schedule weekly even if the schedule is being used by jobs PS C:\\> Remove-DbaAgentSchedule -SqlInstance sql1 -Schedule weekly -Force Example 3: Remove multiple schedules PS C:\\> Remove-DbaAgentSchedule -SqlInstance sql1 -Schedule daily, weekly Example 4: Remove the schedule on multiple servers for multiple schedules PS C:\\> Remove-DbaAgentSchedule -SqlInstance sql1, sql2, sql3 -Schedule daily, weekly Example 5: Remove the schedules using a pipeline PS C:\\> Get-DbaAgentSchedule -SqlInstance sql1 -Schedule sched1, sched2, sched3 | Remove-DbaAgentSchedule Example 6: Remove the schedules using the schedule uid PS C:\\> Remove-DbaAgentSchedule -SqlInstance sql1, sql2, sql3 -ScheduleUid 'bf57fa7e-7720-4936-85a0-87d279db7eb7' Optional Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schedule Specifies the name(s) of SQL Server Agent schedules to remove from the msdb database. Use this when you know the schedule name but need to be aware that multiple schedules can share the same name. When multiple schedules have identical names, you'll need to use -Id or -ScheduleUid to target a specific schedule. | Property | Value | | --- | --- | | Alias | Schedules,Name | | Required | False | | Pipeline | false | | Default Value | | -ScheduleUid Specifies the unique GUID identifier of specific SQL Server Agent schedules to remove. Use this when you need to target an exact schedule, especially when multiple schedules share the same name. The ScheduleUid ensures you're removing the precise schedule without ambiguity. | Property | Value | | --- | --- | | Alias | Uid | | Required | False | | Pipeline | false | | Default Value | | -Id Specifies the numeric schedule ID(s) to remove from SQL Server Agent. Use this when you have the specific schedule ID number, typically obtained from Get-DbaAgentSchedule output. The ID provides an alternative to name-based removal when dealing with duplicate schedule names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts schedule objects from the pipeline, typically from Get-DbaAgentSchedule output. Use this when you want to filter schedules first with Get-DbaAgentSchedule, then pipe the results for removal. This approach allows for complex filtering and review before deletion. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Bypasses the protection that prevents removal of schedules currently assigned to jobs. Without this parameter, schedules in use by jobs are protected and will not be removed. Use this when you need to clean up schedules and automatically remove their job associations first. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per schedule processed, containing removal status and details. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Schedule: The name of the schedule that was removed ScheduleId: The numeric ID of the schedule ScheduleUid: The unique GUID identifier of the schedule Status: Result of the removal operation (\"Dropped\" for success, or error message for failures) IsRemoved: Boolean indicating if the schedule was successfully removed ($true for success, $false for failures) &nbsp;"
  },
  {
    "name": "Remove-DbaAgListener",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgListener",
    "popularityRank": 536,
    "synopsis": "Removes availability group listeners from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgListener View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes availability group listeners from SQL Server instances. 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. Syntax Remove-DbaAgListener [[-SqlInstance] ] [[-SqlCredential] ] [[-Listener] ] [[-AvailabilityGroup] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the ag1 and ag2 availability groups on sqlserver2012 PS C:\\> Remove-DbaAgListener -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false Removes the ag1 and ag2 availability groups on sqlserver2012. Does not prompt for confirmation. Example 2: Removes the listeners returned from the Get-DbaAvailabilityGroup function PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAgListener Removes the listeners returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation. Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Listener Specifies the name of specific availability group listeners to remove. Required when using SqlInstance parameter. Use this when you need to remove particular listeners rather than all listeners from availability groups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Filters listener removal to only those within the specified availability groups. Use this when you want to remove listeners from particular AGs while preserving listeners from other availability groups on the same instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group listener objects from the pipeline, typically from Get-DbaAgListener. Use this when you need to remove listeners that have been filtered or selected through other dbatools commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per listener that is successfully removed from the availability group. Properties: ComputerName: The computer name of the SQL Server instance hosting the listener InstanceName: The SQL Server instance name (the named instance or MSSQLSERVER for default instance) SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName AvailabilityGroup: Name of the availability group from which the listener was removed Listener: The name of the availability group listener that was removed Status: The status of the operation; always \"Removed\" for successful removals &nbsp;"
  },
  {
    "name": "Remove-DbaAgReplica",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAgReplica",
    "popularityRank": 445,
    "synopsis": "Removes secondary replicas from SQL Server Availability Groups",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAgReplica View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes secondary replicas from SQL Server Availability Groups 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. Syntax Remove-DbaAgReplica [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Replica] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the sp1 replica from the SharePoint ag on sql2017a PS C:\\> Remove-DbaAgReplica -SqlInstance sql2017a -AvailabilityGroup SharePoint -Replica sp1 Removes the sp1 replica from the SharePoint ag on sql2017a. Prompts for confirmation. Example 2: Returns full object properties on all availability group replicas found on sql2017a PS C:\\> Remove-DbaAgReplica -SqlInstance sql2017a | Select-Object * Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies the availability group(s) containing the replicas to remove. Accepts wildcards for pattern matching. Use this to limit the removal operation to specific availability groups when you have multiple AGs on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Replica Specifies the name(s) of the availability group replicas to remove from the AG configuration. Accepts wildcards for pattern matching. This parameter is required when using SqlInstance and typically matches the server name hosting the replica you want to remove. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group replica objects from the pipeline, typically from Get-DbaAgReplica output. Use this for batch operations when you need to remove multiple replicas or want to filter replicas before removal. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per replica that is successfully removed from the availability group. Properties: ComputerName: The computer name of the SQL Server instance hosting the replica InstanceName: The SQL Server instance name (the named instance or MSSQLSERVER for default instance) SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName AvailabilityGroup: Name of the availability group from which the replica was removed Replica: The name of the replica that was removed Status: The status of the operation; always \"Removed\" for successful removals &nbsp;"
  },
  {
    "name": "Remove-DbaAvailabilityGroup",
    "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",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaAvailabilityGroup",
    "popularityRank": 377,
    "synopsis": "Removes availability groups from SQL Server instances using DROP AVAILABILITY GROUP.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaAvailabilityGroup View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes availability groups from SQL Server instances using DROP AVAILABILITY GROUP. 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. The 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. When the availability group is dropped from the primary replica, changes are allowed in the former primary databases (without high availability protection). Deleting an availability group from a secondary replica leaves the primary replica in the RESTORING state, and changes are not allowed on the databases. Avoid dropping an availability group when the Windows Server Failover Clustering (WSFC) cluster has no quorum. If you must drop an availability group while the cluster lacks quorum, the metadata availability group that is stored in the cluster is not removed. After the cluster regains quorum, you will need to drop the availability group again to remove it from the WSFC cluster. For more information: https://docs.microsoft.com/en-us/sql/t-sql/statements/drop-availability-group-transact-sql Syntax Remove-DbaAvailabilityGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [-AllAvailabilityGroups] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all availability groups on the sqlserver2014 instance PS C:\\> Remove-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AllAvailabilityGroups Removes all availability groups on the sqlserver2014 instance. Prompts for confirmation. Example 2: Removes the ag1 and ag2 availability groups on sqlserver2012 PS C:\\> Remove-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup ag1, ag2 -Confirm:$false Removes the ag1 and ag2 availability groups on sqlserver2012. Does not prompt for confirmation. Example 3: Removes the availability groups returned from the Get-DbaAvailabilityGroup function PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sqlserver2012 -AvailabilityGroup availabilitygroup1 | Remove-DbaAvailabilityGroup Removes the availability groups returned from the Get-DbaAvailabilityGroup function. Prompts for confirmation. Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies the name(s) of specific availability groups to remove. Accepts multiple values and wildcards for pattern matching. Use this when you need to remove only certain availability groups rather than all groups on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllAvailabilityGroups Removes all availability groups found on the specified SQL Server instance. Use this switch when decommissioning a server or performing bulk cleanup operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations. Use this when you need to filter or pre-process availability groups before removal. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per availability group that is successfully removed. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance (e.g., \"MSSQLSERVER\" for default instance) SqlInstance: The full SQL Server instance name in format ComputerName\\InstanceName AvailabilityGroup: The name of the availability group that was removed Status: Always \"Removed\" when the availability group is successfully dropped &nbsp;"
  },
  {
    "name": "Remove-DbaBackup",
    "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've 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.",
    "category": "Backup & Restore",
    "tags": [
      "backup",
      "disasterrecovery"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaBackup",
    "popularityRank": 231,
    "synopsis": "Removes SQL Server backup files from disk based on retention policies and file extension criteria.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaBackup View Source Chris Sommer (@cjsommer), www.cjsommer.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Server backup files from disk based on retention policies and file extension criteria. 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. You 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've been backed up to another location, preventing accidental loss of unarchived backups. Replaces 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. Syntax Remove-DbaBackup [-Path] [-BackupFileExtension] [-RetentionPeriod] [-CheckArchiveBit] [-RemoveEmptyBackupFolder] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: &#39;.trn&#39; files in &#39;C:\\MSSQL\\SQL Backup\\&#39; and all subdirectories that are more than 48 hours old will be... PS C:\\> Remove-DbaBackup -Path 'C:\\MSSQL\\SQL Backup\\' -BackupFileExtension trn -RetentionPeriod 48h '.trn' files in 'C:\\MSSQL\\SQL Backup\\' and all subdirectories that are more than 48 hours old will be removed. Example 2: Same as example #1, but doesn&#39;t actually remove any files PS C:\\> Remove-DbaBackup -Path 'C:\\MSSQL\\SQL Backup\\' -BackupFileExtension trn -RetentionPeriod 48h -WhatIf Same as example #1, but doesn't actually remove any files. The function will instead show you what would be done. This is useful when first experimenting with using the function. Example 3: &#39;.bak&#39; files in &#39;C:\\MSSQL\\Backup\\&#39; and all subdirectories that are more than 7 days old will be removed, but... PS C:\\> Remove-DbaBackup -Path 'C:\\MSSQL\\Backup\\' -BackupFileExtension bak -RetentionPeriod 7d -CheckArchiveBit '.bak' files in 'C:\\MSSQL\\Backup\\' 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 Archive bit. Example 4: &#39;.bak&#39; files in &#39;C:\\MSSQL\\Backup\\&#39; and all subdirectories that are more than 1 week old will be removed PS C:\\> Remove-DbaBackup -Path 'C:\\MSSQL\\Backup\\' -BackupFileExtension bak -RetentionPeriod 1w -RemoveEmptyBackupFolder '.bak' files in 'C:\\MSSQL\\Backup\\' and all subdirectories that are more than 1 week old will be removed. Any folders left empty will be removed as well. Required Parameters -Path Specifies the root directory where backup files are stored for cleanup. The function recursively searches all subdirectories from this location. Use this to target your primary backup storage location, whether it's a local drive, network share, or mounted backup volume. | Property | Value | | --- | --- | | Alias | BackupFolder | | Required | True | | Pipeline | false | | Default Value | | -BackupFileExtension Specifies the file extension for the backup type to clean up. Common values are 'bak' for full backups, 'trn' for transaction log backups, or 'dif' for differential backups. Use this to target specific backup types during cleanup, allowing you to apply different retention policies for each backup type. Do not include the period. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -RetentionPeriod Defines how long to keep backup files before deletion, formatted as number plus unit (48h, 7d, 4w, 1m). Use shorter periods for transaction log backups (24h-48h) and longer periods for full backups (1w-4w) based on your recovery requirements and storage capacity. Valid units: h=hours, d=days, w=weeks, m=months Examples: '48h' keeps files for 48 hours, '7d' for 7 days, '4w' for 4 weeks, '1m' for 1 month | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -CheckArchiveBit Prevents deletion of files that haven't been archived to tape or another backup location by checking the Windows Archive bit. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -RemoveEmptyBackupFolder Removes directories that become empty after backup file cleanup to prevent folder structure clutter. Use this to maintain a clean backup directory structure, especially when backup files are organized by database or date folders. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.i | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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 deleted without actually removing files. &nbsp;"
  },
  {
    "name": "Remove-DbaClientAlias",
    "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.",
    "category": "Utilities",
    "tags": [
      "sqlclient",
      "alias"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaClientAlias",
    "popularityRank": 656,
    "synopsis": "Removes SQL Server client aliases from Windows registry on local or remote computers",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaClientAlias View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Server client aliases from Windows registry on local or remote computers Description Removes SQL Server client aliases from the Windows registry by deleting entries from both 32-bit and 64-bit registry locations. Client aliases redirect SQL Server connection requests to different servers or instances, but outdated or incorrect aliases can cause connection failures. This 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. Commonly used when decommissioning servers, updating connection strings, or troubleshooting connectivity issues caused by stale alias configurations. Syntax Remove-DbaClientAlias [[-ComputerName] ] [[-Credential] ] [-Alias] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the sqlps SQL Client alias on workstationX PS C:\\> Remove-DbaClientAlias -ComputerName workstationX -Alias sqlps Example 2: Removes all SQL Server client aliases on the local computer PS C:\\> Get-DbaClientAlias | Remove-DbaClientAlias Required Parameters -Alias Specifies the SQL Server client alias name(s) to remove from both 32-bit and 64-bit registry locations. Use this to clean up outdated aliases that redirect connections to decommissioned servers or incorrect instances. Accepts multiple alias names for bulk cleanup operations. | Property | Value | | --- | --- | | Alias | AliasName | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -ComputerName Specifies the target computer(s) where SQL Server client aliases will be removed from the Windows registry. Use this when you need to clean up aliases on remote workstations or application servers. Defaults to the local computer if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to remote computers using alternative credentials | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per alias that was successfully removed from the registry. Properties: ComputerName: The name of the computer where the alias was removed Architecture: Registry architecture where the alias was removed (\"32-bit\" or \"64-bit\") Alias: The name of the SQL Server client alias that was removed Status: The result status, typically \"Removed\" when successful &nbsp;"
  },
  {
    "name": "Remove-DbaCmConnection",
    "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.",
    "category": "Utilities",
    "tags": [
      "computermanagement",
      "cim"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaCmConnection",
    "popularityRank": 650,
    "synopsis": "Removes cached Windows Management and CIM connections from the dbatools connection cache.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaCmConnection View Source Friedrich Weinmann (@FredWeinmann) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes cached Windows Management and CIM connections from the dbatools 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. When you run dbatools commands against remote servers, these connections are automatically created and cached to improve performance and reduce authentication overhead. This 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. Syntax Remove-DbaCmConnection [-ComputerName] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the cached connection to the server sql2014 from the cache PS C:\\> Remove-DbaCmConnection -ComputerName sql2014 Example 2: Clears the entire connection cache PS C:\\> Get-DbaCmConnection | Remove-DbaCmConnection Required Parameters -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. Use this when you need to clear stale connections after credential changes, network issues, or when troubleshooting remote computer management problems. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This command does not return any output to the pipeline. It only modifies the internal dbatools connection cache by removing the specified cached connections. &nbsp;"
  },
  {
    "name": "Remove-DbaComputerCertificate",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaComputerCertificate",
    "popularityRank": 537,
    "synopsis": "Removes certificates from Windows certificate stores on local or remote computers",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaComputerCertificate View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes certificates from Windows certificate stores on local or remote computers 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. Syntax Remove-DbaComputerCertificate [[-ComputerName] ] [[-Credential] ] [-Thumbprint] [[-Store] ] [[-Folder] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes certificate with thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 in the LocalMachine store on... PS C:\\> Remove-DbaComputerCertificate -ComputerName Server1 -Thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 Removes certificate with thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 in the LocalMachine store on Server1 Example 2: Removes certificate using the pipeline PS C:\\> Get-DbaComputerCertificate | Where-Object Thumbprint -eq E0A071E387396723C45E92D42B2D497C6A182340 | Remove-DbaComputerCertificate Example 3: Removes certificate with thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 in the User\\My (Personal) store... PS C:\\> Remove-DbaComputerCertificate -ComputerName Server1 -Thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 -Store User -Folder My Removes certificate with thumbprint C2BBE81A94FEE7A26FFF86C2DFDAF6BFD28C6C94 in the User\\My (Personal) store on Server1 Required Parameters -Thumbprint Specifies the unique thumbprint(s) of the certificate(s) to remove. This is the SHA-1 hash that uniquely identifies each certificate. Use Get-DbaComputerCertificate to find thumbprints of certificates you want to remove, commonly needed when cleaning up expired SSL certificates or removing compromised certificates. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -ComputerName Specifies the target computer(s) where certificates will be removed. Defaults to localhost. Use this when managing SSL certificates across multiple SQL Server instances or cleaning up certificates on remote servers during migrations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to $ComputerName using alternative credentials | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Store Specifies the certificate store location where certificates will be removed. Defaults to LocalMachine. Use LocalMachine for system-wide certificates (typical for SQL Server SSL certificates) or CurrentUser for user-specific certificates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | LocalMachine | -Folder Specifies the certificate store folder (subfolder) where certificates will be removed. Defaults to 'My' (Personal certificates). Common folders include 'My' for SSL certificates used by SQL Server, 'Root' for trusted root certificates, or 'TrustedPeople' for trusted person certificates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | My | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per certificate removal attempt. Each object contains the following properties: ComputerName: The computer name where the certificate removal was attempted Store: The certificate store location (LocalMachine or CurrentUser) Folder: The certificate store folder/subfolder where the certificate was located (My, Root, TrustedPeople, etc.) Thumbprint: The SHA-1 hash thumbprint of the certificate that was targeted for removal 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 &nbsp;"
  },
  {
    "name": "Remove-DbaCredential",
    "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.",
    "category": "Security",
    "tags": [
      "security",
      "credential"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaCredential",
    "popularityRank": 614,
    "synopsis": "Removes SQL credential(s).",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaCredential View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL credential(s). Description Removes the SQL credential(s) that have passed through the pipeline. If not used with a pipeline, Get-DbaCredential will be executed with the parameters provided and the returned SQL credential(s) will be removed. Syntax Remove-DbaCredential [-SqlInstance ] [-SqlCredential ] [-Credential ] [-ExcludeCredential ] [-Identity ] [-ExcludeIdentity ] [-WhatIf] [-Confirm] [ ] Remove-DbaCredential [-SqlInstance ] [-SqlCredential ] [-Credential ] [-ExcludeCredential ] [-Identity ] [-ExcludeIdentity ] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all SQL credentials on the localhost, localhost\\namedinstance instances PS C:\\> Remove-DbaCredential -SqlInstance localhost, localhost\\namedinstance Example 2: Removes MyDatabaseCredential SQL credential on the localhost PS C:\\> Remove-DbaCredential -SqlInstance localhost -Credential MyDatabaseCredential Example 3: Using a pipeline this command gets all SQL credentials on SRV1, lets the user select those to remove and then... PS C:\\> Get-DbaCredential -SqlInstance SRV1 | Out-GridView -Title 'Select SQL credential(s) to drop' -OutputMode Multiple | Remove-DbaCredential Using a pipeline this command gets all SQL credentials on SRV1, lets the user select those to remove and then removes the selected SQL credentials. Required Parameters -InputObject Accepts credential objects from Get-DbaCredential for pipeline operations. Use this to chain credential discovery and removal operations, enabling selective removal through Out-GridView or other filters. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Specifies one or more SQL Server credential names to remove from the instance. Accepts wildcards for pattern matching. Use this to target specific credentials instead of removing all credentials on the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeCredential Specifies one or more SQL Server credential names to exclude from removal. Accepts wildcards for pattern matching. Use this when you want to remove most credentials but preserve certain ones like service account or backup credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Identity Filters credentials by their associated identity (the Windows account or certificate the credential represents). Use this to remove credentials based on the underlying identity rather than the credential name. Enclose identities with spaces in quotes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeIdentity Specifies identities to exclude from credential removal operations. Use this to preserve credentials associated with specific Windows accounts or certificates when removing others. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per credential removed. Each object contains the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the SQL credential that was targeted for removal Status: The status of the removal operation. Shows \"Dropped\" on success, or the error message on failure IsRemoved: Boolean indicating whether the credential was successfully removed ($true) or the removal failed ($false) &nbsp;"
  },
  {
    "name": "Remove-DbaCustomError",
    "description": "Removes custom error messages that applications have added to SQL Server's 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.",
    "category": "Utilities",
    "tags": [
      "general",
      "error"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaCustomError",
    "popularityRank": 697,
    "synopsis": "Removes user-defined error messages from the sys.messages system catalog",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaCustomError View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes user-defined error messages from the sys.messages system catalog Description Removes custom error messages that applications have added to SQL Server's 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. Syntax Remove-DbaCustomError [-SqlInstance] [[-SqlCredential] ] [[-MessageID] ] [[-Language] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the custom message on the sqldev01 and sqldev02 instances with ID 70001 and language French PS C:\\> Remove-DbaCustomError -SqlInstance sqldev01, sqldev02 -MessageID 70001 -Language \"French\" Example 2: Removes all custom messages on the sqldev01 and sqldev02 instances with ID 70001 PS C:\\> Remove-DbaCustomError -SqlInstance sqldev01, sqldev02 -MessageID 70001 -Language \"All\" Example 3: Creates a new custom message on the sqldev01 instance with ID 70000, severity 16, and text &quot;test_70000&quot; To... PS C:\\> $server = Connect-DbaInstance sqldev01 PS C:\\> $newMessage = New-DbaCustomError -SqlInstance $server -MessageID 70000 -Severity 16 -MessageText \"test_70000\" PS C:\\> $original = $server.UserDefinedMessages | Where-Object ID -eq 70000 PS C:\\> $messageID = $original.ID PS C:\\> $severity = 20 PS C:\\> $text = $original.Text PS C:\\> $language = $original.Language PS C:\\> $removed = Remove-DbaCustomError -SqlInstance $server -MessageID 70000 PS C:\\> $alteredMessage = New-DbaCustomError -SqlInstance $server -MessageID $messageID -Severity $severity -MessageText $text -Language $language -WithLog Creates a new custom message on the sqldev01 instance with ID 70000, severity 16, and text \"test_70000\" To modify the custom message at a later time the following can be done to change the severity from 16 to 20: The resulting updated message object is available in $alteredMessage. Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MessageID Specifies the custom error message ID to remove from the sys.messages catalog. Must be between 50001 and 2147483647, which is the valid range for user-defined error messages. Use this to target specific custom errors that applications have registered with SQL Server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Language Specifies which language version of the custom error message to remove. Accepts language names or aliases from sys.syslanguages (like 'English', 'French', 'Deutsch'). Use 'All' to remove all language versions of the message ID at once. Defaults to 'English'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | English | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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. &nbsp;"
  },
  {
    "name": "Remove-DbaDatabase",
    "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.",
    "category": "Database Operations",
    "tags": [
      "delete",
      "database"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDatabase",
    "popularityRank": 63,
    "synopsis": "Removes user databases using multiple fallback methods to handle stuck or locked databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDatabase View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes user databases using multiple fallback methods to handle stuck or locked databases. 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. Syntax Remove-DbaDatabase [-SqlCredential ] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaDatabase -SqlInstance [-SqlCredential ] -Database [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaDatabase [-SqlCredential ] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Prompts then removes the database containeddb on SQL Server sql2016 PS C:\\> Remove-DbaDatabase -SqlInstance sql2016 -Database containeddb Example 2: Prompts then removes the databases containeddb and mydb on SQL Server sql2016 PS C:\\> Remove-DbaDatabase -SqlInstance sql2016 -Database containeddb, mydb Example 3: Does not prompt and swiftly removes containeddb on SQL Server sql2016 PS C:\\> Remove-DbaDatabase -SqlInstance sql2016 -Database containeddb -Confirm:$false Example 4: Removes all the user databases from server\\instance PS C:\\> Get-DbaDatabase -SqlInstance server\\instance | Remove-DbaDatabase Example 5: Removes all the user databases from server\\instance without any confirmation PS C:\\> Get-DbaDatabase -SqlInstance server\\instance | Remove-DbaDatabase -Confirm:$false Required Parameters -SqlInstance The target SQL Server instance or instances.You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Database Specifies the user database(s) to remove from the SQL Server instance. Accepts multiple database names and supports wildcards for pattern matching. Use 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. | Property | Value | | --- | --- | | Alias | Name | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from the pipeline, typically from Get-DbaDatabase or other dbatools database commands. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database that was processed, regardless of success or failure. Properties: ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database that was processed Status: Either \"Dropped\" when the database was successfully removed, or the error message if removal failed The 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\". &nbsp;"
  },
  {
    "name": "Remove-DbaDatabaseSafely",
    "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's only 3 minutes long. http://sqlps.io/backuprant",
    "category": "Database Operations",
    "tags": [
      "database",
      "delete"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDatabaseSafely",
    "popularityRank": 386,
    "synopsis": "Removes databases after creating verified backups and testing restore procedures.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDatabaseSafely View Source Rob Sewell (@SQLDBAWithBeard), sqldbawithabeard.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes databases after creating verified backups and testing restore procedures. 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. This 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. With huge thanks to Grant Fritchey and his verify your backups video. Take a look, it's only 3 minutes long. http://sqlps.io/backuprant Syntax Remove-DbaDatabaseSafely [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Destination] ] [[-DestinationSqlCredential] ] [-NoDbccCheckDb] [-BackupFolder] [[-CategoryName] ] [[-JobOwner] ] [-AllDatabases] [[-BackupCompression] ] [-ReuseSourceFolderStructure] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Performs a DBCC CHECKDB on database RideTheLightning on server Fade2Black PS C:\\> Remove-DbaDatabaseSafely -SqlInstance 'Fade2Black' -Database RideTheLightning -BackupFolder 'C:\\MSSQL\\Backup\\Rationalised - DO NOT DELETE' Performs 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 job 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. Any DBCC errors will be written to your documents folder Example 2: Performs a DBCC CHECKDB on two databases, &#39;DemoNCIndex&#39; and &#39;RemoveTestDatabase&#39; on server Fade2Black PS C:\\> $Database = 'DemoNCIndex','RemoveTestDatabase' PS C:\\> Remove-DbaDatabaseSafely -SqlInstance 'Fade2Black' -Database $Database -BackupFolder 'C:\\MSSQL\\Backup\\Rationalised - DO NOT DELETE' Performs a DBCC CHECKDB on two databases, 'DemoNCIndex' and 'RemoveTestDatabase' on server Fade2Black. Then, an Agent job to restore each database from those backups is created. The databases are then dropped, the Agent jobs to restore them run, a DBCC CHECKDB run against the restored databases, and then they are dropped again. Any DBCC errors will be written to your documents folder Example 3: Performs a DBCC CHECKDB on database RideTheLightning on server Fade2Black PS C:\\> Remove-DbaDatabaseSafely -SqlInstance 'Fade2Black' -Destination JusticeForAll -Database RideTheLightning -BackupFolder '\\\\BACKUPSERVER\\BACKUPSHARE\\MSSQL\\Rationalised - DO NOT DELETE' Performs 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 . Then, 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 run, a DBCC CHECKDB run against the restored database, and then it is dropped from JusticeForAll. Any DBCC errors will be written to your documents folder Example 4: For the databases $Database on the server IronMaiden a DBCC CHECKDB will not be performed before backing up... PS C:\\> Remove-DbaDatabaseSafely -SqlInstance IronMaiden -Database $Database -Destination TheWildHearts -BackupFolder Z:\\Backups -NoDbccCheckDb -JobOwner 'THEBEARD\\Rob' For 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 TheWildHearts with a Job Owner of THEBEARD\\Rob to restore each database from that backup using the instance's 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 the database(s) is(are) dropped. Example 5: The databases $Database on the server IronMaiden will be backed up the to the folder Z:\\Backups PS C:\\> Remove-DbaDatabaseSafely -SqlInstance IronMaiden -Database $Database -Destination TheWildHearts -BackupFolder Z:\\Backups The 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 database from that backup using the instance's 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 the database(s) is(are) dropped. If there is a DBCC Error, the function will continue to perform rest of the actions and will create an Agent job with 'DBCCERROR' in the name and a Backup file with 'DBCCError' in the name. Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies one or more databases to safely remove with validated backups. Accepts multiple database names as an array. Use this to target specific databases for removal, ensuring each gets a verified backup before deletion. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $SqlInstance | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instance when different from SqlCredential. Accepts PowerShell credentials (Get-Credential). Use this when the destination server requires different authentication than the source server, common in cross-domain or different security context scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoDbccCheckDb Skips the initial DBCC CHECKDB integrity check before creating the backup, reducing processing time. Use this only when you're confident about database integrity or when time constraints outweigh the risk of backing up a corrupt database. The function still runs DBCC on the restored test database, but corruption detection happens after backup creation. | Property | Value | | --- | --- | | Alias | NoCheck | | Required | False | | Pipeline | false | | Default Value | False | -CategoryName Sets the SQL Agent job category for the restore jobs that are created. Defaults to 'Rationalisation'. Use a custom category name to organize these restoration jobs separately from other maintenance jobs in SQL Agent. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Rationalisation | -JobOwner Sets the owner account for the SQL Agent restore job that gets created. Defaults to the 'sa' login. Specify a different owner when you need the job to run under specific security context or when 'sa' is disabled in your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllDatabases Removes all user databases from the source server, excluding system databases. Primarily used for server decommissioning scenarios. Use with caution and always specify a different Destination server to avoid removing databases from the same server that will test their backups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BackupCompression Controls backup compression behavior with values: Default, On, or Off. Default uses the server's backup compression configuration setting. Use 'On' to force compression for smaller backup files and reduced network traffic, or 'Off' when compression overhead outweighs benefits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Default | | Accepted Values | Default,On,Off | -ReuseSourceFolderStructure Maintains the original database file paths and folder structure during the test restore operation on the destination server. Use this when you need to preserve specific drive layouts or when the destination server has matching drive structure to the source. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Continues the database removal process even when DBCC integrity checks detect corruption. Creates backups and jobs with 'DBCCERROR' naming to identify them. Use this only in emergency situations when you must remove a corrupt database and accept the risk of having potentially unusable backups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database that completes the removal workflow (backup, restore job creation, drop, verify restore, and cleanup). Properties: SqlInstance: The source SQL Server instance name where the original database was located DatabaseName: The name of the database that was removed JobName: The name of the SQL Agent restore job that was created for backup verification testing TestingInstance: The SQL Server instance where the restore testing job was created and executed BackupFolder: The file path where the final backup of the database was stored before deletion No 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. Each 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. &nbsp;"
  },
  {
    "name": "Remove-DbaDbAsymmetricKey",
    "description": "Removes asymmetric keys from SQL Server databases by executing DROP ASYMMETRIC KEY commands. Asymmetric keys are part of SQL Server's 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.",
    "category": "Utilities",
    "tags": [
      "security",
      "key"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbAsymmetricKey",
    "popularityRank": 693,
    "synopsis": "Removes asymmetric keys from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbAsymmetricKey View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes asymmetric keys from SQL Server databases Description Removes asymmetric keys from SQL Server databases by executing DROP ASYMMETRIC KEY commands. Asymmetric keys are part of SQL Server's 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. Syntax Remove-DbaDbAsymmetricKey [[-SqlInstance] ] [[-SqlCredential] ] [[-Name] ] [[-Database] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: The Asymmetric Key AsCert1 will be removed from the Enctest database on Instance Server1 PS C:\\> Remove-DbaDbAsymmetricKey -SqlInstance Server1 -Database Enctest -Name AsCert1 Example 2: Will remove all the asymmetric keys found in the Enctrst databae on the Server1 instance PS C:\\> Get-DbaDbAsymmetricKey -SqlInstance Server1 -Database Enctest | Remove-DbaDbAsymmetricKey Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies the name of the asymmetric key to remove from the database. Use this when you know the exact key name to target specific encryption objects for deletion. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database containing the asymmetric key to be removed. Defaults to 'master' if not specified. Use this to target specific databases when cleaning up encryption objects during security audits or decommissioning operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | master | -InputObject Accepts AsymmetricKey objects from Get-DbaDbAsymmetricKey for pipeline operations. Use this when you need to remove multiple keys or when filtering keys based on specific criteria before deletion. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per asymmetric key successfully removed. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (e.g., MSSQLSERVER, SQLEXPRESS) SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName or ComputerName for default instance) Database: The name of the database from which the asymmetric key was removed Name: The name of the asymmetric key that was removed Status: String indicating the removal result (typically \"Success\" for successful operations) No output is returned if the operation is skipped (WhatIf) or fails (with EnableException disabled). &nbsp;"
  },
  {
    "name": "Remove-DbaDbBackupRestoreHistory",
    "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's SQL Server Maintenance Solution (https://ola.hallengren.com) rather than manual cleanup operations.",
    "category": "Backup & Restore",
    "tags": [
      "delete",
      "backup",
      "restore",
      "database"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbBackupRestoreHistory",
    "popularityRank": 452,
    "synopsis": "Removes backup and restore history records from MSDB database to prevent excessive growth",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbBackupRestoreHistory View Source IJeb Reitsma Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes backup and restore history records from MSDB database to prevent excessive growth 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. Works 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. The 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. For production environments, consider scheduling regular cleanup using the sp_delete_backuphistory agent job from Ola Hallengren's SQL Server Maintenance Solution (https://ola.hallengren.com) rather than manual cleanup operations. Syntax Remove-DbaDbBackupRestoreHistory [[-SqlInstance] ] [[-SqlCredential] ] [[-KeepDays] ] [[-Database] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Prompts for confirmation then deletes backup and restore history on SQL Server sql2016 older than 30 days... PS C:\\> Remove-DbaDbBackupRestoreHistory -SqlInstance sql2016 Prompts for confirmation then deletes backup and restore history on SQL Server sql2016 older than 30 days (default period) Example 2: Remove backup and restore history on SQL Server sql2016 older than 100 days PS C:\\> Remove-DbaDbBackupRestoreHistory -SqlInstance sql2016 -KeepDays 100 -Confirm:$false Remove backup and restore history on SQL Server sql2016 older than 100 days. Does not prompt for confirmation. Example 3: Prompts for confirmation then deletes all backup and restore history for database db1 on SQL Server sql2016 PS C:\\> Remove-DbaDbBackupRestoreHistory -SqlInstance sql2016 -Database db1 Example 4: Remove complete backup and restore history for all databases on SQL Server sql2016 PS C:\\> Get-DbaDatabase -SqlInstance sql2016 | Remove-DbaDbBackupRestoreHistory -WhatIf Optional Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this for regular maintenance to prevent MSDB growth while preserving recent history for troubleshooting. Cannot be combined with Database parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Database Specifies specific databases to completely remove all backup and restore history records regardless of age. Accepts multiple database names and wildcards. Use this when decommissioning databases or performing targeted cleanup after major maintenance operations. Cannot be combined with KeepDays parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase to remove complete backup and restore history for those specific databases. Use this for pipeline operations when working with filtered database collections or when combining with other dbatools database commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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 (DeleteBackupHistory for server-level cleanup and DropBackupHistory for database-level cleanup). &nbsp;"
  },
  {
    "name": "Remove-DbaDbCertificate",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbCertificate",
    "popularityRank": 572,
    "synopsis": "Removes database certificates from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbCertificate View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes database certificates from SQL Server databases 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. Syntax Remove-DbaDbCertificate [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Certificate] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: The certificate in the master database on server1 will be removed if it exists PS C:\\> Remove-DbaDbCertificate -SqlInstance Server1 Example 2: Suppresses all prompts to remove the certificate in the &#39;db1&#39; database and drops the key PS C:\\> Remove-DbaDbCertificate -SqlInstance Server1 -Database db1 -Confirm:$false Optional Parameters -SqlInstance The SQL Server to create the certificates on. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target databases containing certificates to remove. Accepts multiple database names. When omitted, the function will process certificates from all databases that contain the specified certificates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Certificate Specifies the names of certificates to remove from the target databases. Supports multiple certificate names. Use this to target specific certificates rather than removing all certificates found by Get-DbaDbCertificate. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts certificate objects from Get-DbaDbCertificate via pipeline input. This allows for advanced filtering and bulk operations when combined with other dbatools certificate functions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per certificate successfully removed, with the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database where the certificate was removed Certificate: The name of the certificate that was removed Status: Removal status (Success when the certificate was successfully dropped) Certificates that fail to remove do not produce output; errors are handled via Stop-Function with -Continue behavior. &nbsp;"
  },
  {
    "name": "Remove-DbaDbCheckConstraint",
    "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.",
    "category": "Database Operations",
    "tags": [
      "check",
      "constraint",
      "database"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbCheckConstraint",
    "popularityRank": 667,
    "synopsis": "Removes check constraints from SQL Server database tables",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbCheckConstraint View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes check constraints from SQL Server database tables 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. This 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. Supports piping from Get-DbaDbCheckConstraint to remove only specific constraints that match your criteria, such as constraints containing particular patterns or on specific tables. Syntax Remove-DbaDbCheckConstraint [-SqlInstance ] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-ExcludeSystemTable] [-WhatIf] [-Confirm] [ ] Remove-DbaDbCheckConstraint [-SqlInstance ] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-ExcludeSystemTable] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all check constraints from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> Remove-DbaDbCheckConstraint -SqlInstance localhost, sql2016 -Database db1, db2 Example 2: Removes all check constraints from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> $chkcs = Get-DbaDbCheckConstraint -SqlInstance localhost, sql2016 -Database db1, db2 PS C:\\> $chkcs | Remove-DbaDbCheckConstraint Example 3: Removes all check constraints except those in system tables from db1 and db2 on the local and sql2016 SQL... PS C:\\> Remove-DbaDbCheckConstraint -SqlInstance localhost, sql2016 -Database db1, db2 -ExcludeSystemTable Removes all check constraints except those in system tables from db1 and db2 on the local and sql2016 SQL Server instances. Required Parameters -InputObject Accepts check constraint objects from Get-DbaDbCheckConstraint for targeted removal operations. Use this to remove only specific constraints that match your filtering criteria, such as constraints with certain patterns or on particular tables. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to target for check constraint removal. Accepts wildcards and arrays for multiple databases. Use this when you need to remove constraints from specific databases rather than all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from check constraint removal operations. Accepts wildcards and arrays for multiple databases. Use this to protect critical databases like master, msdb, or production databases when running against multiple instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemTable Excludes check constraints on system tables from the removal operation, focusing only on user-created tables. Use this switch when you want to modify only business logic constraints while preserving SQL Server's built-in constraints. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per check constraint processed, with details about the removal operation result. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database where the check constraint was located Name: The name of the check constraint Status: The result of the removal operation - either \"Dropped\" if successful, or an error message if the operation failed IsRemoved: Boolean indicating whether the check constraint was successfully removed (true) or failed (false) &nbsp;"
  },
  {
    "name": "Remove-DbaDbData",
    "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.",
    "category": "Utilities",
    "tags": [
      "table",
      "data"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbData",
    "popularityRank": 393,
    "synopsis": "Truncates all user tables in specified databases to remove all data while preserving table structure.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbData View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Truncates all user tables in specified databases to remove all data while preserving table structure. 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. Syntax Remove-DbaDbData [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-InputObject] ] [[-Path] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all data from the dbname database on the local default SQL Server instance PS C:\\> Remove-DbaDbData -SqlInstance localhost -Database dbname Example 2: Removes all data from all databases on mssql1 except the DBA Database PS C:\\> Remove-DbaDbData -SqlInstance mssql1 -ExcludeDatabase DBA -Confirm:$False Removes all data from all databases on mssql1 except the DBA Database. Doesn't prompt for confirmation. Example 3: Removes all data from AdventureWorks2017 on the mssql1 SQL Server Instance, uses piped input from... PS C:\\> $svr = Connect-DbaInstance -SqlInstance mssql1 PS C:\\> $svr | Remove-DbaDbData -Database AdventureWorks2017 Removes all data from AdventureWorks2017 on the mssql1 SQL Server Instance, uses piped input from Connect-DbaInstance. Example 4: Removes all data from AdventureWorks2017 on the mssql1 SQL Server Instance, uses piped input from... PS C:\\> Get-DbaDatabase -SqlInstance mssql1 -Database AdventureWorks2017 | Remove-DbaDbData Removes all data from AdventureWorks2017 on the mssql1 SQL Server Instance, uses piped input from Get-DbaDatabase. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to clear of data. Accepts wildcards for pattern matching. When omitted, the function processes all user databases on the instance. System databases are always excluded for safety. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from data removal operations. Use this to protect important databases when clearing multiple databases. Commonly used with production or reference databases that should remain untouched during development environment resets. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts piped database objects from Get-DbaDatabase or server connections from Connect-DbaInstance. Use this for pipeline operations when you need to filter databases with complex criteria before clearing data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Path Sets the temporary directory for storing drop and create scripts during the data removal process. The function creates temporary SQL scripts for foreign keys and views, then automatically removes them when complete. Defaults to the configured dbatools export path. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport') | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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. &nbsp;"
  },
  {
    "name": "Remove-DbaDbDataClassification",
    "description": "Removes all data classification metadata from table columns by dropping the four extended properties:\n- sys_information_type_id\n- sys_information_type_name\n- sys_sensitivity_label_id\n- sys_sensitivity_label_name\n\nAccepts piped input from Get-DbaDbDataClassification, making it easy to remove classifications\nfrom specific columns or bulk-remove classifications across databases.\n\nRequires SQL Server 2005 or later due to use of sp_dropextendedproperty.",
    "category": "Utilities",
    "tags": [
      "dataclassification",
      "classification",
      "compliance",
      "security"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbDataClassification",
    "popularityRank": 0,
    "synopsis": "Removes data classification labels from SQL Server table columns",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbDataClassification View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes data classification labels from SQL Server table columns Description Removes all data classification metadata from table columns by dropping the four extended properties: sys_information_type_id sys_information_type_name sys_sensitivity_label_id sys_sensitivity_label_name Accepts piped input from Get-DbaDbDataClassification, making it easy to remove classifications from specific columns or bulk-remove classifications across databases. Requires SQL Server 2005 or later due to use of sp_dropextendedproperty. Syntax Remove-DbaDbDataClassification [-InputObject] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all data classifications from the AdventureWorks database PS C:\\> Get-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks | Remove-DbaDbDataClassification Example 2: Removes data classifications from all classified columns in the Customer table without prompting PS C:\\> Get-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks -Table Customer | Remove-DbaDbDataClassification -Confirm:$false Example 3: Removes only classifications with the &quot;General&quot; sensitivity label from AdventureWorks PS C:\\> Get-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks | Where-Object SensitivityLabel -eq \"General\" | Remove-DbaDbDataClassification Required Parameters -InputObject Accepts classification objects piped from Get-DbaDbDataClassification. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per successfully processed column with these properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name Database: The database name Schema: The schema of the table Table: The table name Column: The column name Status: The result of the removal operation &nbsp;"
  },
  {
    "name": "Remove-DbaDbEncryptionKey",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbEncryptionKey",
    "popularityRank": 580,
    "synopsis": "Removes database encryption keys from SQL Server databases to disable Transparent Data Encryption",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbEncryptionKey View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes database encryption keys from SQL Server databases to disable Transparent Data Encryption 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. Syntax Remove-DbaDbEncryptionKey [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the encryption key in the master database on sql01 if it exists PS C:\\> Remove-DbaDbEncryptionKey -SqlInstance sql01 -Database test Example 2: Suppresses all prompts then removes the encryption key in the &#39;db1&#39; database on sql01 PS C:\\> Remove-DbaDbEncryptionKey -SqlInstance sql01 -Database db1 -Confirm:$false Optional Parameters -SqlInstance The SQL Server to create the encryption keys on. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database(s) from which to remove the database encryption key (DEK). Required when using SqlInstance parameter to target specific databases for encryption key removal. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database encryption key objects from Get-DbaDbEncryptionKey via pipeline. Use this when you need to remove keys from a filtered set of databases or when chaining commands together. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per successfully removed encryption key with the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database from which the encryption key was removed Status: The status of the operation (\"Success\") No objects are returned if the operation fails or is skipped by WhatIf. &nbsp;"
  },
  {
    "name": "Remove-DbaDbFileGroup",
    "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.",
    "category": "Database Operations",
    "tags": [
      "storage",
      "data",
      "file",
      "filegroup"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbFileGroup",
    "popularityRank": 595,
    "synopsis": "Removes empty filegroups from SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbFileGroup View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes empty filegroups from SQL Server databases. 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. Syntax Remove-DbaDbFileGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-FileGroup] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the HRFG1 filegroup on the TestDb database on the sqldev1 instance PS C:\\> Remove-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 Example 2: Passes in the TestDB database from the sqldev1 instance and removes the HRFG1 filegroup PS C:\\> Get-DbaDatabase -SqlInstance sqldev1 -Database TestDb | Remove-DbaDbFileGroup -FileGroup HRFG1 Example 3: Passes in the HRFG1 filegroup from the TestDB database on the sqldev1 instance and removes the filegroup PS C:\\> Get-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 | Remove-DbaDbFileGroup Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to target for filegroup removal. Required when using SqlInstance parameter. Use this to limit the operation to specific databases instead of all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileGroup Specifies the name(s) of the filegroup(s) to remove from the target databases. Required when specifying databases directly. Only empty filegroups (containing no data files) can be removed. Common scenarios include removing filegroups after data migration or database cleanup projects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database or filegroup objects from Get-DbaDatabase or Get-DbaDbFileGroup for pipeline operations. Use this when you need to remove filegroups from a filtered set of databases or when working with specific filegroup objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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 messages if failures occur. &nbsp;"
  },
  {
    "name": "Remove-DbaDbLogShipping",
    "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.",
    "category": "Utilities",
    "tags": [
      "logshipping"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbLogShipping",
    "popularityRank": 324,
    "synopsis": "Dismantles SQL Server log shipping configurations and removes associated jobs and monitoring",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaDbLogShipping View Source Sander Stad (@sqlstad), sqlstad.nl Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Dismantles SQL Server log shipping configurations and removes associated jobs and monitoring 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. Use 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. By 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. Syntax Remove-DbaDbLogShipping [-PrimarySqlInstance] [[-SecondarySqlInstance] ] [[-PrimarySqlCredential] ] [[-SecondarySqlCredential] ] [-Database] [-RemoveSecondaryDatabase] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Remove the log shipping for database DB1 PS C:\\> Remove-DbaDbLogShipping -PrimarySqlInstance sql1 -SecondarySqlInstance sql2 -Database DB1 Example 2: Remove the log shipping for database DB1 and let the command figure out the secondary instance PS C:\\> Remove-DbaDbLogShipping -PrimarySqlInstance sql1 -Database DB1 Example 3: Remove the log shipping for multiple database PS C:\\> Remove-DbaDbLogShipping -PrimarySqlInstance localhost -SecondarySqlInstance sql2 -Database DB1, DB2 Example 4: Remove the log shipping for database DB2 and remove the database from the secondary instance PS C:\\> Remove-DbaDbLogShipping -PrimarySqlInstance localhost -SecondarySqlInstance localhost -Database DB2 -RemoveSecondaryDatabase Required Parameters -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. You must have sysadmin access to execute the log shipping removal stored procedures. Requires SQL Server 2000 or later. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Database The primary database name(s) to remove from log shipping configuration. Accepts multiple databases via pipeline or array input. Must specify the database name as it exists on the primary instance, not the secondary instance name which may be different. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -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. Required when removing log shipping from multiple secondary instances or when automatic discovery fails. You must have sysadmin access to clean up secondary database configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PrimarySqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecondarySqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when decommissioning the secondary server or when you need to start fresh with a new log shipping setup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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 not return any objects to the pipeline. &nbsp;"
  },
  {
    "name": "Remove-DbaDbMailAccount",
    "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.",
    "category": "Utilities",
    "tags": [
      "databasemail",
      "dbmail",
      "mail"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbMailAccount",
    "popularityRank": 591,
    "synopsis": "Removes Database Mail accounts from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbMailAccount View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes Database Mail accounts from SQL Server instances Description Permanently deletes Database Mail accounts from the specified SQL Server instances, removing them from the MSDB database configuration. This command is useful when decommissioning obsolete email accounts, cleaning up after application retirement, or consolidating accounts during email system migrations. When used without pipeline input, it automatically retrieves accounts using Get-DbaDbMailAccount with the provided parameters before removal. Returns detailed status information for each removal operation, including success/failure status and any error messages encountered. Syntax Remove-DbaDbMailAccount [-SqlInstance] [-SqlCredential ] [-Account ] [-ExcludeAccount ] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaDbMailAccount -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all database mail accounts on the localhost, localhost\\namedinstance instances PS C:\\> Remove-DbaDbMailAccount -SqlInstance localhost, localhost\\namedinstance Example 2: Removes MyDatabaseMailAccount database mail account on the localhost PS C:\\> Remove-DbaDbMailAccount -SqlInstance localhost -Account MyDatabaseMailAccount Example 3: Using a pipeline this command gets all database mail accounts on SRV1, lets the user select those to remove... PS C:\\> Get-DbaDbMailAccount -SqlInstance SRV1 | Out-GridView -Title 'Select database mail account(s) to drop' -OutputMode Multiple | Remove-DbaDbMailAccount Using 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. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts Database Mail account objects from the pipeline, typically from Get-DbaDbMailAccount. Use this approach when you need to filter or review accounts before removal using PowerShell pipeline operations. Provides more flexibility than specifying account names directly. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Account Specifies one or more Database Mail account names to remove from the SQL Server instance. Use this when you need to remove specific accounts rather than all accounts on the server. Accepts multiple account names as a string array for bulk removal operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeAccount Specifies Database Mail account names to exclude from removal when processing all accounts on the instance. Use this when you want to remove most accounts but keep certain ones active for ongoing operations. Only applies when the Account parameter is not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per Database Mail account removed. Each object contains the following properties: ComputerName: The computer name of the SQL Server instance where the account was removed InstanceName: The SQL Server instance name SqlInstance: The fully qualified SQL Server instance name (ComputerName\\InstanceName) Name: The Database Mail account name that was removed Status: The result status (\"Dropped\" for successful removal, or error message if removal failed) IsRemoved: Boolean indicating whether the account was successfully removed (true) or failed (false) &nbsp;"
  },
  {
    "name": "Remove-DbaDbMailProfile",
    "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.",
    "category": "Utilities",
    "tags": [
      "databasemail",
      "dbmail",
      "mail"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbMailProfile",
    "popularityRank": 633,
    "synopsis": "Removes Database Mail profiles from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbMailProfile View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes Database Mail profiles from SQL Server instances. Description Deletes specified Database Mail profiles from the msdb database, permanently removing their configuration and preventing them from sending emails. This is commonly used during security hardening to remove unused profiles or when cleaning up misconfigured mail setups. Accepts profiles via pipeline from Get-DbaDbMailProfile or directly through parameters, making it easy to selectively remove profiles based on specific criteria. Returns detailed results showing which profiles were successfully removed and any that failed during deletion. Syntax Remove-DbaDbMailProfile [-SqlInstance] [-SqlCredential ] [-Profile ] [-ExcludeProfile ] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaDbMailProfile -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all database mail profiles on the localhost, localhost\\namedinstance instances PS C:\\> Remove-DbaDbMailProfile -SqlInstance localhost, localhost\\namedinstance Example 2: Removes MyDatabaseMailProfile database mail profile on the localhost PS C:\\> Remove-DbaDbMailProfile -SqlInstance localhost -Profile MyDatabaseMailProfile Example 3: Using a pipeline this command gets all database mail profiles on SRV1, lets the user select those to remove... PS C:\\> Get-DbaDbMailProfile -SqlInstance SRV1 | Out-GridView -Title 'Select database mail profile(s) to drop' -OutputMode Multiple | Remove-DbaDbMailProfile Using 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. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts Database Mail profile objects from Get-DbaDbMailProfile via pipeline. This allows for advanced filtering and selection of profiles before removal, such as selecting profiles based on account configuration or last usage date. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Profile Specifies one or more Database Mail profile names to remove from the instance. Supports wildcards for pattern matching. Use this when you need to remove specific profiles instead of all profiles on the instance. If unspecified, all profiles will be removed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeProfile Specifies one or more Database Mail profile names to exclude from removal. Supports wildcards for pattern matching. Use this when removing all profiles except certain ones you want to keep active for ongoing email operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per Database Mail profile processed, regardless of success or failure. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName Name: The name of the Database Mail profile that was removed or attempted to be removed Status: A string indicating the operation result (\"Dropped\" on success, or error message on failure) IsRemoved: A boolean value indicating whether the profile was successfully removed ($true for success, $false for failure) &nbsp;"
  },
  {
    "name": "Remove-DbaDbMasterKey",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbMasterKey",
    "popularityRank": 649,
    "synopsis": "Removes database master keys from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbMasterKey View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes database master keys from SQL Server databases 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. Syntax Remove-DbaDbMasterKey [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-All] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: The master key in the pubs database on sql2017 and sql2016 will be removed if it exists PS C:\\> Remove-DbaDbMasterKey -SqlInstance sql2017, sql2016 -Database pubs Example 2: Suppresses all prompts to remove the master key in the &#39;db1&#39; database and drops the key PS C:\\> Remove-DbaDbMasterKey -SqlInstance sql2017 -Database db1 -Confirm:$false Example 3: Suppresses all prompts to remove the master key in the &#39;db1&#39; database and drops the key PS C:\\> Get-DbaDbMasterKey -SqlInstance sql2017 -Database db1 | Remove-DbaDbMasterKey -Confirm:$false Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to remove master keys from. Accepts multiple database names. Use this when you need to remove encryption from specific databases during TDE decommissioning or security policy changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip when using the -All parameter to remove master keys from all databases. Use this to protect critical databases that must retain their encryption while cleaning up master keys from other databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -All Removes master keys from all user databases on the SQL Server instance. Use this when decommissioning encryption across an entire instance or during major security architecture changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts master key objects from Get-DbaDbMasterKey through the pipeline. Use this approach when you need to filter or inspect master keys before removing them, providing more control over the removal process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per master key removed from the database. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name in the format ComputerName\\InstanceName Database: The name of the database from which the master key was removed Status: A string indicating the operation result (\"Master key removed\" on success, or error message on failure) &nbsp;"
  },
  {
    "name": "Remove-DbaDbMirror",
    "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'll need to manually restore those databases with RECOVERY to make them accessible for normal operations.",
    "category": "Utilities",
    "tags": [
      "mirroring",
      "mirror",
      "ha"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbMirror",
    "popularityRank": 551,
    "synopsis": "Breaks database mirroring partnerships and stops mirroring sessions",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbMirror View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Breaks database mirroring partnerships and stops mirroring sessions 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. Important: This function only breaks the mirroring partnership - it does not automatically recover databases that are left in a \"Restoring\" state. You'll need to manually restore those databases with RECOVERY to make them accessible for normal operations. Syntax Remove-DbaDbMirror [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Stops the database mirroring session for the TestDB on the localhost instance PS C:\\> Remove-DbaDbMirror -SqlInstance localhost -Database TestDB Example 2: Stops the database mirroring session for the TestDB1 and TestDB2 databases on the localhost instance PS C:\\> Remove-DbaDbMirror -SqlInstance localhost -Database TestDB1, TestDB2 Example 3: Stops the database mirroring session for the TestDB1 and TestDB2 databases on the localhost instance PS C:\\> Get-DbaDatabase -SqlInstance localhost -Database TestDB1, TestDB2 | Remove-DbaDbMirror Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the names of databases whose mirroring partnerships should be terminated. Accepts multiple database names. Required when using SqlInstance parameter. Use this to target specific mirrored databases rather than processing all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from the pipeline, typically from Get-DbaDatabase. Use this when you want to filter databases using Get-DbaDatabase's capabilities before breaking mirroring partnerships. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database where the mirroring partnership was removed. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database where mirroring was removed Status: Status of the operation (always \"Removed\" on success) &nbsp;"
  },
  {
    "name": "Remove-DbaDbMirrorMonitor",
    "description": "Stops and deletes the mirroring monitor job for all the databases on the server instance.\n\nBasically executes sp_dbmmonitordropmonitoring.",
    "category": "Utilities",
    "tags": [
      "mirroring",
      "mirror",
      "ha"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbMirrorMonitor",
    "popularityRank": 690,
    "synopsis": "Stops and deletes the mirroring monitor job for all the databases on the server instance.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbMirrorMonitor View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Stops and deletes the mirroring monitor job for all the databases on the server instance. Description Stops and deletes the mirroring monitor job for all the databases on the server instance. Basically executes sp_dbmmonitordropmonitoring. Syntax Remove-DbaDbMirrorMonitor [-SqlInstance] [[-SqlCredential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Stops and deletes the mirroring monitor job for all the databases on sql2008 and sql2012 PS C:\\> Remove-DbaDbMirrorMonitor -SqlInstance sql2008, sql2012 Required Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance where the mirror monitoring was removed. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) MonitorStatus: Status of the operation (always \"Removed\" on success) &nbsp;"
  },
  {
    "name": "Remove-DbaDbOrphanUser",
    "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't exist on the current server. This commonly happens after login deletions, database migrations, or restores to servers where the original logins don't 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 'dbo' 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.",
    "category": "Security",
    "tags": [
      "user",
      "orphan",
      "login"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbOrphanUser",
    "popularityRank": 126,
    "synopsis": "Removes orphaned database users that no longer have corresponding SQL Server logins",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbOrphanUser View Source Claudio Silva (@ClaudioESSilva) , Simone Bizzotto (@niphlod) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes orphaned database users that no longer have corresponding SQL Server logins Description Removes orphaned database users from one or more databases, handling schema ownership transfers automatically to prevent dependency issues. Orphaned users occur when a database user exists but its corresponding login in the master database has been deleted or doesn't exist on the current server. This commonly happens after login deletions, database migrations, or restores to servers where the original logins don't exist. The function intelligently handles schema ownership: Drops empty schemas that have the same name as the orphaned user Transfers ownership of other schemas to 'dbo' to maintain database integrity Requires -Force parameter when schemas contain objects, ensuring you make conscious decisions about ownership changes When 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. Contained databases are automatically skipped since they manage authentication differently and cannot have orphaned users in the traditional sense. Syntax Remove-DbaDbOrphanUser [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-User] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Finds and drops all orphan users without matching Logins in all databases present on server &#39;sql2005&#39; PS C:\\> Remove-DbaDbOrphanUser -SqlInstance sql2005 Example 2: Finds and drops all orphan users without matching Logins in all databases present on server &#39;sqlserver2014a&#39; PS C:\\> Remove-DbaDbOrphanUser -SqlInstance sqlserver2014a -SqlCredential $cred Finds and drops all orphan users without matching Logins in all databases present on server 'sqlserver2014a'. SQL Server authentication will be used in connecting to the server. Example 3: Finds and drops orphan users even if they have a matching Login on both db1 and db2 databases PS C:\\> Remove-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1, db2 -Force Example 4: Finds and drops orphan users even if they have a matching Login from all databases except db1 and db2 PS C:\\> Remove-DbaDbOrphanUser -SqlInstance sqlserver2014a -ExcludeDatabase db1, db2 -Force Example 5: Removes user OrphanUser from all databases only if there is no matching login PS C:\\> Remove-DbaDbOrphanUser -SqlInstance sqlserver2014a -User OrphanUser Example 6: Removes user OrphanUser from all databases even if they have a matching Login PS C:\\> Remove-DbaDbOrphanUser -SqlInstance sqlserver2014a -User OrphanUser -Force Removes user OrphanUser from all databases even if they have a matching Login. Any schema that the user owns will change ownership to dbo. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for orphaned users. Accepts single database names, comma-separated lists, or arrays. When omitted, all accessible, non-read-only databases on the instance are processed. Contained databases are automatically skipped since they cannot have orphaned users. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during orphaned user removal. Useful when you want to process most databases but avoid specific ones. Commonly used to exclude system databases, databases undergoing maintenance, or databases where user cleanup should be handled separately. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -User Specifies specific orphaned users to target for removal instead of processing all orphaned users found. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Force Bypasses safety checks that normally prevent orphaned user removal in potentially problematic scenarios. Required when the user owns schemas containing objects (ownership transfers to 'dbo') or when a matching login exists on the server (suggesting repair might be more appropriate than removal). Use with caution as this can change schema ownership and remove users that could potentially be repaired instead. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object for each schema operation (ownership change or drop) that occurs during orphaned user removal. No output is generated if: An orphaned user owns no schemas A user is skipped due to schema complexity without the -Force parameter A matching login exists and -Force is not specified When schema operations occur, returns objects with the following properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: The database containing the schema being modified SchemaName: The name of the schema being modified Action: The operation performed - either \"DROP\" or \"ALTER OWNER\" SchemaOwnerBefore: The original owner of the schema before the operation SchemaOwnerAfter: The new owner of the schema after the operation (either \"dbo\" for ALTER OWNER or \"N/A\" for DROP) Note: User removal is performed silently without output objects. Output objects track only schema ownership changes and drops, not the user removal itself. &nbsp;"
  },
  {
    "name": "Remove-DbaDbPartitionFunction",
    "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.",
    "category": "Database Operations",
    "tags": [
      "partitionfunction",
      "database"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbPartitionFunction",
    "popularityRank": 685,
    "synopsis": "Drops partition functions from SQL Server databases to clean up unused partitioning schemes.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbPartitionFunction View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Drops partition functions from SQL Server databases to clean up unused partitioning schemes. 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. Syntax Remove-DbaDbPartitionFunction [-SqlInstance ] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-WhatIf] [-Confirm] [ ] Remove-DbaDbPartitionFunction [-SqlInstance ] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes partition functions from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> Remove-DbaDbPartitionFunction -SqlInstance localhost, sql2016 -Database db1, db2 Example 2: Using a pipeline this command gets all partition functions on SRV1, lets the user select those to remove and... PS C:\\> Get-DbaDbPartitionFunction -SqlInstance SRV1 | Out-GridView -Title 'Select partition function(s) to drop' -OutputMode Multiple | Remove-DbaDbPartitionFunction Using a pipeline this command gets all partition functions on SRV1, lets the user select those to remove and then removes the selected partition functions. Required Parameters -InputObject Accepts partition function objects from Get-DbaDbPartitionFunction for targeted removal operations. Use this with pipeline operations when you need to selectively remove specific partition functions based on criteria like name patterns, usage, or dependencies. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database(s) from which to remove partition functions. Accepts wildcard patterns for matching multiple databases. Use this to target specific databases when you need to clean up partitioning objects from particular databases rather than all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes the specified database(s) from partition function removal operations. Auto-populated with available databases from the target server. Use this when you want to remove partition functions from most databases but need to preserve them in specific databases like production or critical systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per partition function removal attempt. The object contains information about the operation outcome regardless of success or failure. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database containing the partition function PartitionFunctionName: The name of the partition function that was removed Status: The outcome of the drop operation - either \"Dropped\" on success or the error message on failure IsRemoved: Boolean indicating whether the partition function was successfully removed ($true) or not ($false) &nbsp;"
  },
  {
    "name": "Remove-DbaDbPartitionScheme",
    "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.",
    "category": "Database Operations",
    "tags": [
      "partitionscheme",
      "partition",
      "database"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbPartitionScheme",
    "popularityRank": 701,
    "synopsis": "Removes database partition schemes from SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbPartitionScheme View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes database partition schemes from SQL Server databases. 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. The 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. Each removal operation includes confirmation prompts by default to prevent accidental deletion of partition schemes that may still be referenced by tables or indexes. Syntax Remove-DbaDbPartitionScheme [-SqlInstance ] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-WhatIf] [-Confirm] [ ] Remove-DbaDbPartitionScheme [-SqlInstance ] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes partition schemes from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> Remove-DbaDbPartitionScheme -SqlInstance localhost, sql2016 -Database db1, db2 Example 2: Using a pipeline this command gets all partition schemes on SRV1, lets the user select those to remove and... PS C:\\> Get-DbaDbPartitionScheme -SqlInstance SRV1 | Out-GridView -Title 'Select partition scheme(s) to drop' -OutputMode Multiple | Remove-DbaDbPartitionScheme Using a pipeline this command gets all partition schemes on SRV1, lets the user select those to remove and then removes the selected partition schemes. Required Parameters -InputObject Accepts partition scheme objects piped from Get-DbaDbPartitionScheme for targeted removal operations. Use this for selective removal workflows where you first identify specific partition schemes and then remove only those schemes. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for partition schemes to remove. Accepts multiple database names. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip when scanning for partition schemes to remove. Accepts multiple database names. Use this to exclude system databases or specific databases you want to preserve during bulk partition scheme cleanup operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per partition scheme removal operation with the following properties: ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the partition scheme PartitionSchemeName: The name of the partition scheme that was processed Status: The result of the removal operation (\"Dropped\" on success, or error message on failure) IsRemoved: Boolean indicating whether the partition scheme was successfully dropped (true) or failed (false) &nbsp;"
  },
  {
    "name": "Remove-DbaDbRole",
    "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 'dbo'. 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.",
    "category": "Utilities",
    "tags": [
      "role"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbRole",
    "popularityRank": 545,
    "synopsis": "Removes custom database roles from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbRole View Source Ben Miller (@DBAduck), the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes custom database roles from SQL Server databases 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. When 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 'dbo'. If schemas contain objects, use -Force to allow ownership transfer and proceed with role removal. You 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. Syntax Remove-DbaDbRole [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Role] ] [[-ExcludeRole] ] [-IncludeSystemDbs] [[-InputObject] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes roles customrole1 and customrole2 from the database dbname on the local default SQL Server instance PS C:\\> Remove-DbaDbRole -SqlInstance localhost -Database dbname -Role \"customrole1\", \"customrole2\" Example 2: Removes role1,role2,role3 from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> Remove-DbaDbRole -SqlInstance localhost, sql2016 -Database db1, db2 -Role role1, role2, role3 Example 3: Removes role1 from db1 and db2 on the servers in C:\\servers.txt PS C:\\> $servers = Get-Content C:\\servers.txt PS C:\\> $servers | Remove-DbaDbRole -Database db1, db2 -Role role1 Example 4: Removes role1,role2,role3 from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> $roles = Get-DbaDbRole -SqlInstance localhost, sql2016 -Database db1, db2 -Role role1, role2, role3 PS C:\\> $roles | Remove-DbaDbRole Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to remove roles from. Accepts multiple database names and supports wildcards for pattern matching. When omitted, the function processes all user databases on the instance. Use this when you need to clean up roles from specific databases only. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from role removal operations. Accepts multiple database names and supports wildcards. Use this when processing all databases except certain ones, such as excluding production databases during cleanup operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Role Specifies which custom database roles to remove. Accepts multiple role names and supports wildcards for pattern matching. When 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeRole Excludes specific roles from removal operations. Accepts multiple role names and supports wildcards. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeSystemDbs Allows role removal operations to target system databases (master, model, msdb, tempdb). By 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 system databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts piped objects from Get-DbaDbRole, Get-DbaDatabase, or SQL Server instances for processing. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Force Forces schema ownership transfer to 'dbo' when the role owns schemas containing database objects. Without this, role removal fails if owned schemas contain objects. Use this during role cleanup when you need to ensure complete removal regardless of schema dependencies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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. &nbsp;"
  },
  {
    "name": "Remove-DbaDbRoleMember",
    "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.",
    "category": "Utilities",
    "tags": [
      "role",
      "user"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbRoleMember",
    "popularityRank": 429,
    "synopsis": "Removes database users from database roles across SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbRoleMember View Source Ben Miller (@DBAduck) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes database users from database roles across SQL Server instances. 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. Handles 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. Syntax Remove-DbaDbRoleMember [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Role] ] [-User] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes user1 from the role db_owner in the database mydb on the local default SQL Server instance PS C:\\> Remove-DbaDbRoleMember -SqlInstance localhost -Database mydb -Role db_owner -User user1 Example 2: Removes user1 in servers localhost and sql2016 in the msdb database from the SqlAgentOperatorRole PS C:\\> Remove-DbaDbRoleMember -SqlInstance localhost, sql2016 -Role SqlAgentOperatorRole -User user1 -Database msdb Example 3: Removes user1 from the SqlAgentOperatorRole in the msdb database in every server in C:\\servers.txt PS C:\\> $servers = Get-Content C:\\servers.txt PS C:\\> $servers | Remove-DbaDbRoleMember -Role SqlAgentOperatorRole -User user1 -Database msdb Example 4: Removes user1 in the database DEMODB on the server localhost from the roles db_datareader and db_datawriter PS C:\\> $db = Get-DbaDataabse -SqlInstance localhost -Database DEMODB PS C:\\> $db | Remove-DbaDbRoleMember -Role \"db_datareader\",\"db_datawriter\" -User user1 Example 5 PS C:\\> $roles = Get-DbaDbRole -SqlInstance localhost -Role \"db_datareader\",\"db_datawriter\" PS C:\\> $roles | Remove-DbaDbRoleMember -User user1 Required Parameters -User Specifies the database users to remove from the specified roles. Accepts multiple usernames for bulk operations. The function validates that users are actually members of the roles before attempting removal, preventing errors when users aren't currently assigned to the roles. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to process for role member removal. Accepts wildcards for pattern matching. When 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Role Specifies the database roles to remove users from, such as db_datareader, db_datawriter, db_owner, or custom roles. Accepts multiple roles to remove users from several roles simultaneously. Required unless you're piping in DatabaseRole objects from Get-DbaDbRole. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts piped input from Get-DbaDatabase, Get-DbaDbRole, or SQL Server instance objects. Use this to chain commands together, such as piping specific databases or roles to process only those objects instead of specifying them via parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This command does not return any output objects. It removes specified users from database roles and returns no information about the operation. &nbsp;"
  },
  {
    "name": "Remove-DbaDbSchema",
    "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'll need to remove or relocate all schema objects first before running this command.",
    "category": "Database Operations",
    "tags": [
      "schema",
      "database"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbSchema",
    "popularityRank": 546,
    "synopsis": "Removes database schemas from one or more SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbSchema View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes database schemas from one or more SQL Server databases. 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'll need to remove or relocate all schema objects first before running this command. Syntax Remove-DbaDbSchema [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [-Schema] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the TestSchema1 schema in the example1 database in the sqldev01 instance PS C:\\> Remove-DbaDbSchema -SqlInstance sqldev01 -Database example1 -Schema TestSchema1 Example 2: Passes in the example1 db via pipeline and removes the TestSchema1 and TestSchema2 schemas PS C:\\> Get-DbaDatabase -SqlInstance sqldev01, sqldev02 -Database example1 | Remove-DbaDbSchema -Schema TestSchema1, TestSchema2 Required Parameters -Schema Specifies the name(s) of the schema(s) to remove from the target databases. The schema must be completely empty before removal. Any tables, views, functions, stored procedures, or other objects within the schema must be dropped or moved first. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target database(s) where schemas will be removed. Required when using SqlInstance parameter. Use this to limit schema removal to specific databases rather than affecting all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase via pipeline input. Use this when you need to work with pre-filtered database collections. Eliminates the need to specify SqlInstance and Database parameters when database objects are already available. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This command does not return any output objects. It removes the specified database schemas and returns no information about the operation. &nbsp;"
  },
  {
    "name": "Remove-DbaDbSequence",
    "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.",
    "category": "Utilities",
    "tags": [
      "data",
      "sequence",
      "table"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbSequence",
    "popularityRank": 676,
    "synopsis": "Removes database sequence objects from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbSequence View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes database sequence objects from SQL Server instances. Description Removes sequence objects from SQL Server databases, freeing up schema namespace and cleaning up unused database objects. Sequences are commonly used for generating unique numeric values and may need removal during application changes or database cleanup. When used without a pipeline, the function will first retrieve matching sequences using Get-DbaDbSequence with the provided parameters, then remove them. Pipeline input from Get-DbaDbSequence allows for selective removal after review or filtering. Syntax Remove-DbaDbSequence [-SqlInstance] [-SqlCredential ] [-Database ] [-Sequence ] [-Schema ] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaDbSequence -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the sequence TestSequence in the TestDB database on the sqldev01 instance PS C:\\> Remove-DbaDbSequence -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence Example 2: Using a pipeline this command gets all sequences on SRV1, lets the user select those to remove and then... PS C:\\> Get-DbaDbSequence -SqlInstance SRV1 | Out-GridView -Title 'Select sequence(s) to drop' -OutputMode Multiple | Remove-DbaDbSequence Using a pipeline this command gets all sequences on SRV1, lets the user select those to remove and then removes the selected sequences. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts sequence objects piped from Get-DbaDbSequence for removal. This allows you to first review sequences with Get-DbaDbSequence before selectively removing them. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for sequences to remove. Accepts wildcards for pattern matching. Use this to limit sequence removal to specific databases instead of searching all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Sequence Specifies the name(s) of the sequences to remove. Accepts wildcards for pattern matching. Use this when you know the exact sequence names or want to remove sequences matching a naming pattern. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -Schema Filters sequences to remove by schema name. Accepts wildcards for pattern matching. Useful when you need to remove sequences from specific schemas only, such as during application module cleanup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per sequence removed, with the following properties: ComputerName: The name of the computer where the sequence was dropped InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the sequence Sequence: The fully qualified sequence name in format schema.name SequenceName: The name of the sequence without schema qualification SequenceSchema: The schema name containing the sequence Status: The result of the drop operation (either \"Dropped\" on success or the error message on failure) IsRemoved: Boolean indicating if the sequence was successfully dropped ($true) or failed ($false) &nbsp;"
  },
  {
    "name": "Remove-DbaDbSnapshot",
    "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.",
    "category": "Database Operations",
    "tags": [
      "snapshot",
      "database"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbSnapshot",
    "popularityRank": 498,
    "synopsis": "Drops database snapshots from SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbSnapshot View Source Simone Bizzotto (@niphold) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Drops database snapshots from SQL Server instances 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. Syntax Remove-DbaDbSnapshot [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Snapshot] ] [[-InputObject] ] [-AllSnapshots] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes database snapshots named HR_snap_20161201 and HR_snap_20161101 PS C:\\> Remove-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snap_20161201, HR_snap_20161101 Example 2: Removes all database snapshots having HR and Accounting as base dbs PS C:\\> Remove-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting Example 3: Removes all database snapshots having HR and Accounting as base dbs PS C:\\> Get-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting | Remove-DbaDbSnapshot Example 4: Removes HR_snapshot and Accounting_snapshot PS C:\\> Remove-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snapshot, Accounting_snapshot Example 5: Removes all snapshots associated with databases that have dumpsterfire in the name PS C:\\> Get-DbaDbSnapshot -SqlInstance sql2016 | Where-Object SnapshotOf -like 'dumpsterfire' | Remove-DbaDbSnapshot Example 6: Allows the selection of snapshots on sql2016 to remove PS C:\\> Get-DbaDbSnapshot -SqlInstance sql2016 | Out-GridView -PassThru | Remove-DbaDbSnapshot Example 7: Removes all database snapshots from sql2014 PS C:\\> Remove-DbaDbSnapshot -SqlInstance sql2014 -AllSnapshots Example 8: Removes all database snapshots from sql2014 and prompts for each database PS C:\\> Remove-DbaDbSnapshot -SqlInstance sql2014 -AllSnapshots -Confirm Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the base database(s) whose snapshots should be removed. Only snapshots created from these source databases will be dropped. Use this when you need to clean up snapshots for specific databases while leaving other snapshots intact. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes snapshots from the specified base database(s) from removal. All other snapshots on the instance will be removed. Use this when you want to remove most snapshots but preserve those from critical databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Snapshot Specifies the exact snapshot name(s) to remove. Accepts multiple snapshot names for targeted removal operations. Use this when you know the specific snapshot names you want to drop, such as outdated test or reporting snapshots. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database snapshot objects from Get-DbaDbSnapshot for pipeline operations. This allows filtering and processing snapshots before removal. Use this for complex filtering scenarios where you first identify specific snapshots with Get-DbaDbSnapshot. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -AllSnapshots Removes all database snapshots found on the target SQL Server instance(s). This affects every snapshot regardless of source database. Use this for complete snapshot cleanup operations, typically during maintenance windows or server decommissioning. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Terminates active connections and running queries against snapshots to allow the drop operation to complete successfully. Use this when snapshots have active sessions that would normally block the removal process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts for confirmation of every step. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per snapshot dropped, with the following properties: Default display properties (via Select-DefaultView): ComputerName: The name of the computer where the snapshot was dropped InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the snapshot that was dropped (displayed as Name, stored as Database) Status: The result of the drop operation (either \"Dropped\" on success or the error message on failure) &nbsp;"
  },
  {
    "name": "Remove-DbaDbSynonym",
    "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't have to manually script DROP statements across multiple databases or instances.",
    "category": "Database Operations",
    "tags": [
      "synonym",
      "database"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbSynonym",
    "popularityRank": 657,
    "synopsis": "Removes database synonyms from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbSynonym View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes database synonyms from SQL Server databases 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't have to manually script DROP statements across multiple databases or instances. Syntax Remove-DbaDbSynonym [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Schema] ] [[-ExcludeSchema] ] [[-Synonym] ] [[-ExcludeSynonym] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes synonyms synonym1 and synonym2 from the database db1 on the local default SQL Server instance PS C:\\> Remove-DbaDbSynonym -SqlInstance localhost -Database db1 -Synonym \"synonym1\", \"synonym2\" Example 2: Removes synonym1, synonym2, synonym3 from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> Remove-DbaDbSynonym -SqlInstance localhost, sql2016 -Database db1, db2 -Synonym synonym1, synonym2, synonym3 Example 3: Removes synonym1 from db1 and db2 on the servers in C:\\servers.txt PS C:\\> $servers = Get-Content C:\\servers.txt PS C:\\> $servers | Remove-DbaDbSynonym -Database db1, db2 -Synonym synonym1 Example 4: Removes synonym1, synonym2, synonym3 from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> $synonyms = Get-DbaDbSynonym -SqlInstance localhost, sql2016 -Database db1, db2 -Synonym synonym1, synonym2, synonym3 PS C:\\> $synonyms | Remove-DbaDbSynonym Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to remove synonyms from. Accepts wildcards for pattern matching. Use this to target specific databases instead of processing all databases on the instance. If unspecified, all databases will be processed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during synonym removal operations. Use this when you want to process most databases but exclude specific ones like system databases or production databases during maintenance windows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Specifies which schemas to target for synonym removal within the selected databases. Use this to limit removal to synonyms in specific schemas like 'dbo', 'reporting', or custom application schemas. If unspecified, all schemas will be processed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSchema Specifies schemas to skip during synonym removal operations. Use this to avoid removing synonyms from critical schemas while processing others, such as excluding 'sys' or application-specific schemas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Synonym Specifies the exact synonym names to remove from the target databases. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSynonym Specifies synonym names to skip during the removal operation. Use this when you want to remove most synonyms but preserve specific ones that are still in use by applications or reports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts piped input from Get-DbaDbSynonym, Get-DbaDatabase, or SQL Server instances. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per synonym successfully removed, containing the following properties: ComputerName: The name of the computer where the SQL Server instance resides InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database from which the synonym was removed Synonym: The name of the synonym that was removed Status: The status of the removal operation (set to \"Removed\" on success) Note: Failed removal operations are reported through error handling but do not produce output objects. &nbsp;"
  },
  {
    "name": "Remove-DbaDbTable",
    "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.",
    "category": "Database Operations",
    "tags": [
      "table",
      "database"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbTable",
    "popularityRank": 270,
    "synopsis": "Drops tables from SQL Server databases with safety controls and detailed status reporting.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbTable View Source Andreas Jordan (@JordanOrdix), ordix.de Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Drops tables from SQL Server databases with safety controls and detailed status reporting. 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. Syntax Remove-DbaDbTable [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Table] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes table1, table2, table3 from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> Remove-DbaDbTable -SqlInstance localhost, sql2016 -Database db1, db2 -Table table1, table2, table3 Example 2: Removes table1, table2, table3 from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> $tables = Get-DbaDbTable -SqlInstance localhost, sql2016 -Database db1, db2 -Table table1, table2, table3 PS C:\\> $tables | Remove-DbaDbTable Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to target for table removal operations. Accepts multiple database names as an array. Use this when you need to remove tables from specific databases rather than searching across all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Specifies the names of tables to remove from the target databases. Accepts multiple table names as an array. Tables 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. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts table objects directly from Get-DbaDbTable for removal operations. This approach allows for advanced filtering and validation before deletion. Use this parameter when you need to remove tables based on complex criteria like size, row count, or schema patterns that Get-DbaDbTable can filter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per table removed, containing the following properties: ComputerName: The name of the computer where the SQL Server instance resides InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the table Table: The full table name in schema.name format TableName: The name of the table without schema prefix TableSchema: The schema name containing the table Status: The result of the removal operation (\"Dropped\" on success, or the error message on failure) IsRemoved: Boolean indicating whether the table was successfully removed (true for success, false for failure) &nbsp;"
  },
  {
    "name": "Remove-DbaDbTableData",
    "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's 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.",
    "category": "Data Operations",
    "tags": [
      "table",
      "data"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbTableData",
    "popularityRank": 161,
    "synopsis": "Performs batch deletion of table data while controlling transaction log growth during large-scale data removal operations.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbTableData View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Performs batch deletion of table data while controlling transaction log growth during large-scale data removal operations. 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's 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. This 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. Foreign 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. Two deletion modes are supported: 1. Simple table deletion using -Table and -BatchSize parameters where the DELETE statement is automatically generated 2. Complex deletions with custom WHERE clauses, JOINs, or ORDER BY using the -DeleteSql parameter for advanced scenarios The command returns detailed metadata about the deletion process including row counts, timing information, and log backup details to help you monitor progress and performance. Syntax Remove-DbaDbTableData [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-BatchSize] ] [[-Table] ] [[-DeleteSql] ] [[-LogBackupPath] ] [[-LogBackupTimeStampFormat] ] [[-AzureBaseUrl] ] [[-AzureCredential] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all data from the dbo.Test table in the TestDb database on the local SQL instance PS C:\\> Remove-DbaDbTableData -SqlInstance localhost -Database TestDb -Table dbo.Test -BatchSize 1000000 -LogBackupPath E:\\LogBackups -Confirm:$false Removes 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. Example 2: -LogBackupPath E:\\LogBackups -Confirm:$false Removes data from the dbo.Test table in the TestDb database on... PS C:\\> Remove-DbaDbTableData -SqlInstance localhost -Database TestDb -DeleteSql \"DELETE TOP (1000000) deleteFromTable FROM dbo.Test deleteFromTable LEFT JOIN dbo.Test2 b ON deleteFromTable.Id = b.Id\" -LogBackupPath E:\\LogBackups -Confirm:$false Removes 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 are done in batches of 1000000 rows each and the log backups are written to E:\\LogBackups. Example 3: -LogBackupPath E:\\LogBackups -Confirm:$false Removes data from the dbo.Test table based on the DELETE... PS C:\\> Remove-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;\" -LogBackupPath E:\\LogBackups -Confirm:$false Removes 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 1000000 rows each and the log backups are written to E:\\LogBackups. Example 4: Removes data from the dbo.Test table in the TestDb1 and TestDb2 databases on the local SQL instance PS C:\\> Get-DbaDatabase -SqlInstance localhost -Database TestDb1, TestDb2 | Remove-DbaDbTableData -Table dbo.Test -BatchSize 1000000 -LogBackupPath E:\\LogBackups -Confirm:$false Removes 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 E:\\LogBackups. Example 5: Removes data from the dbo.Test table in the TestDb database on the SQL instances represented by $server and... PS C:\\> $server, $server2 | Remove-DbaDbTableData -Database TestDb -Table dbo.Test -BatchSize 1000000 -LogBackupPath E:\\LogBackups -Confirm:$false Removes 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 written to E:\\LogBackups. Example 6: Timeout=30;Encrypt=True;TrustServerCertificate=False;User Id=dbuser;Password=strongpassword;Database=TestDb&quot;... PS C:\\> $server = Connect-DbaInstance -ConnectionString \"Data Source=TCP:yourserver.database.windows.net,1433;MultipleActiveResultSets=False;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False;User Id=dbuser;Password=strongpassword;Database=TestDb\" Remove-DbaDbTableData -SqlInstance $server -Database TestDb -Table dbo.Test -BatchSize 1000000 -Confirm:$false Removes 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 SQL. Note: for Azure SQL databases error 40552 could occur for large batch deletions: https://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 Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to include in the table data removal operation. Accepts wildcards for pattern matching. If unspecified, all user databases on the instance will be processed, which means the same table deletion will occur across multiple databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. For Azure SQL databases, large batch sizes may trigger error 40552 due to transaction log space limits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 100000 | -Table Specifies the fully qualified table name from which to delete data (e.g., dbo.CustomerHistory, Sales.OrderDetails). Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DeleteSql Provides a custom DELETE statement for complex deletion scenarios involving WHERE clauses, JOINs, or ORDER BY conditions. Must include a TOP (N) clause to control batch size (e.g., \"DELETE TOP (100000) FROM dbo.Orders WHERE OrderDate Outputs PSCustomObject Returns one object per database where table data removal was performed, providing detailed metrics about the batch deletion operation. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance Database: The name of the database where table data was removed Sql: The T-SQL DELETE statement that was executed TotalRowsDeleted: The total number of rows deleted from the table across all batches (integer) TotalTimeMillis: The total execution time for all delete operations in milliseconds (double) AvgTimeMillis: The average execution time per batch iteration in milliseconds (double) TotalIterations: The number of batch iterations performed (integer) *Additional properties available (all properties accessible via Select-Object ):* Timings: Array of TimeSpan objects representing the execution time of each individual batch deletion iteration LogBackups: Array of backup objects returned from Backup-DbaDatabase operations performed during the deletion (empty for Simple recovery model or Azure SQL Database) When 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 advanced analysis of the deletion performance metrics. &nbsp;"
  },
  {
    "name": "Remove-DbaDbUdf",
    "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.",
    "category": "Database Operations",
    "tags": [
      "udf",
      "database"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbUdf",
    "popularityRank": 664,
    "synopsis": "Removes user-defined functions and user-defined aggregates from SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbUdf View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes user-defined functions and user-defined aggregates from SQL Server databases. 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. Syntax Remove-DbaDbUdf [-SqlInstance] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-ExcludeSystemUdf] [-Schema ] [-ExcludeSchema ] [-Name ] [-ExcludeName ] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaDbUdf -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes udf1, udf2, udf3 from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> Remove-DbaDbUdf -SqlInstance localhost, sql2016 -Database db1, db2 -Name udf1, udf2, udf3 Example 2: Removes udf1, udf2, udf3 from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> $udfs = Get-DbaDbUdf -SqlInstance localhost, sql2016 -Database db1, db2 -Name udf1, udf2, udf3 PS C:\\> $udfs | Remove-DbaDbUdf Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts UDF and UDA objects directly from Get-DbaDbUdf pipeline operations. Use this when you need to filter or examine UDFs or UDAs first before removal, enabling complex selection logic not possible with simple name matching. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to process for UDF removal. Accepts multiple database names and supports wildcards. Use this to limit the operation to specific databases instead of processing all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during UDF removal operations. Auto-populated with server database names for tab completion. Use this when you want to process most databases but exclude specific ones like production or system databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSystemUdf Excludes system-generated and built-in user-defined functions from removal operations. Use this safety switch to prevent accidental deletion of system UDFs that may be required for database functionality. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Schema Specifies which schemas to include when removing UDFs. Accepts multiple schema names. Use this to target UDFs in specific schemas like 'dbo', 'reporting', or custom application schemas while leaving others untouched. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSchema Specifies schemas to skip during UDF removal operations. Use this to protect critical schemas from modification while processing UDFs in other schemas throughout the database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies the exact names of UDFs to remove. Accepts multiple function names and supports wildcards. Use this for targeted removal of specific functions like deprecated calculation functions or obsolete business logic UDFs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeName Specifies UDF names to skip during removal operations. Accepts multiple function names and wildcards. Use this to protect specific functions from deletion while removing others that match your criteria. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per user-defined function or user-defined aggregate that was processed for removal. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance SqlInstance: The fully qualified SQL Server instance name (computer\\instance format) Database: The name of the database containing the UDF or UDA Udf: The fully qualified name of the function (schema.name format) UdfName: The unqualified function name UdfSchema: The schema name containing the function Status: The result of the removal operation (\"Dropped\" for successful removals, or error message for failures) IsRemoved: Boolean indicating whether the UDF or UDA was successfully removed (True if dropped, False if failed) &nbsp;"
  },
  {
    "name": "Remove-DbaDbUser",
    "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 'dbo'. 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.",
    "category": "Utilities",
    "tags": [
      "user"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbUser",
    "popularityRank": 132,
    "synopsis": "Removes database users from SQL Server databases with intelligent schema ownership handling",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbUser View Source Doug Meyers (@dgmyrs) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes database users from SQL Server databases with intelligent schema ownership handling 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. When 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 'dbo'. If schemas contain objects, use -Force to allow ownership transfer and proceed with user removal. The 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. Syntax Remove-DbaDbUser [-SqlInstance] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] -User [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaDbUser -InputObject [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Drops user1 from all databases it exists in on server &#39;sqlserver2014&#39; PS C:\\> Remove-DbaDbUser -SqlInstance sqlserver2014 -User user1 Example 2: Drops user1 from the database1 database on server &#39;sqlserver2014&#39; PS C:\\> Remove-DbaDbUser -SqlInstance sqlserver2014 -Database database1 -User user1 Example 3: Drops user1 from all databases it exists in on server &#39;sqlserver2014&#39; except for the model database PS C:\\> Remove-DbaDbUser -SqlInstance sqlserver2014 -ExcludeDatabase model -User user1 Example 4: Drops user1 from all databases it exists in on server &#39;sqlserver2014&#39; PS C:\\> Get-DbaDbUser sqlserver2014 | Where-Object Name -In \"user1\" | Remove-DbaDbUser Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -User Specifies the database user(s) to remove from the target databases. Accepts multiple user names for bulk operations. The function will automatically handle schema ownership conflicts that typically prevent user deletion. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts user objects from Get-DbaDbUser for pipeline operations. This allows for advanced filtering scenarios. Use this when you need to remove users based on complex criteria like creation date, permissions, or other user properties. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database(s) from which to remove the specified users. Accepts wildcards for pattern matching. When omitted, the function processes all accessible databases on the instance to find and remove the specified users. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies the database(s) to skip during user removal operations. Use this to protect critical databases like system databases. Commonly used to exclude model, tempdb, or production databases during bulk user cleanup operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Forces schema ownership transfer to 'dbo' when the user owns schemas containing database objects. Without this, user removal fails if owned schemas contain objects. Use this during user deprovisioning when you need to ensure complete cleanup regardless of schema dependencies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per user successfully removed, with the following properties: ComputerName: The computer name of the SQL Server instance where the user was removed InstanceName: The SQL Server instance name where the user was removed SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name from which the user was removed User: The Microsoft.SqlServer.Management.Smo.User object that was removed Status: Result of the removal operation - \"Dropped\" on success or \"Not Dropped\" on failure When 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 removal succeeds. &nbsp;"
  },
  {
    "name": "Remove-DbaDbView",
    "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.",
    "category": "Database Operations",
    "tags": [
      "view",
      "database"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaDbView",
    "popularityRank": 636,
    "synopsis": "Removes database views from SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaDbView View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes database views from SQL Server databases 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. Syntax Remove-DbaDbView [-SqlInstance] [-SqlCredential ] [-Database ] [-View ] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaDbView -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes view1, view2, view3 from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> Remove-DbaDbView -SqlInstance localhost, sql2016 -Database db1, db2 -View view1, view2, view3 Example 2: Removes view1, view2, view3 from db1 and db2 on the local and sql2016 SQL Server instances PS C:\\> $views = Get-DbaDbView -SqlInstance localhost, sql2016 -Database db1, db2 -View view1, view2, view3 PS C:\\> $views | Remove-DbaDbView Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts view objects from Get-DbaDbView for pipeline operations. Use this for complex filtering scenarios or bulk removals. This approach provides better control over which specific views get removed compared to using name-based targeting. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to search for views to remove. Accepts multiple database names. Use this to limit view removal to specific databases instead of searching all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -View Specifies the names of the views to remove. Accepts multiple view names and supports wildcards for pattern matching. When targeting views in specific schemas, use the two-part naming convention like 'dbo.ViewName'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. This is the default. Use -Confirm:$false to suppress these prompts. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per view removed, with the following properties: ComputerName: The computer name of the SQL Server instance where the view was removed InstanceName: The SQL Server instance name where the view was removed SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name from which the view was removed View: The schema-qualified view name in the format 'schema.viewname' (e.g., 'dbo.MyView') ViewName: The view name only (without schema prefix) ViewSchema: The schema name containing the view Status: Result of the removal operation - \"Dropped\" on success or the error message on failure IsRemoved: Boolean indicating whether the view was successfully removed ($true) or failed ($false) &nbsp;"
  },
  {
    "name": "Remove-DbaEndpoint",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "endpoint"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaEndpoint",
    "popularityRank": 643,
    "synopsis": "Removes SQL Server endpoints including DatabaseMirroring, ServiceBroker, Soap, and TSql types.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaEndpoint View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Server endpoints including DatabaseMirroring, ServiceBroker, Soap, and TSql types. 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. Syntax Remove-DbaEndpoint [[-SqlInstance] ] [[-SqlCredential] ] [[-Endpoint] ] [-AllEndpoints] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all endpoints on the sqlserver2014 instance PS C:\\> Remove-DbaEndpoint -SqlInstance sqlserver2012 -AllEndpoints Removes all endpoints on the sqlserver2014 instance. Prompts for confirmation. Example 2: Removes the endpoint1 and endpoint2 endpoints PS C:\\> Remove-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1,endpoint2 -Confirm:$false Removes the endpoint1 and endpoint2 endpoints. Does not prompt for confirmation. Example 3: Removes the endpoints returned from the Get-DbaEndpoint function PS C:\\> Get-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1 | Remove-DbaEndpoint Removes the endpoints returned from the Get-DbaEndpoint function. Prompts for confirmation. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Endpoint Specifies the names of specific endpoints to remove from the SQL Server instance. Accepts multiple endpoint names as an array. Use this when you need to selectively remove particular endpoints like 'Mirroring' or custom service broker endpoints while leaving others intact. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllEndpoints Removes all user-defined endpoints from the SQL Server instance, excluding system endpoints that cannot be dropped. Use this for complete endpoint cleanup during decommissioning or when hardening an instance by removing all custom network entry points. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts endpoint objects from the pipeline, typically from Get-DbaEndpoint output. Allows for filtering endpoints before removal. Use this when you need to apply complex filtering logic or when chaining endpoint discovery and removal operations together. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per successfully removed endpoint. Properties: ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName) Endpoint: The name of the endpoint that was removed Status: The status of the removal operation (always \"Removed\" for successful removals) &nbsp;"
  },
  {
    "name": "Remove-DbaExtendedProperty",
    "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.",
    "category": "Utilities",
    "tags": [
      "extendedproperties"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaExtendedProperty",
    "popularityRank": 651,
    "synopsis": "Removes custom metadata and documentation stored as extended properties from SQL Server objects",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaExtendedProperty View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes custom metadata and documentation stored as extended properties from SQL Server objects 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. This 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. The 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. Syntax Remove-DbaExtendedProperty [-InputObject] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the appversion extended property from the mydb database PS C:\\> Get-DbaDatabase -SqlInstance localhost -Database mydb | Get-DbaExtendedProperty -Name appversion | Remove-DbaExtendedProperty Example 2: Removes the appversion extended property on the mytable table of the mydb database and does not prompt for... PS C:\\> Get-DbaDbTable -SqlInstance localhost -Database mydb -Table mytable | Get-DbaExtendedProperty -Name appversion | Remove-DbaExtendedProperty -Confirm:$false Removes the appversion extended property on the mytable table of the mydb database and does not prompt for confirmation Required Parameters -InputObject Specifies the extended property objects to remove from SQL Server objects. Accepts ExtendedProperty objects from Get-DbaExtendedProperty. Use this to remove outdated documentation, compliance tags, or metadata stored as extended properties on databases, tables, columns, and other SQL Server objects. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per successfully removed extended property. Properties: ComputerName: The name of the computer where the SQL Server instance is running InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName) ParentName: The name of the parent SQL Server object from which the extended property was removed PropertyType: The type of extended property that was removed Name: The name of the extended property that was removed Status: The status of the removal operation (always \"Dropped\" for successful removals) &nbsp;"
  },
  {
    "name": "Remove-DbaFirewallRule",
    "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.",
    "category": "Utilities",
    "tags": [
      "firewall",
      "network",
      "connection"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaFirewallRule",
    "popularityRank": 686,
    "synopsis": "Removes Windows firewall rules for SQL Server Engine, Browser, and DAC connections from target computers.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaFirewallRule View Source Andreas Jordan (@JordanOrdix), ordix.de Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes Windows firewall rules for SQL Server Engine, Browser, and DAC connections from target computers. 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. The 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. This 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. The functionality is currently limited to rules created by dbatools. Future versions may introduce breaking changes, so review scripts after updating dbatools. Syntax Remove-DbaFirewallRule [-SqlInstance] [-Credential ] [-Type ] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaFirewallRule -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the firewall rule for the default instance on SRV1 PS C:\\> Remove-DbaFirewallRule -SqlInstance SRV1 Example 2: Removes the firewall rule for the instance SQL2016 on SRV1 and the firewall rule for the SQL Server Browser PS C:\\> Remove-DbaFirewallRule -SqlInstance SRV1\\SQL2016 -Type Engine, Browser Example 3: Removes the firewall rules for all instance from SRV1 PS C:\\> Get-DbaFirewallRule -SqlInstance SRV1 -Type AllInstance | Where-Object Type -eq 'Engine' | Remove-DbaFirewallRule Removes the firewall rules for all instance from SRV1. Leaves the firewall rule for the SQL Server Browser in place. Example 4: Removes the firewall rule for the default instance on SRV1 PS C:\\> Remove-DbaFirewallRule -SqlInstance SRV1 -Confirm:$false Removes the firewall rule for the default instance on SRV1. Does not prompt for confirmation. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts firewall rule objects from Get-DbaFirewallRule for pipeline-based removal operations. Use this when you need to filter or review existing firewall rules before removing them, allowing for more precise control over which rules get deleted. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Credential object used to connect to the Computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies which types of SQL Server firewall rules to remove from the target computer. Use this to control exactly which network access rules are cleaned up when decommissioning or reconfiguring SQL Server instances. Engine 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 database 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @('Engine', 'DAC') | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per firewall rule that was removed from the target computer. Properties: ComputerName: The name of the target computer where the firewall rule was removed InstanceName: The SQL Server instance name associated with the firewall rule SqlInstance: The full SQL Server instance identifier (ComputerName\\InstanceName) DisplayName: The display name of the firewall rule that was removed Type: The type of firewall rule removed (Engine, Browser, DAC, DatabaseMirroring, or AllInstance) IsRemoved: Boolean indicating whether the firewall rule was successfully removed Status: A descriptive status message indicating success or details about any warnings, errors, or exceptions encountered during removal &nbsp;"
  },
  {
    "name": "Remove-DbaInstanceList",
    "description": "Removes SQL Server instance names from the user-maintained list that is pre-loaded into\nthe dbatools tab completion cache for the -SqlInstance parameter. The instances are\nremoved from the stored configuration and from the current session's autocomplete cache.\n\nUse Add-DbaInstanceList to add instances to the list and Get-DbaInstanceList to view\nthe current list.",
    "category": "Server Management",
    "tags": [
      "tabcompletion",
      "autocomplete"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaInstanceList",
    "popularityRank": 0,
    "synopsis": "Removes one or more SQL Server instances from the user-maintained autocomplete list.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaInstanceList View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes one or more SQL Server instances from the user-maintained autocomplete list. Description Removes SQL Server instance names from the user-maintained list that is pre-loaded into the dbatools tab completion cache for the -SqlInstance parameter. The instances are removed from the stored configuration and from the current session's autocomplete cache. Use Add-DbaInstanceList to add instances to the list and Get-DbaInstanceList to view the current list. Syntax Remove-DbaInstanceList [-SqlInstance] [-Register] [[-Scope] {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes sql01 from the autocomplete instance list PS C:\\> Remove-DbaInstanceList -SqlInstance \"sql01\" Example 2: Removes two instances from the list and persists the change across PowerShell sessions PS C:\\> Remove-DbaInstanceList -SqlInstance \"sql01\", \"sql02\\dev\" -Register Example 3: Removes all instances from the user-maintained autocomplete list and persists the change PS C:\\> Get-DbaInstanceList | Remove-DbaInstanceList -Register Required Parameters -SqlInstance The SQL Server instance name or names to remove from the autocomplete list. Accepts pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | Optional Parameters -Register Persists the updated instance list to disk after removal so the change is available in future PowerShell sessions. Without this switch, the removal only affects the stored configuration for the current session. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Scope Determines where the persistent configuration is stored when using -Register. UserDefault stores the setting for the current user only. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UserDefault | -WhatIf | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This command updates the stored configuration but does not output any objects to the pipeline. Use Get-DbaInstanceList to retrieve the current configured instance names. &nbsp;"
  },
  {
    "name": "Remove-DbaLinkedServer",
    "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.",
    "category": "Utilities",
    "tags": [
      "linkedserver",
      "server"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaLinkedServer",
    "popularityRank": 518,
    "synopsis": "Removes linked servers from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaLinkedServer View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes linked servers from SQL Server instances. 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. Syntax Remove-DbaLinkedServer [[-SqlInstance] ] [[-SqlCredential] ] [[-LinkedServer] ] [[-InputObject] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the linked server &quot;linkedServer1&quot; from the sql01 instance PS C:\\> Remove-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 -Confirm:$false Example 2: Removes the linked server &quot;linkedServer1&quot; and the associated linked server logins from the sql01 instance PS C:\\> Remove-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 -Confirm:$false -Force Example 3: Passes in a linked server via pipeline and removes it from the sql01 instance PS C:\\> $linkedServer1 = Get-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 PS C:\\> $linkedServer1 | Remove-DbaLinkedServer -Confirm:$false Example 4: Removes the linked server &quot;linkedServer1&quot; from the sql01 instance, which is passed in via pipeline PS C:\\> Connect-DbaInstance -SqlInstance sql01 | Remove-DbaLinkedServer -LinkedServer linkedServer1 -Confirm:$false Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LinkedServer Specifies the name(s) of the linked server(s) to remove from the SQL Server instance. Use this to target specific linked servers instead of removing all linked servers. Accepts an array of names when you need to remove multiple linked servers in a single operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts linked server objects from Get-DbaLinkedServer or server instances from Connect-DbaInstance via pipeline. Use this when you want to remove linked servers that were previously retrieved with Get-DbaLinkedServer. When passing server instances, you must also specify the LinkedServer parameter to identify which linked servers to remove. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Force Removes all linked server logins associated with the linked server before dropping the linked server itself. Use this when the linked server has associated logins that would prevent removal. Without this parameter, the removal will fail if any linked server logins exist, requiring you to manually remove them first. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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. &nbsp;"
  },
  {
    "name": "Remove-DbaLinkedServerLogin",
    "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.",
    "category": "Utilities",
    "tags": [
      "security",
      "server"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaLinkedServerLogin",
    "popularityRank": 653,
    "synopsis": "Removes linked server login mappings that define credential relationships between local and remote server logins.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaLinkedServerLogin View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes linked server login mappings that define credential relationships between local and remote server logins. 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. Syntax Remove-DbaLinkedServerLogin [[-SqlInstance] ] [[-SqlCredential] ] [[-LinkedServer] ] [[-LocalLogin] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the linkedServerLogin1 from the linkedServer1 linked server on the sql01 instance PS C:\\> Remove-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -LocalLogin linkedServerLogin1 -Confirm:$false Example 2: Passes in a SqlInstance via pipeline and removes the linkedServerLogin1 from the linkedServer1 linked server PS C:\\> $instance = Connect-DbaInstance -SqlInstance sql01 PS C:\\> $instance | Remove-DbaLinkedServerLogin -LinkedServer linkedServer1 -LocalLogin linkedServerLogin1 -Confirm:$false Example 3: Passes in a linked server via pipeline and removes the linkedServerLogin1 PS C:\\> $linkedServer1 = Get-DbaLinkedServer -SqlInstance sql01 -LinkedServer linkedServer1 PS C:\\> $linkedServer1 | Remove-DbaLinkedServerLogin -LocalLogin linkedServerLogin1 -Confirm:$false Example 4: Passes in a linked server login via pipeline and removes it PS C:\\> $linkedServerLogin1 = Get-DbaLinkedServerLogin -SqlInstance sql01 -LinkedServer linkedServer1 -LocalLogin linkedServerLogin1 PS C:\\> $linkedServerLogin1 | Remove-DbaLinkedServerLogin -Confirm:$false Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need to remove login mappings from a specific linked server, such as when cleaning up security configurations or decommissioning user access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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, Get-DbaLinkedServer, and Get-DbaLinkedServerLogin. Use this for pipeline operations when you want to remove login mappings from multiple objects or when chaining commands together for bulk security configuration changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per linked server login processed, whether successfully removed or failed. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name LinkedServer: The name of the linked server containing the removed login Login: The name of the linked server login that was removed Status: Either \"Removed\" on success or \"Failure\" if the operation failed &nbsp;"
  },
  {
    "name": "Remove-DbaLogin",
    "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.",
    "category": "Security",
    "tags": [
      "delete",
      "login"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaLogin",
    "popularityRank": 91,
    "synopsis": "Removes SQL Server logins from target instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaLogin View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes SQL Server logins from target instances 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. Syntax Remove-DbaLogin [-SqlCredential ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaLogin -SqlInstance [-SqlCredential ] -Login [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaLogin [-SqlCredential ] -InputObject [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Prompts then removes the Login mylogin on SQL Server sql2016 PS C:\\> Remove-DbaLogin -SqlInstance sql2016 -Login mylogin Example 2: Prompts then removes the Logins mylogin and yourlogin on SQL Server sql2016 PS C:\\> Remove-DbaLogin -SqlInstance sql2016 -Login mylogin, yourlogin Example 3: Does not prompt and swiftly removes mylogin on SQL Server sql2016 PS C:\\> Remove-DbaLogin -SqlInstance sql2016 -Login mylogin -Confirm:$false Example 4: Removes mylogin on SQL Server server\\instance PS C:\\> Get-DbaLogin -SqlInstance server\\instance -Login yourlogin | Remove-DbaLogin Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Login Specifies the SQL Server login names to remove from the target instance. Accepts multiple login names as an array. Use this when you know the specific logins to delete, such as when cleaning up test accounts or decommissioned user logins. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts login objects piped from Get-DbaLogin or other dbatools functions that return SQL Server login objects. Use this for advanced filtering scenarios or when chaining multiple dbatools commands together in a pipeline. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Allows you to login to servers using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Automatically terminates any active database connections and sessions associated with the login before attempting removal. Use this when you need to forcibly remove logins that have active sessions, common in development environments or during emergency cleanup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per login processed, whether successfully removed or failed. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Login: The name of the login that was removed Status: Either \"Dropped\" on success or an error message describing the failure &nbsp;"
  },
  {
    "name": "Remove-DbaNetworkCertificate",
    "description": "Removes the certificate thumbprint from SQL Server's 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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaNetworkCertificate",
    "popularityRank": 529,
    "synopsis": "Removes the SSL certificate configuration from SQL Server network encryption settings",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaNetworkCertificate View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes the SSL certificate configuration from SQL Server network encryption settings Description Removes the certificate thumbprint from SQL Server's 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. Syntax Remove-DbaNetworkCertificate [[-SqlInstance] ] [[-Credential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the Network Certificate for the default instance (MSSQLSERVER) on localhost PS C:\\> Remove-DbaNetworkCertificate Example 2: Removes the Network Certificate for the SQL2008R2SP2 instance on sql1 PS C:\\> Remove-DbaNetworkCertificate -SqlInstance sql1\\SQL2008R2SP2 Example 3: Shows what would happen if the command were run PS C:\\> Remove-DbaNetworkCertificate -SqlInstance localhost\\SQL2008R2SP2 -WhatIf Optional Parameters -SqlInstance The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must also specify InstanceClusterName (see below) | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Windows credentials for accessing the target computer's registry and WMI services. This is used for computer-level authentication, not SQL Server authentication. Required when the current user lacks administrative privileges on the target server or when running against remote servers in different domains. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance where the network certificate configuration was removed. Properties: ComputerName: The name of the computer where the certificate was removed InstanceName: The SQL Server instance name (extracted from DisplayName) SqlInstance: The full SQL Server instance identifier (VSNAME) ServiceAccount: The service account used by the SQL Server instance RemovedThumbprint: The certificate thumbprint that was removed (or $null if none was configured) &nbsp;"
  },
  {
    "name": "Remove-DbaPfDataCollectorCounter",
    "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.",
    "category": "Utilities",
    "tags": [
      "perfmon"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaPfDataCollectorCounter",
    "popularityRank": 692,
    "synopsis": "Removes specific performance counters from Windows Performance Monitor Data Collector Sets.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaPfDataCollectorCounter View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes specific performance counters from Windows Performance Monitor Data Collector Sets. 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. Syntax Remove-DbaPfDataCollectorCounter [[-ComputerName] ] [[-Credential] ] [[-CollectorSet] ] [[-Collector] ] [-Counter] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Prompts for confirmation then removes the &#39;\\LogicalDisk()\\Avg PS C:\\> Remove-DbaPfDataCollectorCounter -ComputerName sql2017 -CollectorSet 'System Correlation' -Collector DataCollector01 -Counter '\\LogicalDisk()\\Avg. Disk Queue Length' Prompts for confirmation then removes the '\\LogicalDisk(*)\\Avg. Disk Queue Length' counter within the DataCollector01 collector within the System Correlation collector set on sql2017. Example 2: Allows you to select which counters you&#39;d like on localhost and does not prompt for confirmation PS C:\\> Get-DbaPfDataCollectorCounter | Out-GridView -PassThru | Remove-DbaPfDataCollectorCounter -Confirm:$false Required Parameters -Counter Specifies the exact performance counter name(s) to remove from the data collector. Must use the full counter path format like '\\Processor(_Total)\\% Processor Time' or '\\SQLServer:Buffer Manager\\Buffer cache hit ratio'. Use 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 unnecessary resources. | Property | Value | | --- | --- | | Alias | Name | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -ComputerName Specifies the target computer(s) where the Performance Monitor Data Collector Set is configured. Accepts multiple computer names for bulk operations. Use this when you need to remove counters from collector sets on remote SQL Server machines or when managing performance monitoring across multiple servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the target computer using alternative credentials. To use: $cred = Get-Credential, then pass $cred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you know the specific collector set name where your performance counters are configured, such as 'System Correlation' or custom SQL Server monitoring sets. | Property | Value | | --- | --- | | Alias | DataCollectorSet | | Required | False | | Pipeline | false | | Default Value | | -Collector Specifies the name of the individual data collector within the collector set that contains the performance counters to remove. Supports multiple collector names. Use this to target specific data collectors when your collector set contains multiple collectors, allowing you to remove counters from only the collectors you specify. | Property | Value | | --- | --- | | Alias | DataCollector | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts performance counter objects from Get-DbaPfDataCollectorCounter via the pipeline, allowing you to remove counters discovered through previous queries. Use this when you want to first review existing counters with Get-DbaPfDataCollectorCounter and then selectively remove specific ones through pipeline operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per counter successfully removed from the Data Collector Set. Properties: ComputerName: The name of the computer where the performance counter was removed DataCollectorSet: The name of the Data Collector Set containing the collector DataCollector: The name of the specific data collector within the Collector Set where the counter was removed Name: The performance counter path that was removed Status: The operation status (always \"Removed\" on success) &nbsp;"
  },
  {
    "name": "Remove-DbaPfDataCollectorSet",
    "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.",
    "category": "Utilities",
    "tags": [
      "perfmon"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaPfDataCollectorSet",
    "popularityRank": 687,
    "synopsis": "Removes Windows Performance Monitor Data Collector Sets from local or remote computers",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaPfDataCollectorSet View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes Windows Performance Monitor Data Collector Sets from local or remote computers 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. Syntax Remove-DbaPfDataCollectorSet [[-ComputerName] ] [[-Credential] ] [[-CollectorSet] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Prompts for confirmation then removes all ready Collectors on localhost PS C:\\> Remove-DbaPfDataCollectorSet Example 2: Attempts to remove all ready Collectors on localhost and does not prompt to confirm PS C:\\> Remove-DbaPfDataCollectorSet -ComputerName sql2017 -Confirm:$false Example 3: Prompts for confirmation then removes the &#39;System Correlation&#39; Collector on sql2017 and sql2016 using... PS C:\\> Remove-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet 'System Correlation' Prompts for confirmation then removes the 'System Correlation' Collector on sql2017 and sql2016 using alternative credentials. Example 4: Removes the &#39;System Correlation&#39; Collector PS C:\\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Remove-DbaPfDataCollectorSet Example 5: Stops and removes the &#39;System Correlation&#39; Collector PS C:\\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Stop-DbaPfDataCollectorSet | Remove-DbaPfDataCollectorSet Optional Parameters -ComputerName Specifies the target computer(s) where Performance Monitor Data Collector Sets will be removed. Supports multiple computers for bulk operations. Use this when removing collector sets from remote SQL Server hosts or when standardizing monitoring configurations across multiple servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the target computer using alternative credentials. To use: $cred = Get-Credential, then pass $cred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CollectorSet Specifies the exact name(s) of the Performance Monitor Data Collector Sets to remove. Accepts multiple collector set names for batch operations. Use this when you need to remove specific monitoring configurations rather than all available collector sets on the target computer. | Property | Value | | --- | --- | | Alias | DataCollectorSet | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Data Collector Set objects from Get-DbaPfDataCollectorSet for pipeline operations. Enables chaining commands together for workflow automation. Use this when you need to filter collector sets with Get-DbaPfDataCollectorSet first, then remove only the matching results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per Performance Monitor Data Collector Set removed. Properties: ComputerName: The name of the computer from which the collector set was removed Name: The name of the Data Collector Set that was removed Status: The operation status (Removed) &nbsp;"
  },
  {
    "name": "Remove-DbaRegServer",
    "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.",
    "category": "Utilities",
    "tags": [
      "registeredserver",
      "cms"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaRegServer",
    "popularityRank": 457,
    "synopsis": "Removes registered servers from SQL Server Central Management Server or local registered server groups.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaRegServer View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes registered servers from SQL Server Central Management Server or local registered server groups. 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. You 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. Syntax Remove-DbaRegServer [[-SqlInstance] ] [[-SqlCredential] ] [[-Name] ] [[-ServerName] ] [[-Group] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all servers from the HR and Accounting groups on sql2012 PS C:\\> Remove-DbaRegServer -SqlInstance sql2012 -Group HR, Accounting Example 2: Removes all servers from the HR and sub-group Development from the CMS on sql2012 PS C:\\> Remove-DbaRegServer -SqlInstance sql2012 -Group HR\\Development Example 3: Removes all registered servers on sql2012 and turns off all prompting PS C:\\> Remove-DbaRegServer -SqlInstance sql2012 -Confirm:$false Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies registered server display names to remove from CMS or local registered servers. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ServerName Specifies actual SQL Server instance names to remove from registered servers. Use 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 different friendly names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Group Removes all registered servers from specified Central Management Server groups. Supports hierarchical paths using backslash notation (e.g., \"Production\\Database Servers\"). Use this when you need to clean out entire groups during environment changes, server migrations, or organizational restructuring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts registered server objects from Get-DbaRegServer for targeted removal operations. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per registered server removed from CMS or local registered server groups. Default display properties vary based on server type: For Central Management Server registered servers (with ID): ComputerName: The name of the computer hosting the CMS instance InstanceName: The SQL Server instance name of the CMS SqlInstance: The full SQL Server instance name in format ComputerName\\InstanceName Name: The display name of the registered server as shown in SSMS ServerName: The actual SQL Server instance name or connection string Status: The operation status (Dropped) For local registered server groups (without ID): Name: The display name of the registered server ServerName: The actual SQL Server instance name or connection string Status: The operation status (Dropped) &nbsp;"
  },
  {
    "name": "Remove-DbaRegServerGroup",
    "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've 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.",
    "category": "Utilities",
    "tags": [
      "registeredserver",
      "cms"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaRegServerGroup",
    "popularityRank": 624,
    "synopsis": "Removes server groups from SQL Server Central Management Server (CMS).",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaRegServerGroup View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes server groups from SQL Server Central Management Server (CMS). 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've 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. Syntax Remove-DbaRegServerGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-Name] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the HR and Accounting groups on sql2012 PS C:\\> Remove-DbaRegServerGroup -SqlInstance sql2012 -Group HR, Accounting Example 2: Removes the Development subgroup within the HR group on sql2012 and turns off all prompting PS C:\\> Remove-DbaRegServerGroup -SqlInstance sql2012 -Group HR\\Development -Confirm:$false Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 parent groups. Use 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. | Property | Value | | --- | --- | | Alias | Group | | Required | False | | Pipeline | false | | Default Value | | -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. Use this approach when you need to perform complex filtering, review groups before deletion, or process large numbers of groups with conditional logic. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per server group removed. For server groups on Central Management Server (CMS), default display properties are: ComputerName: The computer name of the CMS instance InstanceName: The instance name of the CMS SqlInstance: The full instance name of the CMS (computer\\instance) Name: The name of the server group that was removed Status: \"Dropped\" if successful For local registered server groups, default display properties are: Name: The name of the server group that was removed Status: \"Dropped\" if successful Note: The PSCustomObject includes all properties listed above regardless of display mode. Use Select-Object * to see all properties when needed. &nbsp;"
  },
  {
    "name": "Remove-DbaReplArticle",
    "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 <Object> 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.",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaReplArticle",
    "popularityRank": 684,
    "synopsis": "Removes articles from SQL Server replication publications and their associated subscriptions.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaReplArticle View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes articles from SQL Server replication publications and their associated subscriptions. 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. When 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. Important 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 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. Syntax Remove-DbaReplArticle [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Publication] ] [[-Schema] ] [[-Name] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes the publishers article from a publication called PubFromPosh on mssql1 PS C:\\> Remove-DbaReplArticle -SqlInstance mssql1 -Database Pubs -Publication PubFromPosh -Name 'publishers' Example 2: Removes all articles from a publication called TestPub on mssql1 PS C:\\> Get-DbaReplArticle -SqlInstance mssql1 -Database Pubs -Publication TestPub | Remove-DbaReplArticle Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the publication database on the publisher that contains the article to remove from replication. This is the database where the source objects (tables, views, stored procedures) exist and are published for replication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Publication Specifies the name of the replication publication from which to remove the article. Use Get-DbaReplPublication to list available publications if you're unsure of the exact name. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Specifies the schema name of the replicated object to remove from the publication. Defaults to 'dbo'. Required when multiple schemas contain objects with the same name, ensuring you remove the correct article. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | dbo | -Name Specifies the name of the article to remove from the publication. This corresponds to the source object name (table, view, or stored procedure) that was added to replication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts replication article objects from Get-DbaReplArticle for pipeline operations. Use this to remove multiple articles efficiently: Get-DbaReplArticle | Remove-DbaReplArticle. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per article removed from the replication publication. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The publication database name ObjectName: The name of the replicated object (table, view, or stored procedure) ObjectSchema: The schema that owns the replicated object Status: \"Removed\" on successful removal, or an error message if the operation failed IsRemoved: Boolean indicating whether the article was successfully removed (true) or failed (false) &nbsp;"
  },
  {
    "name": "Remove-DbaReplPublication",
    "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",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaReplPublication",
    "popularityRank": 644,
    "synopsis": "Removes a publication from the database on the target SQL instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaReplPublication View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes a publication from the database on the target SQL instances. Description Removes a publication from the database on the target SQL instances. https://learn.microsoft.com/en-us/sql/relational-databases/replication/publish/delete-a-publication?view=sql-server-ver16#RMOProcedure Syntax Remove-DbaReplPublication [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Name] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes a publication called PubFromPosh from the Northwind database on mssql1 PS C:\\> Remove-DbaReplPublication -SqlInstance mssql1 -Database Northwind -Name PubFromPosh Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database containing the replication publication to remove. Required when using SqlInstance to identify which database's publications to target. Use this to scope the operation to a specific database when multiple databases have replication configured. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Specifies the exact name of the replication publication to remove. Required when using SqlInstance to identify which specific publication to target. Use this when you know the publication name and want to remove a specific publication rather than all publications in a database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts replication publication objects from Get-DbaReplPublication for pipeline operations. Use this when you want to filter publications first, then remove selected ones. Particularly useful when removing multiple publications based on specific criteria or when integrating with other replication management workflows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per publication removed, containing details about the removal operation. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name containing the publication Name: The publication name that was removed Type: The publication type (Transactional, Snapshot, or Merge) Status: The result of the removal operation (\"Removed\" on success, or error message on failure) IsRemoved: Boolean indicating whether the publication was successfully removed (True if successful, False if failed or not found) &nbsp;"
  },
  {
    "name": "Remove-DbaReplSubscription",
    "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",
    "category": "Utilities",
    "tags": [
      "repl",
      "replication"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaReplSubscription",
    "popularityRank": 626,
    "synopsis": "Removes a subscription for the target SQL instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaReplSubscription View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes a subscription for the target SQL instances. Description Removes a subscription for the target SQL instances. https://learn.microsoft.com/en-us/sql/relational-databases/replication/delete-a-push-subscription?view=sql-server-ver16 https://learn.microsoft.com/en-us/sql/relational-databases/replication/delete-a-pull-subscription?view=sql-server-ver16 Syntax Remove-DbaReplSubscription [-SqlInstance] [[-SqlCredential] ] [-Database] [-PublicationName] [-SubscriberSqlInstance] [[-SubscriberSqlCredential] ] [-SubscriptionDatabase] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes a subscription for the testPub publication on mssql2.pubs PS C:\\> $sub = @{ >> SqlInstance = 'mssql1' >> Database = 'pubs' >> PublicationName = 'testPub' >> SubscriberSqlInstance = 'mssql2' >> SubscriptionDatabase = 'pubs' >> } PS C:\\> Remove-DbaReplSubscription @sub Required Parameters -SqlInstance The target publisher SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Database Specifies the publisher database that contains the replication publication. This is the source database where the published data originates from. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -PublicationName Specifies the exact name of the replication publication to remove the subscription from. Must match an existing publication name on the publisher database. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -SubscriberSqlInstance Specifies the SQL Server instance that receives replicated data from the publisher. Use this to identify which subscriber instance should have its subscription removed. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -SubscriptionDatabase Specifies the database on the subscriber instance that receives the replicated data. This is the target database where the subscription will be removed from. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target publisher instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SubscriberSqlCredential Login to the subscriber instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Required when the subscriber instance uses different authentication than the publisher. Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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. &nbsp;"
  },
  {
    "name": "Remove-DbaRgResourcePool",
    "description": "Removes user-defined resource pools from SQL Server's 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.",
    "category": "Utilities",
    "tags": [
      "resourcepool",
      "resourcegovernor"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaRgResourcePool",
    "popularityRank": 700,
    "synopsis": "Removes internal or external resource pools from SQL Server Resource Governor configuration",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaRgResourcePool View Source John McCall (@lowlydba), lowlydba.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes internal or external resource pools from SQL Server Resource Governor configuration Description Removes user-defined resource pools from SQL Server's 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. Resource 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. The function automatically reconfigures Resource Governor after pool removal to ensure changes take effect immediately, unless you specify -SkipReconfigure for batch operations. Syntax Remove-DbaRgResourcePool [[-SqlInstance] ] [[-SqlCredential] ] [[-ResourcePool] ] [[-Type] ] [-SkipReconfigure] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes an internal resource pool named &quot;poolAdmin&quot; for the instance sql2016 PS C:\\> Remove-DbaRgResourcePool -SqlInstance sql2016 -ResourcePool \"poolAdmin\" -Type Internal Example 2: Removes all user internal resource pools for the instance sql2016 by piping output from Get-DbaRgResourcePool PS C:\\> Get-DbaRgResourcePool -SqlInstance sql2016 -Type \"Internal\" | Where-Object { $_.IsSystemObject -eq $false } | Remove-DbaRgResourcePool Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | -SqlCredential Credential object used to connect to the Windows server as a different user | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -ResourcePool Name of the resource pool to remove from Resource Governor configuration. Accepts multiple pool names. Use this when you need to clean up specific unused pools or consolidate resource management by removing obsolete pools. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies whether to remove Internal or External resource pools. Defaults to Internal. Internal pools manage CPU and memory for regular SQL Server workloads, while External pools manage resources for R/Python/Java external scripts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Internal | | Accepted Values | Internal,External | -SkipReconfigure Skips the automatic Resource Governor reconfiguration after removing resource pools. By default, Resource Governor is reconfigured to apply changes immediately. Use this when removing multiple pools in batch operations to avoid repeated reconfigurations, then manually reconfigure once at the end. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts resource pool objects piped from Get-DbaRgResourcePool for removal. Supports both Internal and External resource pool objects. Use this for pipeline operations when you need to filter pools before removal or process multiple pools efficiently. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This command does not return any output objects. It only performs removal and reconfiguration operations on the Resource Governor. &nbsp;"
  },
  {
    "name": "Remove-DbaRgWorkloadGroup",
    "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.",
    "category": "Utilities",
    "tags": [
      "workloadgroup",
      "resourcegovernor"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaRgWorkloadGroup",
    "popularityRank": 698,
    "synopsis": "Removes workload groups from SQL Server Resource Governor",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaRgWorkloadGroup View Source John McCall (@lowlydba), lowlydba.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes workload groups from SQL Server Resource Governor Description Removes specified workload groups from SQL Server Resource Governor and automatically reconfigures the Resource Governor so changes take effect immediately. Workload groups define resource allocation policies for incoming requests, and removing them eliminates those resource controls. Useful for cleaning up test environments, removing deprecated resource policies, or simplifying Resource Governor configurations during performance tuning. Works with both internal and external resource pools, and can process multiple workload groups through pipeline input from Get-DbaRgWorkloadGroup. Syntax Remove-DbaRgWorkloadGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-WorkloadGroup] ] [[-ResourcePool] ] [[-ResourcePoolType] ] [-SkipReconfigure] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes a workload group named &quot;groupAdmin&quot; in the &quot;poolAdmin&quot; resource pool for the instance sql2016 PS C:\\> Remove-DbaRgResourcePool -SqlInstance sql2016 -WorkloadGroup \"groupAdmin\" -ResourcePool \"poolAdmin\" -ResourcePoolType Internal Example 2: Removes a workload group named &quot;groupAdmin&quot; in the default resource pool for the instance sql2016 PS C:\\> Remove-DbaRgResourcePool -SqlInstance sql2016 -WorkloadGroup \"groupAdmin\" Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | -SqlCredential Credential object used to connect to the Windows server as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -WorkloadGroup Specifies the name of the workload group(s) to remove from Resource Governor. Use this when you need to eliminate specific resource allocation policies or clean up deprecated workload configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ResourcePool Specifies the resource pool containing the workload group to be removed. Defaults to \"default\" pool. Required when workload groups exist in custom resource pools rather than the default SQL Server resource pool. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | default | -ResourcePoolType Specifies whether to target Internal or External resource pools. Defaults to \"Internal\". Use \"External\" when removing workload groups that manage external script execution resources like R or Python jobs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Internal | | Accepted Values | Internal,External | -SkipReconfigure Skips the automatic Resource Governor reconfiguration that makes workload group changes take effect immediately. Use this when removing multiple workload groups in sequence to avoid repeated reconfigurations, but remember to manually reconfigure afterwards. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts workload group objects piped from Get-DbaRgWorkloadGroup for removal. Use this approach when you need to filter workload groups first or when processing multiple groups across different resource pools. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per workload group removed, containing the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (service name) SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the workload group that was removed Status: Status of the removal operation (\"Dropped\" on success, or error message on failure) IsRemoved: Boolean indicating whether the workload group was successfully removed ($true or $false) &nbsp;"
  },
  {
    "name": "Remove-DbaServerRole",
    "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.",
    "category": "Security",
    "tags": [
      "role",
      "login"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaServerRole",
    "popularityRank": 613,
    "synopsis": "Removes custom server-level roles from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaServerRole View Source Claudio Silva (@ClaudioESSilva), claudioessilva.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes custom server-level roles from SQL Server instances. 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. Syntax Remove-DbaServerRole [[-SqlInstance] ] [[-SqlCredential] ] [[-ServerRole] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Server-role &#39;serverExecuter&#39; on Server1 will be removed if it exists PS C:\\> Remove-DbaServerRole -SqlInstance Server1 -ServerRole 'serverExecuter' Example 2: Suppresses all prompts to remove the server-role &#39;serverExecuter&#39; on &#39;Server1&#39; PS C:\\> Remove-DbaServerRole -SqlInstance Server1 -ServerRole 'serverExecuter' -Confirm:$false Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ServerRole Specifies the name of the custom server-level role to remove from the SQL Server instance. Only user-defined server roles can be removed - built-in roles like sysadmin or serveradmin are protected. Use this when you need to clean up obsolete custom roles after application decommissioning or security reviews. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts server role objects from Get-DbaServerRole for pipeline operations. Use this when you need to remove multiple roles or want to filter roles before removal. Allows for more complex scenarios like removing all custom roles that match specific criteria. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per server role removed, with the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ServerRole: The name of the server role that was dropped Status: The result of the removal operation (\"Success\" or \"Failed\") &nbsp;"
  },
  {
    "name": "Remove-DbaServerRoleMember",
    "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.",
    "category": "Security",
    "tags": [
      "role",
      "login"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaServerRoleMember",
    "popularityRank": 512,
    "synopsis": "Revokes server-level role membership from SQL Server logins and roles.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaServerRoleMember View Source Mikey Bronowski (@MikeyBronowski), bronowski.it Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Revokes server-level role membership from SQL Server logins and roles. 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. Syntax Remove-DbaServerRoleMember [[-SqlInstance] ] [[-SqlCredential] ] [[-ServerRole] ] [[-Login] ] [[-Role] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes login1 from the dbcreator fixed server-level role on the instance server1 PS C:\\> Remove-DbaServerRoleMember -SqlInstance server1 -ServerRole dbcreator -Login login1 Example 2: Removes login1 from customrole custom server-level role on the instance server1 and sql2016 PS C:\\> Remove-DbaServerRoleMember -SqlInstance server1, sql2016 -ServerRole customrole -Login login1 Example 3: Removes customrole custom server-level role from the dbcreator fixed server-level role PS C:\\> Remove-DbaServerRoleMember -SqlInstance server1 -ServerRole customrole -Role dbcreator Example 4: Removes login1 from the sysadmin fixed server-level role in every server in C:\\servers.txt PS C:\\> $servers = Get-Content C:\\servers.txt PS C:\\> $servers | Remove-DbaServerRoleMember -ServerRole sysadmin -Login login1 Example 5: Removes login1 from the bulkadmin and dbcreator fixed server-level roles on the server localhost PS C:\\> Remove-DbaServerRoleMember -SqlInstance localhost -ServerRole bulkadmin, dbcreator -Login login1 Example 6: Removes login1 from the bulkadmin and dbcreator fixed server-level roles on the server localhost PS C:\\> $roles = Get-DbaServerRole -SqlInstance localhost -ServerRole bulkadmin, dbcreator PS C:\\> $roles | Remove-DbaServerRoleMember -Login login1 Example 7: PS C:\\ $srvLogins = Get-DbaLogin -SqlInstance server1 -Login $logins PS C:\\ Remove-DbaServerRoleMember -Login... PS C:\\> PS C:\\ $logins = Get-Content C:\\logins.txt PS C:\\ $srvLogins = Get-DbaLogin -SqlInstance server1 -Login $logins PS C:\\ Remove-DbaServerRoleMember -Login $logins -ServerRole mycustomrole Removes all the logins found in C:\\logins.txt from mycustomrole custom server-level role on server1. Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need to revoke specific permissions by removing logins or nested roles from elevated privilege roles. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Specifies the login name(s) to remove from the target server role(s). Accepts SQL Server logins, Windows logins, and Active Directory accounts. Use this when removing user access after role changes, departures, or security reviews where individual logins need privilege reduction. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Role Specifies the server role name(s) to remove from the target server role(s), enabling nested role management. Use this when restructuring role hierarchies or removing inherited permissions where one server role should no longer be a member of another. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts piped server role objects from Get-DbaServerRole, allowing you to chain role discovery with member removal operations. Use this pattern when you need to filter roles first then remove specific members from the filtered results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This command does not produce any output. It performs role membership modifications via SMO methods ($ServerRole.DropMember() and $ServerRole.DropMembershipFromRole()) without returning objects to the pipeline. &nbsp;"
  },
  {
    "name": "Remove-DbaSpn",
    "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.",
    "category": "Server Management",
    "tags": [
      "spn"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaSpn",
    "popularityRank": 413,
    "synopsis": "Removes Service Principal Names from Active Directory service accounts and cleans up related Kerberos delegation",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Remove-DbaSpn View Source Drew Furgiuele (@pittfurg), port1433.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes Service Principal Names from Active Directory service accounts and cleans up related Kerberos delegation 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. Requires write access to Active Directory through the provided credentials. Syntax Remove-DbaSpn [-SPN] [-ServiceAccount] [[-Credential] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Connects to Active Directory and removes a provided SPN from the given account (and also the relative... PS C:\\> Remove-DbaSpn -SPN MSSQLSvc\\SQLSERVERA.domain.something -ServiceAccount domain\\account Connects to Active Directory and removes a provided SPN from the given account (and also the relative delegation) Example 2: Connects to Active Directory and removes a provided SPN from the given account, suppressing all error... PS C:\\> Remove-DbaSpn -SPN MSSQLSvc\\SQLSERVERA.domain.something -ServiceAccount domain\\account -EnableException Connects to Active Directory and removes a provided SPN from the given account, suppressing all error messages and throw exceptions that can be caught instead Example 3: Connects to Active Directory and removes a provided SPN to the given account PS C:\\> Remove-DbaSpn -SPN MSSQLSvc\\SQLSERVERA.domain.something -ServiceAccount domain\\account -Credential ad\\sqldba Connects to Active Directory and removes a provided SPN to the given account. Uses alternative account to connect to AD. Example 4: Shows what would happen trying to remove all set SPNs for sql2005 and the relative delegations PS C:\\> Test-DbaSpn -ComputerName sql2005 | Where-Object { $_.isSet -eq $true } | Remove-DbaSpn -WhatIf Example 5: Removes all set SPNs for sql2005 and the relative delegations PS C:\\> Test-DbaSpn -ComputerName sql2005 | Where-Object { $_.isSet -eq $true } | Remove-DbaSpn Required Parameters -SPN Specifies the exact Service Principal Name to remove from Active Directory. Must include the full SPN format like 'MSSQLSvc/servername:port' or 'MSSQLSvc/servername.domain.com'. Use this when decommissioning SQL instances, changing service accounts, or cleaning up duplicate SPNs that cause Kerberos authentication failures. | Property | Value | | --- | --- | | Alias | RequiredSPN | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | -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. This should match the account currently running the SQL Server service that you're decommissioning or reconfiguring. | Property | Value | | --- | --- | | Alias | InstanceServiceAccount,AccountName | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -Credential The credential you want to use to connect to Active Directory to make the changes | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command was executed | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Turns confirmations before changes on or off | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one or two objects per SPN removal operation, depending on what was removed: First object indicates the SPN removal result: Name: The Service Principal Name that was processed ServiceAccount: The Active Directory account from which the SPN was removed Property: Always \"servicePrincipalName\" for the first object IsSet: Boolean indicating whether the SPN is still set (true if removal failed, false if successful or not found) Notes: Status message such as \"Successfully removed SPN\", \"SPN not found\", or \"Failed to remove SPN\" Second object (if SPN removal succeeded) indicates the delegation cleanup result: Name: The Service Principal Name that was processed ServiceAccount: The Active Directory account from which delegation was removed Property: Always \"msDS-AllowedToDelegateTo\" for the second object IsSet: Boolean indicating whether the delegation entry is still set (true if removal failed, false if successful or not found) Notes: Status message such as \"Successfully removed delegation\", \"Delegation not found\", or \"Failed to remove delegation\" &nbsp;"
  },
  {
    "name": "Remove-DbaTrace",
    "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.",
    "category": "Performance",
    "tags": [
      "trace"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaTrace",
    "popularityRank": 677,
    "synopsis": "Stops and removes SQL Server traces by ID or piped input from Get-DbaTrace.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaTrace View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Stops and removes SQL Server traces by ID or piped input from Get-DbaTrace. 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. Syntax Remove-DbaTrace [[-SqlInstance] ] [[-SqlCredential] ] [[-Id] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Stops and removes all traces on sql2008 PS C:\\> Remove-DbaTrace -SqlInstance sql2008 Example 2: Stops and removes all trace with ID 1 on sql2008 PS C:\\> Remove-DbaTrace -SqlInstance sql2008 -Id 1 Example 3: Stops and removes selected traces on sql2008 PS C:\\> Get-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Remove-DbaTrace Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Id Specifies the trace IDs to stop and remove from the SQL Server instance. Accepts one or more integer values. Use this when you know the specific trace IDs you want to remove, which you can obtain from Get-DbaTrace or SQL Server Profiler. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts trace objects from Get-DbaTrace via the pipeline for removal operations. This enables filtering traces with Get-DbaTrace before removing specific ones, such as removing only traces with certain characteristics. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per trace that was successfully removed. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: The trace ID that was removed (integer) Status: Status message indicating \"Stopped, closed and deleted\" &nbsp;"
  },
  {
    "name": "Remove-DbaXESession",
    "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's built-in diagnostics. Useful for removing outdated monitoring configurations or cleaning up test sessions that are no longer needed.",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Remove",
    "popular": false,
    "url": "/Remove-DbaXESession",
    "popularityRank": 661,
    "synopsis": "Removes Extended Events sessions from SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Remove-DbaXESession View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes Extended Events sessions from SQL Server instances. 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's built-in diagnostics. Useful for removing outdated monitoring configurations or cleaning up test sessions that are no longer needed. Syntax Remove-DbaXESession [-SqlInstance] [-SqlCredential ] -Session [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaXESession [-SqlInstance] [-SqlCredential ] -AllSessions [-EnableException] [-WhatIf] [-Confirm] [ ] Remove-DbaXESession -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes all Extended Event Session on the sqlserver2014 instance PS C:\\> Remove-DbaXESession -SqlInstance sql2012 -AllSessions Example 2: Removes the xesession1 and xesession2 Extended Event sessions PS C:\\> Remove-DbaXESession -SqlInstance sql2012 -Session xesession1,xesession2 Example 3: Removes all sessions from sql2017, bypassing prompts PS C:\\> Get-DbaXESession -SqlInstance sql2017 | Remove-DbaXESession -Confirm:$false Example 4: Removes the sessions returned from the Get-DbaXESession function PS C:\\> Get-DbaXESession -SqlInstance sql2012 -Session xesession1 | Remove-DbaXESession Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Session Specifies one or more Extended Events session names to remove from the target instance. Use this when you want to selectively remove specific monitoring sessions rather than all user sessions. Accepts session names as strings, with support for arrays to remove multiple sessions in one command. | Property | Value | | --- | --- | | Alias | Name,Sessions | | Required | True | | Pipeline | false | | Default Value | | -AllSessions Removes all user-created Extended Events sessions while preserving critical system sessions. Use this for cleanup operations when you want to clear all monitoring sessions without breaking SQL Server's built-in diagnostics. Automatically excludes system_health, telemetry_xevents, and AlwaysOn_health sessions to maintain server functionality. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | False | -InputObject Accepts Extended Events session objects directly from Get-DbaXESession for pipeline operations. Use this when you need to filter sessions with Get-DbaXESession first, then remove the filtered results. Enables complex filtering scenarios and integration with other dbatools XE functions. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per Extended Events session removed. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Session: The name of the Extended Events session that was removed Status: String value \"Removed\" indicating the session was successfully dropped No output is generated for sessions that fail to be removed due to errors. &nbsp;"
  },
  {
    "name": "Rename-DbaDatabase",
    "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's 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 <DBN> for database name, <FGN> for filegroup name, <DATE> for current date, and <FT> 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 *\"",
    "category": "Database Operations",
    "tags": [
      "database",
      "rename"
    ],
    "verb": "Rename",
    "popular": false,
    "url": "/Rename-DbaDatabase",
    "popularityRank": 141,
    "synopsis": "Renames database names, filegroups, logical files, and physical files using customizable templates with placeholder support.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Rename-DbaDatabase View Source Simone Bizzotto (@niphold) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Renames database names, filegroups, logical files, and physical files using customizable templates with placeholder support. Description Systematically renames all database components using template-based naming conventions to enforce consistent standards across your SQL Server environment. This function addresses the common challenge of standardizing database naming when inheriting inconsistent systems or implementing new naming policies. The renaming process follows SQL Server's object hierarchy and executes in this order: Database name is changed (optionally forcing users out) Filegroup names are changed accordingly Logical file names are changed accordingly Physical file names are changed accordingly If Move is specified, the database goes offline for file operations, then back online If Move is not specified, the database remains online (unless SetOffline), and you handle file moves manually The function uses powerful template placeholders like for database name, for filegroup name, for current date, and for file type. When naming conflicts occur, automatic counters are appended to ensure uniqueness. If any step fails, the entire process stops to prevent partial renames that could leave your database in an inconsistent state. Always backup your databases before using this function, and take a full backup of master after completion. The function returns detailed objects showing all completed renames, with hidden properties providing human-readable summaries. Store results in a variable for troubleshooting: \"$result = Rename-DbaDatabase .....\" Use the -Preview parameter first to see exactly what changes would occur: \"Rename-DbaDatabase .... -Preview | Select-Object \" Syntax Rename-DbaDatabase -SqlInstance [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-AllDatabases] [-DatabaseName ] [-FileGroupName ] [-LogicalName ] [-FileName ] [-ReplaceBefore] [-Force] [-Move] [-SetOffline] [-Preview] [-EnableException] [-WhatIf] [-Confirm] [ ] Rename-DbaDatabase [-SqlCredential ] [-ExcludeDatabase ] [-AllDatabases] [-DatabaseName ] [-FileGroupName ] [-LogicalName ] [-FileName ] [-ReplaceBefore] [-Force] [-Move] [-SetOffline] [-Preview] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Shows the detailed result set you&#39;ll get renaming the HR database to HR2 without doing anything PS C:\\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName HR2 -Preview | Select-Object Example 2: Renames the HR database to HR2 PS C:\\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName HR2 Example 3: Same as before, but with a piped database (renames the HR database to HR2) PS C:\\> Get-DbaDatabase -SqlInstance sqlserver2014a -Database HR | Rename-DbaDatabase -DatabaseName HR2 Example 4: Renames the HR database to dbatools_HR PS C:\\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_ \" Example 5: Renames the HR database to dbatools_HR_20170807 (if today is 07th Aug 2017) PS C:\\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_ _ \" Example 6: Renames every FileGroup within HR to &quot;dbatools_[the original FileGroup name]&quot; PS C:\\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -FileGroupName \"dbatools_ \" Example 7: Renames the HR database to &quot;dbatools_HR&quot;, then renames every FileGroup within to &quot;dbatools_HR_[the original... PS C:\\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_ \" -FileGroupName \" _ \" Renames the HR database to \"dbatools_HR\", then renames every FileGroup within to \"dbatools_HR_[the original FileGroup name]\" Example 8: Renames the HR database to &quot;dbatools_HR&quot;, then renames every FileGroup within to &quot;dbatools_HR_[the original... PS C:\\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -FileGroupName \"dbatools_ _ \" PS C:\\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_ \" Renames the HR database to \"dbatools_HR\", then renames every FileGroup within to \"dbatools_HR_[the original FileGroup name]\" Example 9: Renames the HR database to &quot;dbatools_HR&quot; and then all filenames as &quot;dbatools_HR_[Name of the... PS C:\\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_ \" -FileName \" _ _ \" Renames the HR database to \"dbatools_HR\" and then all filenames as \"dbatools_HR_[Name of the FileGroup]_[original_filename]\" The 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 Example 10: Renames the HR database to &quot;dbatools_HR&quot; and then all filenames as &quot;dbatools_HR_[Name of the... PS C:\\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_ \" -FileName \" _ _ \" -SetOffline Renames the HR database to \"dbatools_HR\" and then all filenames as \"dbatools_HR_[Name of the FileGroup]_[original_filename]\" The 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 Example 11: Renames the HR database to &quot;dbatools_HR&quot; and then all filenames as &quot;dbatools_HR_[Name of the... PS C:\\> Rename-DbaDatabase -SqlInstance sqlserver2014a -Database HR -DatabaseName \"dbatools_ \" -FileName \" _ _ \" -Move Renames the HR database to \"dbatools_HR\" and then all filenames as \"dbatools_HR_[Name of the FileGroup]_[original_filename]\" The 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 Required Parameters -SqlInstance Target any number of instances, in order to return their build state. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from the pipeline, typically from Get-DbaDatabase. Allows for advanced filtering and database selection before renaming. Use this when you need complex database selection logic or when chaining database operations in a pipeline. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to include in the renaming operation. Accepts database names, wildcards, or arrays of database names. Use this when you need to rename specific databases instead of all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to exclude from the renaming operation. Accepts database names, wildcards, or arrays of database names. Use this to protect specific databases when using -AllDatabases or when you want to process most databases except certain ones. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllDatabases Applies the renaming operation to all user databases on the SQL Server instance. System databases are automatically excluded. Use this switch when standardizing naming conventions across your entire instance rather than targeting specific databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DatabaseName Specifies a template for renaming database names using placeholder substitution. Creates new database names based on the template pattern. Use this when you need to standardize database names according to organizational naming conventions. Common patterns include adding prefixes, suffixes, or date stamps. Valid placeholders are: (current database name), (current date in yyyyMMdd format). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need consistent filegroup naming across databases or when implementing data organization strategies that require specific filegroup names. Valid placeholders are: (current filegroup name), (current database name), (current date in yyyyMMdd format). If distinct names cannot be generated, a counter is appended (0001, 0002, etc). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need consistent logical file naming for backup operations, maintenance scripts, or troubleshooting, as logical names are referenced in many SQL commands. Valid placeholders are: (file type: ROWS, LOG, MMO, FS), (current logical name), (current filegroup name), (current database name), (current date in yyyyMMdd format). If distinct names cannot be generated, a counter is appended (0001, 0002, etc). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when you need to align physical file names with your database naming standards for easier file management, monitoring, and disaster recovery operations. Valid placeholders are: (current file name without directory or extension), (file type: ROWS, LOG, MMO, FS), (current logical name), (current filegroup name), (current database name), (current date in yyyyMMdd format). If distinct names cannot be generated, a counter is appended (0001, 0002, etc). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 scenarios. Use this when your existing names already contain components that would be duplicated by the template placeholders, resulting in cleaner final names. For example, with -ReplaceBefore, renaming database \"HR_DB\" to \"PROD_HR\" and using template \" _Data\" results in \"PROD_HR_Data\" instead of \"PROD_HR_HR_DB_Data\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when you need to force database renames in production environments where applications may maintain persistent connections. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use 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's file system. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SetOffline Forces the database offline after renaming operations to prepare for manual file moves. Terminates active connections and sets database state to offline. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this first to verify your templates and parameters will produce the desired results before committing to actual database changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database processed, containing detailed information about all renames performed. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance where the database resides InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The Microsoft.SqlServer.Management.Smo.Database object representing the database DBN: Hashtable containing database name renames (original name as key, new name as value) FGN: Hashtable containing filegroup name renames (original name as key, new name as value) LGN: Hashtable containing logical file name renames (original name as key, new name as value) FNN: Hashtable containing physical file name renames (original path as key, new path as value) PendingRenames: ArrayList of PSCustomObject items with Source and Destination properties for files that need to be moved on disk (empty if no file renames) Status: String indicating completion status - \"FULL\" for complete success, \"PARTIAL\" if some operations were skipped or failed *Hidden display properties (accessible with Select-Object ):** DatabaseRenames: String with newline-separated list showing database rename transformations (e.g., \"OldDB --> NewDB\") FileGroupsRenames: String with newline-separated list showing filegroup rename transformations LogicalNameRenames: String with newline-separated list showing logical file name transformations FileNameRenames: String with newline-separated list showing physical file path transformations All 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. &nbsp;"
  },
  {
    "name": "Rename-DbaLogin",
    "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.",
    "category": "Security",
    "tags": [
      "login"
    ],
    "verb": "Rename",
    "popular": false,
    "url": "/Rename-DbaLogin",
    "popularityRank": 396,
    "synopsis": "Renames SQL Server logins and optionally their associated database users",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Rename-DbaLogin View Source Mitchell Hamann (@SirCaptainMitch) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Renames SQL Server logins and optionally their associated database users 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. When 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. By 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. Syntax Rename-DbaLogin [-SqlInstance] [[-SqlCredential] ] [-Login] [-NewLogin] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: SQL Login Example PS C:\\> Rename-DbaLogin -SqlInstance localhost -Login DbaToolsUser -NewLogin captain Example 2: Change the windowsuser login name PS C:\\> Rename-DbaLogin -SqlInstance localhost -Login domain\\oldname -NewLogin domain\\newname Example 3: WhatIf Example PS C:\\> Rename-DbaLogin -SqlInstance localhost -Login dbatoolsuser -NewLogin captain -WhatIf Required Parameters -SqlInstance Source SQL Server.You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Login Specifies the existing login name that you want to rename on the SQL Server instance. This must be an exact match for a login that currently exists on the server. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -NewLogin Specifies the new name for the login after the rename operation. For Windows logins, the new name must resolve to the same SID as the original login to maintain security mappings. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Renames corresponding database users across all databases where the login is mapped. Without 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts to confirm actions | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per operation performed (login rename and/or user renames). Each object includes the following properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the user being renamed (null for login-level rename operations) PreviousLogin: The original login name (populated for login rename, null for user renames) NewLogin: The new login name (populated for login rename, null for user renames) PreviousUser: The original database user name (null for login rename, populated for user renames) NewUser: The new database user name (null for login rename, populated for successful user renames) Status: Result of the operation (Successful, Failure, or \"Failure to rename. Rolled back change.\" when rollback occurs) When -Force is not specified, only one object is returned representing the login rename operation. When -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 back and a rollback status is returned. &nbsp;"
  },
  {
    "name": "Repair-DbaDbMirror",
    "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.",
    "category": "Utilities",
    "tags": [
      "mirroring",
      "mirror",
      "ha"
    ],
    "verb": "Repair",
    "popular": false,
    "url": "/Repair-DbaDbMirror",
    "popularityRank": 609,
    "synopsis": "Repairs suspended database mirroring sessions by restarting endpoints and resuming mirroring",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Repair-DbaDbMirror View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Repairs suspended database mirroring sessions by restarting endpoints and resuming mirroring 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. When 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. Syntax Repair-DbaDbMirror [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Attempts to repair the mirrored but suspended pubs database on sql2017 PS C:\\> Repair-DbaDbMirror -SqlInstance sql2017 -Database pubs Attempts to repair the mirrored but suspended pubs database on sql2017. Restarts the endpoints then sets the partner to resume. Prompts for confirmation. Example 2: Attempts to repair the mirrored but suspended pubs database on sql2017 PS C:\\> Get-DbaDatabase -SqlInstance sql2017 -Database pubs | Repair-DbaDbMirror -Confirm:$false Attempts to repair the mirrored but suspended pubs database on sql2017. Restarts the endpoints then sets the partner to resume. Does not prompt for confirmation. Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the name of the mirrored database that needs repair on the SQL Server instance. Use this when you know the specific database with suspended mirroring that requires endpoint restart and session resumption. Accepts multiple database names and supports wildcards for pattern matching. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase pipeline input to repair multiple mirrored databases in a single operation. Use this approach when you need to repair several databases at once or when working with the output of database filtering commands. Each database object must represent a database that has mirroring configured. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Database Returns the repaired database object for each database where mirroring was successfully resumed. One object is returned per database processed. All properties from the SMO Database object are available, including: Name: Database name Owner: Database owner login CreateDate: DateTime when the database was created LastBackupDate: DateTime of the most recent full backup LastDifferentialBackupDate: DateTime of the most recent differential backup LastLogBackupDate: DateTime of the most recent transaction log backup RecoveryModel: The recovery model (Simple, Full, BulkLogged) Status: Current database status (Normal, Restoring, RecoveryPending, Suspect, etc.) MirroringStatus: State of database mirroring (Disabled, Suspended, Synchronizing, Synchronized, Disconnected) Size: Total size of the database in megabytes SpaceAvailable: Available space in the database in megabytes Tables: Collection of tables in the database Views: Collection of views in the database StoredProcedures: Collection of stored procedures in the database &nbsp;"
  },
  {
    "name": "Repair-DbaDbOrphanUser",
    "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.",
    "category": "Utilities",
    "tags": [
      "orphan"
    ],
    "verb": "Repair",
    "popular": true,
    "url": "/Repair-DbaDbOrphanUser",
    "popularityRank": 49,
    "synopsis": "Repairs orphaned database users by remapping them to matching server logins or optionally removing them.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Repair-DbaDbOrphanUser View Source Claudio Silva (@ClaudioESSilva) , Simone Bizzotto (@niphlod) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Repairs orphaned database users by remapping them to matching server logins or optionally removing them. 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. The 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. Uses 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. Syntax Repair-DbaDbOrphanUser [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Users] ] [-RemoveNotExisting] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Finds and repairs all orphan users of all databases present on server &#39;sql2005&#39; PS C:\\> Repair-DbaDbOrphanUser -SqlInstance sql2005 Example 2: Finds and repair all orphan users in all databases present on server &#39;sqlserver2014a&#39; PS C:\\> Repair-DbaDbOrphanUser -SqlInstance sqlserver2014a -SqlCredential $cred Finds and repair all orphan users in all databases present on server 'sqlserver2014a'. SQL credentials are used to authenticate to the server. Example 3: Finds and repairs all orphan users in both db1 and db2 databases PS C:\\> Repair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1, db2 Example 4: Finds and repairs user &#39;OrphanUser&#39; in &#39;db1&#39; database PS C:\\> Repair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Database db1 -Users OrphanUser Example 5: Finds and repairs user &#39;OrphanUser&#39; on all databases PS C:\\> Repair-DbaDbOrphanUser -SqlInstance sqlserver2014a -Users OrphanUser Example 6: Finds all orphan users of all databases present on server &#39;sqlserver2014a&#39; PS C:\\> Repair-DbaDbOrphanUser -SqlInstance sqlserver2014a -RemoveNotExisting Finds all orphan users of all databases present on server 'sqlserver2014a'. Removes all users that do not have matching Logins. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for orphaned users. Accepts wildcards for pattern matching and multiple database names. Use this when you only need to repair orphaned users in specific databases rather than scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip when scanning for orphaned users. Useful for avoiding system databases or databases under maintenance. Commonly used to exclude tempdb, distribution databases, or databases where orphaned users should remain untouched. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Users Specifies specific database users to repair rather than processing all orphaned users found. Use this when you need to target specific problematic users or when working with large databases where selective repair is preferred. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -RemoveNotExisting Removes orphaned database users that have no corresponding server login instead of just reporting them. Use this after database migrations or when cleaning up databases where some users should no longer exist. Exercise caution as this permanently removes users. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Bypasses confirmation prompts and forces schema ownership changes to dbo when removing orphaned users. Required when orphaned users own database schemas that prevent their removal. Use with caution as it can affect database object ownership. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) DatabaseName: The name of the database where the orphaned user exists User: The name of the orphaned database user Status: The outcome of the repair attempt. Values are: \"Success\": User was successfully remapped to their matching server login \"No matching login\": No matching server login was found for the user (returned only when -RemoveNotExisting is not specified) When -RemoveNotExisting is specified, users without matching logins are passed to Remove-DbaDbOrphanUser instead of being returned in the output. No output is returned if no orphaned users are found in the specified database(s). &nbsp;"
  },
  {
    "name": "Repair-DbaInstanceName",
    "description": "Updates SQL Server's @@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/",
    "category": "Server Management",
    "tags": [
      "spn",
      "instance",
      "utility"
    ],
    "verb": "Repair",
    "popular": false,
    "url": "/Repair-DbaInstanceName",
    "popularityRank": 380,
    "synopsis": "Updates SQL Server's @@SERVERNAME system variable to match the Windows hostname",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Repair-DbaInstanceName View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Updates SQL Server's @@SERVERNAME system variable to match the Windows hostname Description Updates SQL Server's @@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. The 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. A 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. https://www.mssqltips.com/sqlservertip/2525/steps-to-change-the-server-name-for-a-sql-server-machine/ Syntax Repair-DbaInstanceName [-SqlInstance] [[-SqlCredential] ] [-AutoFix] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Checks to see if the server name is updatable and changes the name with a number of prompts PS C:\\> Repair-DbaInstanceName -SqlInstance sql2014 Example 2: Checks to see if the server name is updatable and automatically performs the change PS C:\\> Repair-DbaInstanceName -SqlInstance sql2014 -AutoFix Checks to see if the server name is updatable and automatically performs the change. Replication or mirroring will be broken if necessary. Example 3: Checks to see if the server name is updatable and automatically performs the change, bypassing most prompts... PS C:\\> Repair-DbaInstanceName -SqlInstance sql2014 -AutoFix -Force Checks 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. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AutoFix Automatically resolves blockers that prevent the server name repair, including removing replication distribution and disabling database mirroring. Use this when you need to fix the server name without manual intervention to remove these blocking configurations. This parameter will prompt for confirmation before breaking replication or mirroring unless combined with -Force. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Bypasses confirmation prompts for potentially destructive operations like stopping SQL services and breaking replication or mirroring. Use this for unattended automation or when you're certain about proceeding with all changes. Combine with -AutoFix for fully automated server name repairs without any prompts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object when the server name is successfully updated. The object contains instance identification and rename confirmation details from the Test-DbaInstanceName command. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) ServerName: The configured server name after the rename operation NewServerName: The expected server name based on hostname and instance name RenameRequired: Boolean indicating whether a rename was needed (should be false after successful rename) Updatable: Boolean indicating if the instance could be renamed (true when rename completed) Warnings: Warning message about SQL Server Reporting Services needing update if found, or \"N/A\" if not applicable Blockers: Array of reasons that prevented rename before fix, or \"N/A\" if no blockers existed No output is returned if the operation is skipped (instance already has correct name, clustered environment, or rename cancelled). &nbsp;"
  },
  {
    "name": "Reset-DbaAdmin",
    "description": "Recovers access to SQL Server instances when you're 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't 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't 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.",
    "category": "Server Management",
    "tags": [
      "wsman",
      "instance",
      "utility"
    ],
    "verb": "Reset",
    "popular": true,
    "url": "/Reset-DbaAdmin",
    "popularityRank": 19,
    "synopsis": "Regains administrative access to SQL Server instances when passwords or access has been lost",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Reset-DbaAdmin View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Regains administrative access to SQL Server instances when passwords or access has been lost Description Recovers access to SQL Server instances when you're 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. The 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. This 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. Once the service is restarted, the following tasks are performed: Login is added if it doesn't exist If login is a Windows User, an attempt is made to ensure it exists 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 Login will be enabled and unlocked Login will be added to sysadmin role If 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. For remote SQL Server instances, ensure WinRM is configured and accessible. If remote access isn't possible, run the script locally on the target server. Requires Windows administrator access to the server hosting SQL Server. Supports SQL Server 2005 and above on clustered and standalone configurations. Syntax Reset-DbaAdmin [-SqlInstance] [[-SqlCredential] ] [[-Login] ] [[-SecurePassword] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Prompts for password, then resets the &quot;sqladmin&quot; account password on sqlcluster PS C:\\> Reset-DbaAdmin -SqlInstance sqlcluster -SqlCredential sqladmin Example 2: Adds the domain account &quot;ad\\administrator&quot; as a sysadmin to the SQL instance PS C:\\> Reset-DbaAdmin -SqlInstance sqlserver\\sqlexpress -Login ad\\administrator -Confirm:$false Adds the domain account \"ad\\administrator\" as a sysadmin to the SQL instance. If the account already exists, it will be added to the sysadmin role. Does not prompt for a password since it is not a SQL login. Does not prompt for confirmation since -Confirm is set to $false. Example 3: Skips restart confirmation, prompts for password, then adds a SQL Login &quot;sqladmin&quot; with sysadmin privileges PS C:\\> Reset-DbaAdmin -SqlInstance sqlserver\\sqlexpress -Login sqladmin -Force Skips restart confirmation, prompts for password, then adds a SQL Login \"sqladmin\" with sysadmin privileges. If the account already exists, it will be added to the sysadmin role and the password will be reset. Required Parameters -SqlInstance The target SQL Server instance or instances. SQL Server must be 2005 and above, and can be a clustered or stand-alone instance. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Instead of using Login and SecurePassword, you can just pass in a credential object. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Specifies the login account to reset or create with sysadmin privileges. Defaults to \"sa\" if not specified. Use 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 \"DOMAIN\\User\" or \"DOMAIN\\Group\"). If the login doesn't 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | sa | -SecurePassword Provides the password for SQL authentication logins as a SecureString to avoid interactive prompts. Use this when automating the reset process or when you don't want to be prompted to enter the password manually. Only required for SQL logins, not Windows authentication accounts. The password will be applied during login creation or when resetting an existing SQL login's password. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Bypasses all confirmation prompts and proceeds with the service restart and login reset operations. Use this when you need to automate the recovery process or when you're certain about proceeding without manual confirmation. This includes the high-impact confirmation for stopping and restarting SQL Server services. Does not actually drop and recreate logins - the existing description appears to be incorrect for this function. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Dataplat.Dbatools.Login Returns 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 SQL Server instance. Properties include: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The name of the SQL Server instance SqlInstance: The full SQL Server instance name (ComputerName\\InstanceName format) Name: The login name (either SQL or Windows authentication account) LoginType: The type of login (SqlLogin or WindowsUser) CreateDate: The date/time the login was created LastLogin: The date/time of the most recent login (if available) IsDisabled: Boolean indicating if the login is disabled IsLocked: Boolean indicating if the login is locked out IsSysAdmin: Boolean indicating if the login has sysadmin privileges (should be True after successful reset) If an error occurs during the reset process and the function cannot reconnect to verify the login, no output is returned. &nbsp;"
  },
  {
    "name": "Reset-DbatoolsConfig",
    "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.",
    "category": "Utilities",
    "tags": [
      "module"
    ],
    "verb": "Reset",
    "popular": false,
    "url": "/Reset-DbatoolsConfig",
    "popularityRank": 497,
    "synopsis": "Resets dbatools module configuration settings back to their default values.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Reset-DbatoolsConfig View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Resets dbatools module configuration settings back to their default values. 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. The 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. In order for a reset to be possible, two conditions must be met: The setting must have been initialized. The setting cannot have been enforced by policy. Syntax Reset-DbatoolsConfig [-ConfigurationItem ] [-FullName ] [-EnableException] [-WhatIf] [-Confirm] [ ] Reset-DbatoolsConfig -Module [-Name ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Resets all configuration items of the MyModule to default PS C:\\> Reset-DbatoolsConfig -Module MyModule Example 2: Resets ALL configuration items to default PS C:\\> Get-DbatoolsConfig | Reset-DbatoolsConfig Example 3: Resets the configuration item named &#39;MyModule.Group.Setting1&#39; PS C:\\> Reset-DbatoolsConfig -FullName MyModule.Group.Setting1 Required Parameters -Module The name of the module whose configuration settings should be reset (e.g., 'dbatools', 'sql', 'connection'). Use this when you want to reset all settings within a specific functional area, such as resetting all connection-related settings after environment changes. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -ConfigurationItem One or more configuration objects as returned by Get-DbatoolsConfig. Use this when you want to reset specific configuration items that you've already identified through Get-DbatoolsConfig, allowing for precise control over which settings get reset. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -FullName The full qualified name of a specific configuration setting to reset (e.g., 'dbatools.Connection.EncryptConnection'). Use this when you know the exact setting name and want to reset just that one item, providing the most precise targeting of configuration changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Name A wildcard pattern to match configuration setting names within the specified module (defaults to \"\" for all settings). Use this with the -Module parameter to selectively reset settings, such as using \"Encrypt\" to reset only encryption-related settings within a module. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | * | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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. &nbsp;"
  },
  {
    "name": "Resolve-DbaNetworkName",
    "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't 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.",
    "category": "Utilities",
    "tags": [
      "network",
      "connection",
      "resolve"
    ],
    "verb": "Resolve",
    "popular": false,
    "url": "/Resolve-DbaNetworkName",
    "popularityRank": 299,
    "synopsis": "Resolves network names and returns detailed network information for SQL Server connection troubleshooting and validation.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Resolve-DbaNetworkName View Source Klaas Vandenberghe (@PowerDBAKlaas) , Simone Bizzotto (@niphold) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Resolves network names and returns detailed network information for SQL Server connection troubleshooting and validation. Description Performs comprehensive network name resolution to gather detailed connection information for SQL Server instances and computers. This function is essential when you need to verify connectivity, troubleshoot connection issues, or validate network configurations before connecting to SQL Server. Uses multiple resolution methods including DNS lookups, ICMP ping tests, and WMI/CIM queries to ensure accurate results across different network configurations. First tests connectivity using ICMP to identify the responding IP address, then gathers comprehensive network details through various protocols. Important: Remember that FQDN doesn't always match \"ComputerName dot Domain\" as AD intends. There are network setup (google \"disjoint domain\") where AD and DNS do not match. \"Full computer name\" (as reported by sysdm.cpl) is the only match between the two, and it matches the \"DNSHostName\" property of the computer object stored in AD. This means that the notation of FQDN that matches \"ComputerName dot Domain\" is incorrect in those scenarios. In other words, the \"suffix\" of the FQDN CAN be different from the AD Domain. This cmdlet has been providing good results since its inception but for lack of useful names some doubts may arise. Let this clear the doubts: InputName: whatever has been passed in ComputerName: hostname only IPAddress: IP Address DNSHostName: hostname only, coming strictly from DNS (as reported from the calling computer) DNSDomain: domain only, coming strictly from DNS (as reported from the calling computer) Domain: domain only, coming strictly from AD (i.e. the domain the ComputerName is joined to) DNSHostEntry: Fully name as returned by DNS [System.Net.Dns]::GetHostEntry FQDN: \"legacy\" notation of ComputerName \"dot\" Domain (coming from AD) FullComputerName: Full name as configured from within the Computer (i.e. the only secure match between AD and DNS) So, if you need to use something, go with FullComputerName, always, as it is the most correct in every scenario. Syntax Resolve-DbaNetworkName [[-ComputerName] ] [[-Credential] ] [-Turbo] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain... PS C:\\> Resolve-DbaNetworkName -ComputerName sql2014 Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry for sql2014 Example 2: Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain... PS C:\\> Resolve-DbaNetworkName -ComputerName sql2016, sql2014 Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry for sql2016 and sql2014 Example 3: Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain... PS C:\\> Get-DbaRegServer -SqlInstance sql2014 | Resolve-DbaNetworkName Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry for all SQL Servers returned by Get-DbaRegServer Example 4: Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain... PS C:\\> Get-DbaRegServer -SqlInstance sql2014, sql2016\\sqlexpress | Resolve-DbaNetworkName Returns a custom object displaying InputName, ComputerName, IPAddress, DNSHostName, DNSDomain, Domain, DNSHostEntry, FQDN, DNSHostEntry for all SQL Servers returned by Get-DbaRegServer Optional Parameters -ComputerName Specifies the target computer name, IP address, or SQL Server instance to resolve network information for. Use this when troubleshooting connectivity issues or validating network configurations before connecting to SQL Server. Accepts computer names (SERVER01), IP addresses (192.168.1.100), SQL Server instances (SERVER01\\INSTANCE), or SMO objects from Get-DbaRegServer. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Turbo Enables DNS-only resolution mode for faster network name resolution without connecting to the target computer. Use this when you need quick DNS lookups but don't require comprehensive network details or WMI/CIM information. Results may be less accurate in disjoint-domain environments where AD and DNS configurations don't align, and may vary depending on your local DNS configuration. | Property | Value | | --- | --- | | Alias | FastParrot | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one network information object per input computer name. Each object contains comprehensive network resolution details with the following properties: InputName (string): The original input value as provided by the user (computer name, IP address, or instance name) ComputerName (string): The hostname only, in uppercase (e.g., \"SERVER01\") IPAddress (string): The IP address that responded to connectivity tests, either IPv4 or IPv6 DNSHostname (string): The hostname portion from DNS resolution (lowercase), coming from DNS as reported by the local system DNSDomain (string): The domain suffix from DNS resolution, as reported by the local system's DNS configuration Domain (string): The domain name from Active Directory, representing the domain the computer is joined to DNSHostEntry (string): The fully qualified domain name as returned by [System.Net.Dns]::GetHostEntry() FQDN (string): Legacy notation combining ComputerName and Domain with a dot separator (e.g., \"SERVER01.CONTOSO.COM\") FullComputerName (string): The full computer name as configured within the operating system, matching the DNSHostName property in Active Directory When -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 faster results but may be less accurate in disjoint-domain environments. Note: FullComputerName is the most reliable property across all network configurations as it matches between AD and DNS in both standard and disjoint-domain environments. &nbsp;"
  },
  {
    "name": "Resolve-DbaPath",
    "description": "Validates and resolves file system paths with additional safety checks beyond PowerShell's 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.",
    "category": "Utilities",
    "tags": [
      "path",
      "resolve",
      "utility"
    ],
    "verb": "Resolve",
    "popular": false,
    "url": "/Resolve-DbaPath",
    "popularityRank": 534,
    "synopsis": "Validates and resolves file system paths with enhanced error handling and provider verification.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Resolve-DbaPath View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates and resolves file system paths with enhanced error handling and provider verification. Description Validates and resolves file system paths with additional safety checks beyond PowerShell's 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. Syntax Resolve-DbaPath [-Path] [[-Provider] ] [-SingleItem] [-NewChild] [ ] &nbsp; Examples &nbsp; Example 1: Ensures the resolved path is a FileSystem path PS C:\\> Resolve-DbaPath -Path report.log -Provider FileSystem -NewChild -SingleItem Ensures the resolved path is a FileSystem path. This will resolve to the current folder and the file report.log. Will not ensure the file exists or doesn't exist. If the current path is in a different provider, it will throw an exception. Example 2: This will resolve all items in the parent folder, whatever the current path or drive might be PS C:\\> Resolve-DbaPath -Path ..\\* Required Parameters -Path Specifies the file system path to validate and resolve, supporting both absolute and relative paths. Use this to verify backup destinations, database file locations, or script paths before database operations. Accepts wildcards for pattern matching and can validate multiple paths when passed as an array. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Provider Validates that the resolved path belongs to the specified PowerShell provider type. Use 'FileSystem' to ensure database backup paths or data file locations are on disk storage, not registry or other providers. Prevents accidental operations on wrong provider types like 'Registry', 'Certificate', or 'ActiveDirectory'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SingleItem Requires the path to resolve to exactly one location, preventing wildcard expansion. Use when specifying a unique backup file destination or single database file path where multiple matches would cause errors. Will throw an error if wildcards or patterns resolve to multiple paths. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NewChild Validates the parent directory exists for creating new files, without requiring the target file to exist. Use when specifying backup file destinations, new database file paths, or log file locations that will be created. The parent folder must be accessible, but the final filename can be new. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String Returns one or more resolved file system paths as strings. Each input path that resolves successfully is output as a separate string value. When 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. The returned paths are fully qualified file system paths in the format expected by PowerShell cmdlets and .NET APIs. When using -NewChild, returns the constructed path for the new file even if it does not yet exist, but the parent directory must be accessible. &nbsp;"
  },
  {
    "name": "Restart-DbaService",
    "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).",
    "category": "Server Management",
    "tags": [
      "service",
      "instance",
      "restart"
    ],
    "verb": "Restart",
    "popular": false,
    "url": "/Restart-DbaService",
    "popularityRank": 135,
    "synopsis": "Restarts SQL Server services with proper dependency handling and service ordering.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Restart-DbaService View Source Kirill Kravtsov (@nvarscar) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Restarts SQL Server services with proper dependency handling and service ordering. 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. Requires Local Admin rights on destination computer(s). Syntax Restart-DbaService [[-ComputerName] ] [-InstanceName ] [-SqlInstance ] [-Type ] [-Timeout ] [-Credential ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Restart-DbaService [-InstanceName ] [-Type ] -InputObject [-Timeout ] [-Credential ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Restarts the SQL Server related services on computer sqlserver2014a PS C:\\> Restart-DbaService -ComputerName sqlserver2014a Example 2: Gets the SQL Server related services on computers sql1, sql2 and sql3 and restarts them PS C:\\> 'sql1','sql2','sql3'| Get-DbaService | Restart-DbaService Example 3: Restarts the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2 PS C:\\> Restart-DbaService -ComputerName sql1,sql2 -InstanceName MSSQLSERVER Example 4: Restarts the SQL Server related services of type &quot;SSRS&quot; (Reporting Services) on computers in the variable... PS C:\\> Restart-DbaService -ComputerName $MyServers -Type SSRS Restarts the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers. Example 5: Restarts SQL Server database engine services on sql1 forcing dependent SQL Server Agent services to restart... PS C:\\> Restart-DbaService -ComputerName sql1 -Type Engine -Force Restarts SQL Server database engine services on sql1 forcing dependent SQL Server Agent services to restart as well. Required Parameters -InputObject Accepts service objects from Get-DbaService to restart specific services that have already been filtered or identified. Use 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. | Property | Value | | --- | --- | | Alias | ServiceCollection | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -ComputerName Specifies the computer names where SQL Server services will be restarted. Accepts multiple computer names for batch operations. Use this when you need to restart services across multiple SQL Server hosts during maintenance windows or after configuration changes. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -InstanceName Restricts the restart operation to services belonging to specific SQL Server instances (like MSSQLSERVER, SQLEXPRESS, or named instances). Use this when you have multiple instances on a server but only need to restart services for specific instances, avoiding unnecessary downtime for other instances. | Property | Value | | --- | --- | | Alias | Instance | | Required | False | | Pipeline | false | | Default Value | | -SqlInstance Use a combination of computername and instancename to get the SQL Server related services for specific instances on specific computers. Parameters ComputerName and InstanceName will be ignored if SqlInstance is used. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies which SQL Server service types to restart: Agent, Browser, Engine, FullText, SSAS, SSIS, SSRS, PolyBase, or Launchpad. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Agent,Browser,Engine,FullText,SSAS,SSIS,SSRS,PolyBase,Launchpad | -Timeout Sets the maximum time in seconds to wait for each service stop/start operation to complete before timing out. Defaults to 60 seconds. Increase 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 60 | -Credential Credential object used to connect to the computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Automatically includes dependent services (SQL Agent, PolyBase, Launchpad) when restarting Database Engine services to ensure proper shutdown sequence. Use this when restarting Engine services to avoid dependency conflicts and ensure all related services restart cleanly, particularly important during major configuration changes or patches. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per service that was processed with the following properties: ComputerName: The name of the computer where the service is running InstanceName: The SQL Server instance name the service belongs to ServiceName: The Windows service name (MSSQLSERVER, MSSQL$NAMED, SQLSERVERAGENT, etc.) ServiceType: The type of service (Engine, Agent, Browser, FullText, SSAS, SSIS, SSRS, PolyBase, Launchpad) Status: The result of the restart operation (Successful, Failed, or other status values) Services that failed to stop are returned before services that successfully restarted. This allows you to identify which services encountered issues during the restart process. If -Force is specified with Engine services, dependent services (Agent, PolyBase, Launchpad) are automatically included and restarted as part of the operation. &nbsp;"
  },
  {
    "name": "Restore-DbaDatabase",
    "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't 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's maintenance solution backup structures for faster processing.",
    "category": "Backup & Restore",
    "tags": [
      "disasterrecovery",
      "backup",
      "restore"
    ],
    "verb": "Restore",
    "popular": true,
    "url": "/Restore-DbaDatabase",
    "popularityRank": 3,
    "synopsis": "Restores SQL Server databases from backup files with intelligent backup chain selection and point-in-time recovery.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Restore-DbaDatabase View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Restores SQL Server databases from backup files with intelligent backup chain selection and point-in-time recovery. Description Scans backup files and automatically selects the optimal restore sequence to recover databases to a specific point in time. This function handles the complex task of building complete backup chains from full, differential, and transaction log backups, so you don't have to manually determine which files are needed or in what order to restore them. The function excels at disaster recovery scenarios where you need to quickly restore from a collection of backup files. It validates backup headers, ensures restore chains are complete, and can recover to any point in time within your backup coverage. Whether restoring from local files, network shares, or Azure blob storage, it automatically handles file discovery and validation. By default, all file paths must be accessible to the target SQL Server instance. The function uses xp_dirtree for remote file scanning and supports various input methods including direct file lists, folder scanning, and pipeline input from other dbatools commands. It integrates seamlessly with Ola Hallengren's maintenance solution backup structures for faster processing. Syntax Restore-DbaDatabase -SqlInstance [-SqlCredential ] -Path [-DatabaseName ] [-DestinationDataDirectory ] [-DestinationLogDirectory ] [-DestinationFileStreamDirectory ] [-RestoreTime ] [-NoRecovery] [-WithReplace] [-KeepReplication] [-XpDirTree] [-NoXpDirRecurse] [-OutputScriptOnly] [-VerifyOnly] [-MaintenanceSolutionBackup] [-FileMapping ] [-IgnoreLogBackup] [-IgnoreDiffBackup] [-UseDestinationDefaultDirectories] [-ReuseSourceFolderStructure] [-DestinationFilePrefix ] [-RestoredDatabaseNamePrefix ] [-TrustDbBackupHistory] [-MaxTransferSize ] [-BlockSize ] [-BufferCount ] [-DirectoryRecurse] [-EnableException] [-StandbyDirectory ] [-Continue] [-ExecuteAs ] [-StorageCredential ] [-ReplaceDbNameInFile] [-DestinationFileSuffix ] [-KeepCDC] [-ErrorBrokerConversations] [-GetBackupInformation ] [-StopAfterGetBackupInformation] [-SelectBackupInformation ] [-StopAfterSelectBackupInformation] [-FormatBackupInformation ] [-StopAfterFormatBackupInformation] [-TestBackupInformation ] [-StopAfterTestBackupInformation] [-StopBefore] [-StopMark ] [-StopAfterDate ] [-StopAtLsn ] [-StatementTimeout ] [-Checksum] [-Restart] [-WhatIf] [-Confirm] [ ] Restore-DbaDatabase -SqlInstance [-SqlCredential ] -Path [-DatabaseName ] [-OutputScriptOnly] [-TrustDbBackupHistory] [-MaxTransferSize ] [-BlockSize ] [-BufferCount ] [-EnableException] [-StorageCredential ] [-GetBackupInformation ] [-StopAfterGetBackupInformation] [-SelectBackupInformation ] [-StopAfterSelectBackupInformation] [-FormatBackupInformation ] [-StopAfterFormatBackupInformation] [-TestBackupInformation ] [-StopAfterTestBackupInformation] -PageRestore -PageRestoreTailFolder [-StopBefore] [-StopMark ] [-StopAfterDate ] [-StopAtLsn ] [-StatementTimeout ] [-Checksum] [-Restart] [-WhatIf] [-Confirm] [ ] Restore-DbaDatabase -SqlInstance [-SqlCredential ] [-DatabaseName ] [-OutputScriptOnly] [-EnableException] [-StorageCredential ] [-Recover] [-GetBackupInformation ] [-StopAfterGetBackupInformation] [-SelectBackupInformation ] [-StopAfterSelectBackupInformation] [-FormatBackupInformation ] [-StopAfterFormatBackupInformation] [-TestBackupInformation ] [-StopAfterTestBackupInformation] [-StopBefore] [-StopMark ] [-StopAfterDate ] [-StopAtLsn ] [-StatementTimeout ] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Scans all the backup files in \\\\server2\\backups, filters them and restores the database to server1\\instance1 PS C:\\> Restore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups Example 2: Scans all the backup files in \\\\server2\\backups$ stored in an Ola Hallengren style folder structure, filters... PS C:\\> Restore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups -MaintenanceSolutionBackup -DestinationDataDirectory c:\\restores Scans all the backup files in \\\\server2\\backups$ stored in an Ola Hallengren style folder structure, filters them and restores the database to the c:\\restores folder on server1\\instance1 Example 3: Takes the provided files from multiple directories and restores them on server1\\instance1 PS C:\\> Get-ChildItem c:\\SQLbackups1\\, \\\\server\\sqlbackups2 | Restore-DbaDatabase -SqlInstance server1\\instance1 Example 4: Scans all the backup files in \\\\server2\\backups stored in an Ola Hallengren style folder structure, filters... PS C:\\> $RestoreTime = Get-Date('11:19 23/12/2016') PS C:\\> Restore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups -MaintenanceSolutionBackup -DestinationDataDirectory c:\\restores -RestoreTime $RestoreTime Scans all the backup files in \\\\server2\\backups stored in an Ola Hallengren style folder structure, filters them and restores the database to the c:\\restores folder on server1\\instance1 up to 11:19 23/12/2016 Example 5: Scans all the backup files in \\\\server2\\backups, filters them and generate the T-SQL Scripts to restore the... PS C:\\> $result = Restore-DbaDatabase -SqlInstance server1\\instance1 -Path \\\\server2\\backups -DestinationDataDirectory c:\\restores -OutputScriptOnly PS C:\\> $result | Out-File -Filepath c:\\scripts\\restore.sql Scans 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 retrieval Example 6: Scans all the files in c:\\backups and then restores them onto the SQL Server Instance server1\\instance1... PS C:\\> Restore-DbaDatabase -SqlInstance server1\\instance1 -Path c:\\backups -DestinationDataDirectory c:\\DataFiles -DestinationLogDirectory c:\\LogFile Scans all the files in c:\\backups and then restores them onto the SQL Server Instance server1\\instance1, placing data files c:\\DataFiles and all the log files into c:\\LogFiles Example 7: Will restore the backup held at http://demo.blob.core.windows.net/backups/dbbackup.bak to server1\\instance1 PS C:\\> Restore-DbaDatabase -SqlInstance server1\\instance1 -Path http://demo.blob.core.windows.net/backups/dbbackup.bak -AzureCredential MyAzureCredential Will 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 credential MyAzureCredential held on instance Server1\\instance1 Example 8: Will attempt to restore the backups from http://demo.blob.core.windows.net/backups/dbbackup.bak if a SAS... PS C:\\> Restore-DbaDatabase -SqlInstance server1\\instance1 -Path http://demo.blob.core.windows.net/backups/dbbackup.bak Will 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 Example 9: Will restore the backup from S3-compatible storage to sql2022 PS C:\\> Restore-DbaDatabase -SqlInstance sql2022 -Path s3://s3.us-west-2.amazonaws.com/mybucket/backups/dbbackup.bak -StorageCredential MyS3Credential Will restore the backup from S3-compatible storage to sql2022. Requires SQL Server 2022 or higher. The credential must be configured with Identity = 'S3 Access Key' and Secret containing the access key and secret key. Example 10: This will take all of the files found under the folders c:\\backups and \\\\server1\\backups, and pipeline them... PS C:\\> $File = Get-ChildItem c:\\backups, \\\\server1\\backups PS C:\\> $File | Restore-DbaDatabase -SqlInstance Server1\\Instance -UseDestinationDefaultDirectories This will take all of the files found under the folders c:\\backups and \\\\server1\\backups, and pipeline them into Restore-DbaDatabase. Restore-DbaDatabase will then scan all of the files, and restore all of the databases included to the latest point in time covered by their backups. All data and log files will be moved to the default SQL Server folder for those file types as defined on the target instance. Example 11: In this example we step through the backup files held in c:\\dbatools\\db1 folder PS C:\\> $files = Get-ChildItem C:\\dbatools\\db1 PS C:\\> $params = @{ >> SqlInstance = 'server\\instance1' >> DestinationFilePrefix = 'prefix' >> DatabaseName ='Restored' >> RestoreTime = (get-date \"14:58:30 22/05/2017\") >> NoRecovery = $true >> WithReplace = $true >> StandbyDirectory = 'C:\\dbatools\\standby' >> } >> PS C:\\> $files | Restore-DbaDatabase @params PS C:\\> Invoke-DbaQuery -SQLInstance server\\instance1 -Query \"select top 1 from Restored.dbo.steps order by dt desc\" PS C:\\> $params.RestoreTime = (get-date \"15:09:30 22/05/2017\") PS C:\\> $params.NoRecovery = $false PS C:\\> $params.Add(\"Continue\",$true) PS C:\\> $files | Restore-DbaDatabase @params PS C:\\> Invoke-DbaQuery -SQLInstance server\\instance1 -Query \"select top 1 from Restored.dbo.steps order by dt desc\" PS C:\\> Restore-DbaDatabase -SqlInstance server\\instance1 -DestinationFilePrefix prefix -DatabaseName Restored -Continue -WithReplace In this example we step through the backup files held in c:\\dbatools\\db1 folder. First we restore the database to a point in time in standby mode. This means we can check some details in the databases We then roll it on a further 9 minutes to perform some more checks And finally we continue by rolling it all the way forward to the latest point in the backup. At each step, only the log files needed to roll the database forward are restored. Example 12: In this example we restore example1 database with no recovery, and then the second call is to set the... PS C:\\> Restore-DbaDatabase -SqlInstance server\\instance1 -Path c:\\backups -DatabaseName example1 -NoRecovery PS C:\\> Restore-DbaDatabase -SqlInstance server\\instance1 -Recover -DatabaseName example1 In this example we restore example1 database with no recovery, and then the second call is to set the database to recovery. Example 13: Gets a list of Suspect Pages using Get-DbaSuspectPage PS C:\\> $SuspectPage = Get-DbaSuspectPage -SqlInstance server\\instance1 -Database ProdFinance PS C:\\> Get-DbaDbBackupHistory -SqlInstance server\\instance1 -Database ProdFinance -Last | Restore-DbaDatabase -PageRestore $SuspectPage -PageRestoreTailFolder c:\\temp -TrustDbBackupHistory Gets 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 If server\\instance1 is Enterprise edition this will be done online, if not it will be performed offline Example 14: Due to SQL Server 2000 not returning all the backup headers we cannot restore directly PS C:\\> $BackupHistory = Get-DbaBackupInformation -SqlInstance sql2005 -Path \\\\backups\\sql2000\\ProdDb PS C:\\> $BackupHistory | Restore-DbaDatabase -SqlInstance sql2000 -TrustDbBackupHistory Due 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 This will use a SQL Server instance > 2000 to read the headers, and then pass them in to Restore-DbaDatabase as a BackupHistory object. Example 15: This will restore the database from the &quot;C:\\Temp\\devops_prod_full.bak&quot; file, with the new name &quot;DevOps_DEV&quot;... PS C:\\> Restore-DbaDatabase -SqlInstance server1\\instance1 -Path \"C:\\Temp\\devops_prod_full.bak\" -DatabaseName \"DevOps_DEV\" -ReplaceDbNameInFile PS C:\\> Rename-DbaDatabase -SqlInstance server1\\instance1 -Database \"DevOps_DEV\" -LogicalName \" _ \" This 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 configured data and log locations. After 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 Example 16: Restores &#39;database&#39; to &#39;server1&#39; and moves the files to new locations PS C:\\> $FileStructure = @{ >> 'database_data' = 'C:\\Data\\database_data.mdf' >> 'database_log' = 'C:\\Log\\database_log.ldf' >> } >> PS C:\\> Restore-DbaDatabase -SqlInstance server1 -Path \\\\ServerName\\ShareName\\File -DatabaseName database -FileMapping $FileStructure Restores 'database' to 'server1' 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. Example 17: Restores test to sql2019 using the file structure built from the existing database on sql2016 PS C:\\> $filemap = Get-DbaDbFileMapping -SqlInstance sql2016 -Database test PS C:\\> Get-ChildItem \\\\nas\\db\\backups\\test | Restore-DbaDatabase -SqlInstance sql2019 -Database test -FileMapping $filemap.FileMapping Example 18: Restores the backups from \\\\ServerName\\ShareName\\File as database, stops before the first &#39;OvernightStart&#39;... PS C:\\> Restore-DbaDatabase -SqlInstance server1 -Path \\\\ServerName\\ShareName\\File -DatabaseName database -StopMark OvernightStart -StopBefore -StopAfterDate Get-Date('21:00 10/05/2020') Restores the backups from \\\\ServerName\\ShareName\\File as database, stops before the first 'OvernightStart' mark that occurs after '21:00 10/05/2020'. Example 19: Restores the backups from \\\\ServerName\\ShareName\\File as database, stopping when the specified LSN is reached PS C:\\> Restore-DbaDatabase -SqlInstance server1 -Path \\\\ServerName\\ShareName\\File -DatabaseName database -StopAtLsn '00000030:00000f28:0001' Example 20: Restores the backups from \\\\ServerName\\ShareName\\File as database, stopping just before the specified LSN is... PS C:\\> Restore-DbaDatabase -SqlInstance server1 -Path \\\\ServerName\\ShareName\\File -DatabaseName database -StopAtLsn '00000030:00000f28:0001' -StopBefore Restores the backups from \\\\ServerName\\ShareName\\File as database, stopping just before the specified LSN is reached. Note that Date time needs to be specified in your local SQL Server culture Example 21: Demonstrates the recommended workflow for restoring from S3 storage PS C:\\> # Restore from S3 storage folder (SQL Server 2022+) PS C:\\> # First, enumerate S3 bucket contents using AWS PowerShell module - You need to be authenticated! PS C:\\> $s3Files = Get-S3Object -BucketName \"mybucket\" -KeyPrefix \"backups/AdventureWorks/\" -Region \"us-west-2\" PS C:\\> $backupPaths = $s3Files | Where-Object { $_.Key -match '\\.(bak|trn|dif)$' } | ForEach-Object { \"s3://mybucket.s3.us-west-2.amazonaws.com/$($_.Key)\" } PS C:\\> PS C:\\> # Then restore using the enumerated file paths PS C:\\> Restore-DbaDatabase -SqlInstance sql2022 -Path $backupPaths -StorageCredential MyS3Credential Demonstrates the recommended workflow for restoring from S3 storage. Since SQL Server cannot enumerate S3 bucket contents via T-SQL, you must first use PowerShell's Get-S3Object cmdlet to list backup files, then pass the full S3 URLs to Restore-DbaDatabase. The StorageCredential parameter should reference a SQL Server credential configured for S3 access. Example 22: Scans the \\\\server\\backups share and restores only files with a .bak extension, excluding any incomplete or... PS C:\\> Get-ChildItem \\\\server\\backups | Where-Object { $_.Extension -eq \".bak\" } | Restore-DbaDatabase -SqlInstance server1\\instance1 Scans the \\\\server\\backups share and restores only files with a .bak extension, excluding any incomplete or in-progress files such as those with extensions like .bak.part that may be created by SFTP clients or other upload tools during file transfer. When backup files are uploaded to a share while a restore job is running, incomplete files with non-standard extensions can cause Restore-DbaDatabase to hang while trying to read the backup header of a locked or partial file. Always filter your file list to include only complete backup files before passing them to this command. Example 23: Recursively scans \\\\server\\backups and filters files to only those ending in .bak, .trn, or .dif using a... PS C:\\> $backupFiles = Get-ChildItem \\\\server\\backups -Recurse | Where-Object { $_.Name -match '\\.(bak|trn|dif)$' } PS C:\\> $backupFiles | Restore-DbaDatabase -SqlInstance server1\\instance1 Recursively scans \\\\server\\backups and filters files to only those ending in .bak, .trn, or .dif using a regex match, then restores them to server1\\instance1. This pattern is recommended when your backup directory may contain non-backup files or files from in-progress uploads, ensuring only complete backup files are processed. Required Parameters -SqlInstance The target SQL Server instance. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Path Specifies the location of backup files to restore from, supporting local drives, UNC paths, Azure blob storage URLs, or S3 URLs. Use this when you need to restore from a specific backup location or when piping backup files from Get-ChildItem. Accepts multiple comma-separated paths for complex restore scenarios spanning multiple locations. For S3 storage (SQL Server 2022+): S3 bucket contents cannot be enumerated using T-SQL. You must provide explicit file paths or use PowerShell's Get-S3Object cmdlet (from AWS.Tools.S3 module) to retrieve the list of backup files first, then pass them to this command. See examples for S3 usage patterns. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -PageRestore Performs targeted restoration of specific damaged pages using output from Get-DbaSuspectPages. Use this for repairing isolated page corruption without restoring the entire database. Enterprise Edition enables online page restore while Standard Edition requires the database offline during repair. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -PageRestoreTailFolder Specifies where to create the tail log backup required for page restore operations. Use this to designate a safe location for the automatic tail log backup that page restore creates. The folder must be accessible to the SQL Server service account and have sufficient space for the tail log backup. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DatabaseName Defines the target database name for the restored database when different from the original name. Use this when creating a copy of a production database for testing or when restoring to avoid name conflicts. Required when restoring a single database to a different name than what's stored in the backup files. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -DestinationDataDirectory Sets the target directory path where data files (.mdf, .ndf) will be restored on the destination instance. Use this when you need to restore to a different drive or storage location than the original database. When specified alone, log files will also be placed here unless DestinationLogDirectory is provided. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationLogDirectory Defines the target directory for transaction log files (.ldf) separate from data files. Use this to follow best practices by placing log files on different drives for performance and disaster recovery. Must be used together with DestinationDataDirectory for proper file separation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationFileStreamDirectory Specifies where FILESTREAM data containers will be restored, separate from regular database files. Use this when your database contains FILESTREAM data and you need to place it on specific storage. Requires DestinationDataDirectory to be specified and the target instance to have FILESTREAM enabled. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestoreTime Sets the point-in-time recovery target for restoring the database to a specific moment. Use this for recovering from logical errors, unwanted changes, or data corruption that occurred at a known time. Requires a complete backup chain including transaction logs covering the specified time period. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-Date).AddYears(1) | -NoRecovery Leaves the database in a restoring state to allow additional transaction log restores or log shipping setup. Use this when you need to apply additional log backups, set up availability groups, or prepare for continuous log shipping. The database will remain inaccessible until recovered with the RESTORE WITH RECOVERY statement. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WithReplace Allows overwriting an existing database with the same name during the restore operation. Use this when you need to refresh a test environment or replace a corrupted database with a backup. Essential for disaster recovery scenarios where you're restoring over a damaged database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepReplication Maintains replication settings and objects when restoring databases involved in replication topologies. Use this when restoring publisher or subscriber databases where you need to preserve replication configuration. Essential for disaster recovery scenarios involving replicated databases to avoid reconfiguring publications and subscriptions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -XpDirTree Forces backup file discovery to use SQL Server's xp_dirtree instead of PowerShell file system access. Use this when backup files are on network shares that PowerShell cannot access but SQL Server can. Requires sysadmin privileges and may be needed for environments with strict network security policies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoXpDirRecurse If specified, prevents the XpDirTree process from recursing (its default behaviour). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -OutputScriptOnly Generates the T-SQL RESTORE statements without executing them, allowing for script review or manual execution. Use this to validate restore commands, create deployment scripts, or when you need approval before running restores. Helpful for compliance environments where all database changes must be reviewed before execution. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -VerifyOnly Validates backup files and restore paths without performing the actual restore operation. Use this to test backup file integrity, verify backup chains are complete, and confirm restore feasibility. Essential for disaster recovery planning and backup validation routines without impacting production systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MaintenanceSolutionBackup Optimizes backup file scanning for Ola Hallengren's Maintenance Solution folder structure. Use this when your backups follow the standard Ola Hallengren folder layout with separate FULL, DIFF, and LOG subdirectories. Significantly improves performance by using predictable file locations rather than reading every backup header. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FileMapping Provides precise control over where individual database files are restored using logical file names. Use this when you need granular file placement, such as putting specific filegroups on different drives for performance. Create a hashtable mapping logical names to physical paths: @{'DataFile1'='C:\\Data\\File1.mdf'; 'LogFile1'='D:\\Logs\\File1.ldf'} | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -IgnoreLogBackup Excludes transaction log backups from the restore operation, stopping at the latest full or differential backup. Use this when you only need to restore to a recent backup checkpoint rather than the latest point in time. Useful for creating a baseline copy of a database without applying the most recent transactions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IgnoreDiffBackup Skips differential backups and restores using only full backups plus transaction logs. Use this when differential backups are corrupted or when you need to restore using a specific full backup as the baseline. Results in longer restore times as all transaction log backups since the full backup must be applied. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UseDestinationDefaultDirectories Places restored database files in the SQL Server instance's default data and log directories. Use this when you want to follow the target instance's standard file location configuration. The function will attempt to create directories if they don't exist, ensuring consistent file placement. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ReuseSourceFolderStructure Maintains the original database file directory structure from the source server during restore. Use this when migrating between servers that share similar drive layouts or when preserving application-specific paths. Consider version differences in SQL Server default paths (MSSQL12, MSSQL13, etc.) when restoring between versions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DestinationFilePrefix This value will be prefixed to ALL restored files (log and data). This is just a simple string prefix. If you want to perform more complex rename operations then please use the FileMapping parameter. This will apply to all file move options, except for FileMapping. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestoredDatabaseNamePrefix A string which will be prefixed to the start of the restore Database's Name. Useful if restoring a copy to the same sql server for testing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TrustDbBackupHistory Bypasses backup header validation when using piped input from Get-DbaDbBackupHistory or similar commands. Use this to significantly speed up restores when you're confident in the backup chain integrity. Trades verification safety for performance - backup file issues won't be detected until the restore attempt. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MaxTransferSize Controls the size of each data transfer between storage and SQL Server during restore operations. Use this to optimize restore performance based on your storage subsystem characteristics. Must be a multiple of 64KB with higher values potentially improving performance on high-speed storage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BlockSize Defines the physical block size used for backup file reading during restore operations. Use this to match the block size used during backup creation for optimal performance. Valid values: 0.5KB, 1KB, 2KB, 4KB, 8KB, 16KB, 32KB, or 64KB, with larger blocks typically faster on modern storage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BufferCount Sets the number of I/O buffers SQL Server uses for the restore operation to improve throughput. Use this to optimize restore performance by allowing more parallel I/O operations. Higher values can improve performance but consume more memory - typically set between 2-64 based on available RAM. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -DirectoryRecurse If specified the specified directory will be recursed into (overriding the default behaviour). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -StandbyDirectory Places restored databases in STANDBY mode with undo files created in the specified directory. Use this for log shipping secondary servers or when you need read-only access during restore operations. The directory must exist and be writable by the SQL Server service account for undo file creation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Continue Resumes log restore operations on databases currently in RESTORING or STANDBY states. Use this to apply additional transaction log backups to advance the recovery point of an existing restore chain. Essential for log shipping scenarios or when performing point-in-time recovery in multiple steps. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExecuteAs If value provided the restore will be executed under this login's context. The login must exist, and have the relevant permissions to perform the restore. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StorageCredential Specifies the SQL Server credential name for authenticating to Azure blob storage or S3-compatible object storage during restore operations. Use this when restoring from Azure blob storage or S3 backups that require authentication. For Azure: The credential must contain valid Azure storage account keys or SAS tokens. For S3: The credential must use Identity = 'S3 Access Key' and Secret = 'AccessKeyID:SecretKeyID'. Requires SQL Server 2022 or higher. | Property | Value | | --- | --- | | Alias | AzureCredential,S3Credential | | Required | False | | Pipeline | false | | Default Value | | -ReplaceDbNameInFile Substitutes the original database name with the new DatabaseName in physical file names during restore. Use this when restoring databases with descriptive file names to maintain naming consistency. Requires DatabaseName parameter and helps avoid confusing file names like \"Production_Data.mdf\" in test environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DestinationFileSuffix This value will be suffixed to ALL restored files (log and data). This is just a simple string suffix. If you want to perform more complex rename operations then please use the FileMapping parameter. This will apply to all file move options, except for FileMapping. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Recover Brings databases currently in RESTORING state online by executing RESTORE WITH RECOVERY. Use this to complete restore operations that were left in NoRecovery state or to finalize standby databases. Makes previously inaccessible databases available for normal read/write operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepCDC Preserves Change Data Capture (CDC) configuration and data during the restore operation. Use this when restoring databases with CDC enabled and you need to maintain change tracking functionality. Cannot be combined with NoRecovery or Standby modes as CDC requires the database to be fully recovered. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ErrorBrokerConversations Ends all conversations in the database with an error message when restoring, using the ERROR_BROKER_CONVERSATIONS option. Use this when you want to clean up Service Broker conversations that may be left in an inconsistent state after a restore. Only applied during the final restore step (WITH RECOVERY), not during intermediate log restores. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -GetBackupInformation Passing a string value into this parameter will cause a global variable to be created holding the output of Get-DbaBackupInformation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StopAfterGetBackupInformation Switch which will cause the function to exit after returning GetBackupInformation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SelectBackupInformation Passing a string value into this parameter will cause a global variable to be created holding the output of Select-DbaBackupInformation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StopAfterSelectBackupInformation Switch which will cause the function to exit after returning SelectBackupInformation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FormatBackupInformation Passing a string value into this parameter will cause a global variable to be created holding the output of Format-DbaBackupInformation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StopAfterFormatBackupInformation Switch which will cause the function to exit after returning FormatBackupInformation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -TestBackupInformation Passing a string value into this parameter will cause a global variable to be created holding the output of Test-DbaBackupInformation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StopAfterTestBackupInformation Switch which will cause the function to exit after returning TestBackupInformation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -StopBefore Switch to indicate the restore should stop before StopMark or StopAtLsn occurs, default is to stop when mark/LSN is reached. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -StopMark Marked point in the transaction log to stop the restore at (Mark is created via BEGIN TRANSACTION (https://docs.microsoft.com/en-us/sql/t-sql/language-elements/begin-transaction-transact-sql?view=sql-server-ver15)). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-Date '01/01/1971') | -StopAtLsn Log Sequence Number (LSN) in the transaction log at which to stop the restore operation. Use this for precise point-in-time recovery to an exact LSN, which provides more granular control than timestamp-based recovery. The LSN value can be obtained from sys.fn_dblog, backup headers, or error logs. Combine with -StopBefore to stop just before the specified LSN. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StatementTimeout Sets the maximum time in minutes to wait for restore operations before timing out. Use this to prevent extremely long-running restores from hanging indefinitely in automated scripts. Defaults to unlimited since large database restores can take hours depending on size and storage speed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Checksum Enables backup checksum verification during restore operations. Forces the restore to verify backup checksums and fail if checksums are not present. Use this to ensure backup files contain checksums and validate them during restore, following backup best practices. Without this parameter, SQL Server verifies checksums if present but doesn't fail if checksums are missing. With this parameter, the operation fails if checksums are not present in the backup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Restart Instructs the restore operation to restart an interrupted restore sequence. Use this when a previous restore operation was interrupted due to a reboot, service failure, or other system event. Allows resuming large transaction log restores that were partially completed before interruption. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command would execute, but does not actually perform the command. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts to confirm certain actions. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.String (when -OutputScriptOnly is specified) Returns the T-SQL RESTORE statements as strings without executing them. This allows the scripts to be reviewed, modified, or executed later. PSCustomObject (for -Recover parameter set only) When using the -Recover parameter to bring databases online, returns one object per database recovered with the following properties: SqlInstance: The target SQL Server instance DatabaseName: The name of the database that was recovered RestoreComplete: Boolean indicating if recovery succeeded Scripts: The T-SQL RESTORE statement that was executed No direct output (for standard restore operations) When performing standard restore operations (without OutputScriptOnly or Recover), the function delegates to Invoke-DbaAdvancedRestore which handles database restoration. The function may also create global variables if any of the following parameters are specified: GetBackupInformation: Creates global variable containing backup information SelectBackupInformation: Creates global variable containing selected backup history FormatBackupInformation: Creates global variable containing formatted backup information TestBackupInformation: Creates global variable containing tested backup information Use these variables to inspect the backup chain analysis, file mappings, and restore validation results without executing the restore operation. &nbsp;"
  },
  {
    "name": "Restore-DbaDbCertificate",
    "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.",
    "category": "Backup & Restore",
    "tags": [
      "certbackup",
      "certificate",
      "backup"
    ],
    "verb": "Restore",
    "popular": false,
    "url": "/Restore-DbaDbCertificate",
    "popularityRank": 225,
    "synopsis": "Restores database certificates from .cer and .pvk files into SQL Server databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Restore-DbaDbCertificate View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Restores database certificates from .cer and .pvk files into SQL Server databases. 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. The 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. Syntax Restore-DbaDbCertificate [-SqlInstance] [[-SqlCredential] ] [-Path] [[-KeyFilePath] ] [[-EncryptionPassword] ] [[-Database] ] [[-Name] ] [[-DecryptionPassword] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Restores all the certificates in the specified path, password is used to both decrypt and encrypt the private... PS C:\\> $securepass = Get-Credential usernamedoesntmatter | Select-Object -ExpandProperty Password PS C:\\> Restore-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates -DecryptionPassword $securepass Restores all the certificates in the specified path, password is used to both decrypt and encrypt the private key. Example 2: Restores the DatabaseTDE certificate to Server1 and uses the MasterKey to encrypt the private key PS C:\\> Restore-DbaDbCertificate -SqlInstance Server1 -Path \\\\Server1\\Certificates\\DatabaseTDE.cer -DecryptionPassword (Get-Credential usernamedoesntmatter).Password Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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. Use this to restore certificates from your certificate backup location after disaster recovery or server migrations. | Property | Value | | --- | --- | | Alias | FullName,ExportPath | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 certificate. Only specify this when your private key files are stored in a different location from your certificate files. | Property | Value | | --- | --- | | Alias | Key | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -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. Use this when you want to change the private key encryption method or set a specific password for the restored certificate. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target database where the certificate will be restored. Defaults to the master database if not specified. Use this when restoring certificates for specific database features like TDE, Always Encrypted, or application-specific encryption within user databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when you need the certificate to have a specific name that differs from the backup file naming convention. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Required for all certificate restores since private keys are encrypted by default when exported from SQL Server. | Property | Value | | --- | --- | | Alias | Password,SecurePassword | | Required | False | | Pipeline | false | | Default Value | (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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Certificate Returns one Certificate object per certificate successfully restored to the database. For example, restoring 3 certificates results in 3 objects being returned. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database where the certificate was restored Name: The name of the certificate Subject: The subject field of the certificate for identification StartDate: The date and time when the certificate becomes valid ActiveForServiceBrokerDialog: Boolean indicating if the certificate is active for Service Broker dialog security ExpirationDate: The date and time when the certificate expires Issuer: The issuer of the certificate LastBackupDate: The date and time of the most recent backup of the certificate Owner: The owner or principal that owns the certificate PrivateKeyEncryptionType: The encryption type used for the private key (None, Password, or MasterKey) Serial: The serial number of the certificate *Additional properties available from the SMO Certificate object (via Select-Object ):** DatabaseId: The unique identifier of the database containing the certificate Thumbprint: The SHA-1 hash of the certificate CreateDate: The date and time when the certificate was created SignedByCertificate: Name of the certificate that signed this certificate (if applicable) PrivateKeyExists: Boolean indicating if the certificate has a private key &nbsp;"
  },
  {
    "name": "Restore-DbaDbSnapshot",
    "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's RESTORE DATABASE FROM DATABASE_SNAPSHOT command and automatically handles SQL Server's 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.",
    "category": "Backup & Restore",
    "tags": [
      "snapshot",
      "backup",
      "restore",
      "database"
    ],
    "verb": "Restore",
    "popular": false,
    "url": "/Restore-DbaDbSnapshot",
    "popularityRank": 371,
    "synopsis": "Restores SQL Server databases from database snapshots, reverting to the snapshot's point-in-time state",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Restore-DbaDbSnapshot View Source Simone Bizzotto (@niphold) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Restores SQL Server databases from database snapshots, reverting to the snapshot's point-in-time state 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. The function uses SQL Server's RESTORE DATABASE FROM DATABASE_SNAPSHOT command and automatically handles SQL Server's 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. When Force is specified, the command will terminate active connections to both the target database and snapshot to ensure the restore operation completes successfully. Syntax Restore-DbaDbSnapshot [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Snapshot] ] [[-InputObject] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Restores HR and Accounting databases using the latest snapshot available PS C:\\> Restore-DbaDbSnapshot -SqlInstance sql2014 -Database HR, Accounting Example 2: Restores HR database from latest snapshot and kills any active connections in the database on sql2014 PS C:\\> Restore-DbaDbSnapshot -SqlInstance sql2014 -Database HR -Force Example 3: Restores HR database from latest snapshot and kills any active connections in the database on sql2016 PS C:\\> Get-DbaDbSnapshot -SqlInstance sql2016 -Database HR | Restore-DbaDbSnapshot -Force Example 4: Allows the selection of snapshots on sql2016 to restore PS C:\\> Get-DbaDbSnapshot -SqlInstance sql2016 | Out-GridView -PassThru | Restore-DbaDbSnapshot Example 5: Restores databases from snapshots named HR_snap_20161201 and Accounting_snap_20161101 PS C:\\> Restore-DbaDbSnapshot -SqlInstance sql2014 -Snapshot HR_snap_20161201, Accounting_snap_20161101 Optional Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to restore from their most recent snapshots. Accepts multiple database names and wildcards for pattern matching. Use this when you want to restore specific databases to their snapshot state rather than working with snapshot names directly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from being restored when using wildcard patterns or restoring multiple databases. Helpful when you want to restore most databases from snapshots but skip certain critical production databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Snapshot Specifies the exact snapshot names to restore from, giving you precise control over which snapshot is used for each database. Use this when you need to restore from specific snapshots rather than automatically using the most recent ones. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts snapshot objects from other dbatools commands like Get-DbaDbSnapshot through the PowerShell pipeline. This enables you to filter and select specific snapshots before restoring, such as using Out-GridView for interactive selection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Force Automatically drops other snapshots of the same database that would prevent the restore operation, as required by SQL Server. Also terminates active connections to both the target database and snapshot to ensure the restore completes successfully. Required when multiple snapshots exist for the database being restored or when active sessions could block the operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts for confirmation of every step. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Database Returns 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 file growth settings were restored to their pre-snapshot values. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Database name Status: Current database status (Normal, Suspect, Offline, etc.) IsAccessible: Boolean indicating if the database is currently accessible RecoveryModel: Database recovery model (Full, Simple, BulkLogged) Owner: Database owner login name Additional properties available from the SMO Database object: Size: Current size of the database in megabytes CreateDate: DateTime when the database was created LastBackupDate: DateTime of the most recent backup LastDiffBackup: DateTime of the most recent differential backup LastLogBackup: DateTime of the most recent transaction log backup Collation: Database collation setting CompatibilityLevel: Database compatibility level All properties from the base SMO Database object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Resume-DbaAgDbDataMovement",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Resume",
    "popular": false,
    "url": "/Resume-DbaAgDbDataMovement",
    "popularityRank": 316,
    "synopsis": "Resumes suspended data synchronization for availability group databases.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Resume-DbaAgDbDataMovement View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Resumes suspended data synchronization for availability group databases. 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. Syntax Resume-DbaAgDbDataMovement [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Database] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Resumes data movement on db1 and db2 to ag1 on sql2017a PS C:\\> Resume-DbaAgDbDataMovement -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2 Resumes data movement on db1 and db2 to ag1 on sql2017a. Prompts for confirmation. Example 2: Resumes data movement on the selected availability group databases PS C:\\> Get-DbaAgDatabase -SqlInstance sql2017a, sql2019 | Out-GridView -Passthru | Resume-DbaAgDbDataMovement -Confirm:$false Resumes data movement on the selected availability group databases. Does not prompt for confirmation. Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies the name of the availability group containing the databases with suspended data movement. Required when using the SqlInstance parameter to identify which AG context to work within. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which availability group databases to resume data movement for. Accepts multiple database names. Use this to target specific databases when you don't want to resume movement for all databases in the availability group. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group database objects from Get-DbaAgDatabase for pipeline operations. Use this when you want to filter or select specific AG databases before resuming data movement. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityDatabase Returns 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 secondary replica to the primary's transaction log stream. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) AvailabilityGroup: Name of the availability group LocalReplicaRole: Role of this replica (Primary or Secondary) Name: Database name SynchronizationState: Current synchronization state (NotSynchronizing, Synchronizing, Synchronized, Reverting, Initializing) IsFailoverReady: Boolean indicating if the database is ready for failover IsJoined: Boolean indicating if the database has joined the availability group IsSuspended: Boolean indicating if data movement is suspended (should be False after ResumeDataMovement succeeds) Additional properties available (from SMO AvailabilityDatabase object): DatabaseGuid: Unique identifier for the database EstimatedDataLoss: Estimated data loss in seconds EstimatedRecoveryTime: Estimated recovery time in seconds FileStreamSendRate: Rate of FILESTREAM data being sent (bytes/sec) GroupDatabaseId: Unique identifier for the database within the AG LastCommitTime: Timestamp of last committed transaction LogSendQueue: Size of log send queue in KB RedoRate: Rate of redo operations (bytes/sec) State: SMO object state (Existing, Creating, Pending, etc.) All properties from the base SMO object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Revoke-DbaAgPermission",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Revoke",
    "popular": false,
    "url": "/Revoke-DbaAgPermission",
    "popularityRank": 596,
    "synopsis": "Revokes permissions from SQL Server logins on database mirroring endpoints or availability groups.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Revoke-DbaAgPermission View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Revokes permissions from SQL Server logins on database mirroring endpoints or availability groups. 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. Syntax Revoke-DbaAgPermission [[-SqlInstance] ] [[-SqlCredential] ] [[-Login] ] [[-AvailabilityGroup] ] [-Type] [[-Permission] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes CreateAnyDatabase permissions from ad\\spservice on the SharePoint availability group on sql2017a PS C:\\> Revoke-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup SharePoint -Login ad\\spservice -Permission CreateAnyDatabase Removes CreateAnyDatabase permissions from ad\\spservice on the SharePoint availability group on sql2017a. Does not prompt for confirmation. Example 2: Removes CreateAnyDatabase permissions from ad\\spservice on the ag1 and ag2 availability groups on sql2017a PS C:\\> Revoke-DbaAgPermission -SqlInstance sql2017a -Type AvailabilityGroup -AvailabilityGroup ag1, ag2 -Login ad\\spservice -Permission CreateAnyDatabase -Confirm Removes CreateAnyDatabase permissions from ad\\spservice on the ag1 and ag2 availability groups on sql2017a. Prompts for confirmation. Example 3: Revokes the selected logins Connect permissions on the DatabaseMirroring endpoint for sql2017a PS C:\\> Get-DbaLogin -SqlInstance sql2017a | Out-GridView -Passthru | Revoke-DbaAgPermission -Type EndPoint Required Parameters -Type Determines whether to revoke permissions on database mirroring endpoints or availability groups. This parameter is mandatory. Use 'Endpoint' to revoke permissions on the DatabaseMirroring endpoint, typically needed for Always On setup or mirroring configurations. Use 'AvailabilityGroup' to revoke permissions directly on specific availability group objects for more granular security control. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | | Accepted Values | Endpoint,AvailabilityGroup | Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Specifies the SQL Server logins or Windows accounts to remove permissions from. Required when using the SqlInstance parameter. Use this when you need to revoke access from service accounts, developers, or other principals that no longer need endpoint or availability group permissions. If the specified login doesn't exist, the function will attempt to create it first. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies which availability groups to target for permission revocation. Required when using Type 'AvailabilityGroup'. Use this to limit the scope when you only want to revoke permissions on specific AGs rather than all availability groups in the instance. Accepts multiple availability group names for bulk operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Permission Specifies which permissions to revoke from the targeted logins. Defaults to 'Connect' if not specified. For endpoints, most permissions are valid including Connect, Alter, and Control. CreateAnyDatabase is not supported for endpoints. For availability groups, only Alter, Control, TakeOwnership, and ViewDefinition are supported. Use Connect for basic endpoint access, Alter for configuration changes, Control for full permissions, or ViewDefinition for read-only metadata access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Connect | | Accepted Values | 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. Use this approach when you want to filter or select specific logins before revoking permissions, or when combining with other dbatools commands. This parameter provides an alternative to specifying SqlInstance and Login parameters directly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The login name from which the permission was revoked Permission: The permission that was revoked (Connect, Alter, Control, etc.) Type: Always \"Revoke\" indicating the operation type Status: \"Success\" when the revocation completes successfully &nbsp;"
  },
  {
    "name": "Save-DbaCommunitySoftware",
    "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's 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/",
    "category": "Utilities",
    "tags": [
      "community"
    ],
    "verb": "Save",
    "popular": false,
    "url": "/Save-DbaCommunitySoftware",
    "popularityRank": 338,
    "synopsis": "Downloads and caches popular SQL Server community tools from GitHub for use by dbatools installation commands",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Save-DbaCommunitySoftware View Source Andreas Jordan, @JordanOrdix Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Downloads and caches popular SQL Server community tools from GitHub for use by dbatools installation commands Description Downloads and extracts popular SQL Server community tools from GitHub repositories to maintain a local cache used by dbatools installation commands. This function automatically manages the acquisition and versioning of essential DBA script collections, eliminating the need to manually download and organize multiple tool repositories. It's called internally by Install-Dba, Update-Dba, and Invoke-DbaAzSqlDbTip commands when they need to access the latest versions of community tools. Supports both online downloads directly from GitHub and offline installations using local zip files, making it suitable for restricted network environments. The function handles version detection, directory structure normalization, and maintains consistent file organization across different tool repositories. For 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: MaintenanceSolution: https://github.com/olahallengren/sql-server-maintenance-solution FirstResponderKit: https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit/releases DarlingData: https://github.com/erikdarlingdata/DarlingData SQLWATCH: https://github.com/marcingminski/sqlwatch/releases WhoIsActive: https://github.com/amachanic/sp_whoisactive/releases DbaMultiTool: https://github.com/LowlyDBA/dba-multitool/releases AzSqlTips: https://github.com/microsoft/azure-sql-tips/releases/ Syntax Save-DbaCommunitySoftware [[-Software] ] [[-Branch] ] [[-LocalFile] ] [[-Url] ] [[-LocalDirectory] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Updates the local cache of Ola Hallengren&#39;s Solution objects PS C:\\> Save-DbaCommunitySoftware -Software MaintenanceSolution Example 2: Updates the local cache of the First Responder Kit based on the given file PS C:\\> Save-DbaCommunitySoftware -Software FirstResponderKit -LocalFile \\\\fileserver\\Software\\SQL-Server-First-Responder-Kit-20211106.zip Optional Parameters -Software Name of the software to download. Options include: MaintenanceSolution: SQL Server Maintenance Solution created by Ola Hallengren (https://ola.hallengren.com) FirstResponderKit: First Responder Kit created by Brent Ozar (http://FirstResponderKit.org) DarlingData: Erik Darling's stored procedures (https://www.erikdarlingdata.com) SQLWATCH: SQL Server Monitoring Solution created by Marcin Gminski (https://sqlwatch.io/) WhoIsActive: Adam Machanic's comprehensive activity monitoring stored procedure sp_WhoIsActive (https://github.com/amachanic/sp_whoisactive) DbaMultiTool: John McCall's T-SQL scripts for the long haul: optimizing storage, on-the-fly documentation, and general administrative needs (https://dba-multitool.org) AzSqlTips: Azure SQL PM team scripts to review Azure SQL Database design, health and performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this when you need a specific development branch or to override default versioning. Only applies to branch-based downloads like MaintenanceSolution, FirstResponderKit, DarlingData, and DbaMultiTool. For SQLWATCH, use 'prerelease' or 'pre-release' to get preview versions instead of stable releases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LocalFile Specifies the path to a local zip file or SQL script to install from instead of downloading from GitHub. Use 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 AzSqlTips (get-sqldb-tips.sql). Essential for air-gapped systems where direct internet access is not available. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Url Specifies a custom URL to download the software archive from instead of using the automatic GitHub URLs. Use 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. Must point to a downloadable zip file containing the community tools. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LocalDirectory Specifies a custom directory path where the community software will be extracted and cached. Use 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. Useful for custom cache locations or when working with multiple versions of the same tool. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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, check the exit code or use ErrorAction/ErrorVariable parameters. &nbsp;"
  },
  {
    "name": "Save-DbaDiagnosticQueryScript",
    "description": "Downloads the latest versions of Glenn Berry's 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's resources page, saving them with version-specific filenames for easy identification.",
    "category": "Advanced Features",
    "tags": [
      "community",
      "glennberry"
    ],
    "verb": "Save",
    "popular": false,
    "url": "/Save-DbaDiagnosticQueryScript",
    "popularityRank": 471,
    "synopsis": "Downloads Glenn Berry's SQL Server Diagnostic Information Queries for performance monitoring and troubleshooting",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Save-DbaDiagnosticQueryScript View Source Andre Kamman (@AndreKamman), andrekamman.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Downloads Glenn Berry's SQL Server Diagnostic Information Queries for performance monitoring and troubleshooting Description Downloads the latest versions of Glenn Berry's 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. The 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. This 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. The function automatically detects and downloads scripts for all available SQL Server versions found on Glenn Berry's resources page, saving them with version-specific filenames for easy identification. Syntax Save-DbaDiagnosticQueryScript [[-Path] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Downloads the most recent version of all Glenn Berry DMV scripts to the specified location PS C:\\> Save-DbaDiagnosticQueryScript -Path c:\\temp Downloads the most recent version of all Glenn Berry DMV scripts to the specified location. If Path is not specified, the \"My Documents\" location will be used. Optional Parameters -Path Specifies the directory path where Glenn Berry's diagnostic query scripts will be downloaded. Defaults to the current user's Documents folder. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | [Environment]::GetFolderPath(\"mydocuments\") | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns one file information object for each diagnostic script downloaded. Each object represents a downloaded SQL script file containing Glenn Berry's diagnostic queries. Properties: FullName: Full file path of the downloaded diagnostic query script (e.g., C:\\Users\\UserName\\Documents\\SQLServerDiagnosticQueries_2022.sql) Name: The filename of the script (e.g., SQLServerDiagnosticQueries_2022.sql) Extension: File extension (.sql) Length: File size in bytes CreationTime: DateTime when the file was created LastWriteTime: DateTime when the file was last modified Directory: The directory object containing the file Attributes: File attributes (Archive, etc.) &nbsp;"
  },
  {
    "name": "Save-DbaKbUpdate",
    "description": "Downloads Microsoft KB updates, cumulative updates, and service packs from Microsoft's 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.",
    "category": "Utilities",
    "tags": [
      "deployment",
      "install",
      "patching"
    ],
    "verb": "Save",
    "popular": false,
    "url": "/Save-DbaKbUpdate",
    "popularityRank": 214,
    "synopsis": "Downloads Microsoft Knowledge Base updates and patches to local storage",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Save-DbaKbUpdate View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Downloads Microsoft Knowledge Base updates and patches to local storage Description Downloads Microsoft KB updates, cumulative updates, and service packs from Microsoft's 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. Syntax Save-DbaKbUpdate [[-Name] ] [[-Path] ] [[-FilePath] ] [[-Architecture] ] [[-Language] ] [[-InputObject] ] [-UseWebRequest] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Downloads KB4057119 to the current directory PS C:\\> Save-DbaKbUpdate -Name KB4057119 Downloads KB4057119 to the current directory. This works for SQL Server or any other KB. Example 2: Downloads the selected files from KB4057119 to the current directory PS C:\\> Get-DbaKbUpdate -Name KB4057119 -Simple | Out-GridView -Passthru | Save-DbaKbUpdate Example 3: Downloads KB4057119 and the x64 version of KB4057114 to C:\\temp PS C:\\> Save-DbaKbUpdate -Name KB4057119, 4057114 -Path C:\\temp Downloads KB4057119 and the x64 version of KB4057114 to C:\\temp. This works for SQL Server or any other KB. Example 4: Downloads the x64 version of KB4057114 and the x86 version of KB4057114 to C:\\temp PS C:\\> Save-DbaKbUpdate -Name KB4057114 -Architecture All -Path C:\\temp Downloads the x64 version of KB4057114 and the x86 version of KB4057114 to C:\\temp. This works for SQL Server or any other KB. Example 5: Downloads only the english version of KB5003279, which is the Service Pack 3 for SQL Server 2016, to C:\\temp PS C:\\> Save-DbaKbUpdate -Name KB5003279 -Language enu -Path C:\\temp Optional Parameters -Name Specifies the Microsoft Knowledge Base article number to download. Accepts KB prefix or just the numeric value (e.g., 'KB4057119' or '4057119'). Use this to target specific patches, cumulative updates, or service packs for SQL Server or other Microsoft products. Supports multiple KB numbers in a single command for batch downloading. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the directory where downloaded KB files will be saved. Defaults to the current working directory. Use this to organize patches into specific folders or network locations for easier deployment across multiple servers. The directory will be created if it doesn't exist. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | . | -FilePath Specifies the exact filename and path for the downloaded file, overriding the server-provided filename. Use this when you need custom naming conventions or want to save to a specific location with a particular name. Cannot be used when downloading multiple KBs or when Architecture is set to 'All'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Architecture Specifies the CPU architecture for the downloaded files. Valid values are 'x64', 'x86', 'ia64', or 'All'. Use 'All' to download files for all available architectures when you need to support mixed environments. Most modern SQL Server deployments use 'x64', which is the default. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | x64 | | Accepted Values | x64,x86,ia64,All | -Language Filters downloads to a specific language version using three-letter language codes (e.g., 'enu' for English, 'deu' for German). Primarily useful for SQL Server Service Packs which have separate files per language, unlike Cumulative Updates which are language-neutral. Only downloads files matching the specified language code when multiple language versions are available. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts pipeline input from Get-DbaKbUpdate, allowing you to filter and select specific files before downloading. Use this workflow to preview available downloads with Get-DbaKbUpdate, then pipe selected results for download. Particularly useful when working with KBs that have multiple file options. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -UseWebRequest Forces the use of Invoke-WebRequest instead of Start-BitsTransfer for downloading files. Use this when running in a non-interactive context such as a scheduled task or SQL Agent job, where Start-BitsTransfer may fail because it requires a logged-in user session. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.IO.FileInfo Returns one FileInfo object for each successfully downloaded KB file. The objects represent the downloaded files saved to the local file system. Properties: Name: The filename of the downloaded KB file FullName: The complete file path where the file was saved Length: The file size in bytes Directory: The directory where the file was saved CreationTime: DateTime when the file was created LastWriteTime: DateTime when the file was last modified Attributes: File attributes (Archive, ReadOnly, Hidden, etc.) Mode: File permissions string (e.g., -a--- for archive) Only 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. &nbsp;"
  },
  {
    "name": "Select-DbaBackupInformation",
    "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.",
    "category": "Backup & Restore",
    "tags": [
      "backup",
      "restore"
    ],
    "verb": "Select",
    "popular": false,
    "url": "/Select-DbaBackupInformation",
    "popularityRank": 176,
    "synopsis": "Filters backup history to identify the minimum backup chain needed for point-in-time database recovery",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Select-DbaBackupInformation View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Filters backup history to identify the minimum backup chain needed for point-in-time database recovery 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. Syntax Select-DbaBackupInformation [-BackupHistory] [[-RestoreTime] ] [-IgnoreLogs] [-IgnoreDiffs] [[-DatabaseName] ] [[-ServerName] ] [[-ContinuePoints] ] [[-LastRestoreType] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all backups needed to restore all the backups in \\\\server1\\backups$ to 1 hour ago PS C:\\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$ PS C:\\> $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) Example 2: Returns all the backups needed to restore Database ProdFinance to an hour ago PS C:\\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$ PS C:\\> $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -DatabaseName ProdFinance Example 3: Returns all the backups in \\\\server1\\backups$ to restore to as close prior to 1 hour ago as can be managed... PS C:\\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$ PS C:\\> $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -IgnoreLogs Returns 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 Example 4: Returns all the backups in \\\\server1\\backups$ to restore to 1 hour ago using only Full and Log backups PS C:\\> $Backups = Get-DbaBackupInformation -SqlInstance Server1 -Path \\\\server1\\backups$ PS C:\\> $FilteredBackups = $Backups | Select-DbaBackupInformation -RestoreTime (Get-Date).AddHours(-1) -IgnoreDiffs Required Parameters -BackupHistory Backup history records from Get-DbaBackupInformation containing backup metadata and file paths. This function analyzes these records to determine the minimum backup chain needed for point-in-time recovery. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -RestoreTime The specific point in time to restore the database to. Defaults to one month in the future if not specified. Use this when you need to recover to a specific moment, such as just before a data corruption incident occurred. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-Date).addmonths(1) | -IgnoreLogs Excludes transaction log backups from the restore chain, limiting recovery to the most recent full or differential backup. Use this when you don't need point-in-time recovery or when log backups are unavailable or corrupted. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IgnoreDiffs Excludes differential backups from the restore chain, using only full backups and transaction logs. Use this when differential backups are corrupted or when you want to test a restore strategy using only full and log backups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DatabaseName Filters results to only include backup chains for the specified database names. Accepts wildcards. Use this when you only need to restore specific databases from a backup set containing multiple databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ServerName Filters results to only include backups from the specified server or availability group names. For Availability Groups, this filters by the AG name rather than individual replica server names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ContinuePoints Output from Get-RestoreContinuableDatabase containing LSN and fork information for resuming interrupted restores. Use this when continuing a partial restore operation on a database that's already in a restoring state. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LastRestoreType Output from Get-DbaDbRestoreHistory -Last showing the most recent restore operation performed on the target database. This determines whether differential backups can be applied based on the last restore type performed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Backup objects from Get-DbaBackupInformation Returns 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 includes the original properties from Get-DbaBackupInformation plus an added RestoreTime property. The returned objects represent: One full or differential backup (the most recent full backup before RestoreTime, or the most recent differential backup) Zero or more transaction log backups (the sequence of log backups from the most recent full/diff to the RestoreTime) Output properties vary based on the input backup history objects, but typically include: Database: The database name Type: Backup type (Full, Differential, Log, Transaction Log, etc.) BackupSetID: Unique identifier for the backup set Start: DateTime when the backup started End: DateTime when the backup completed FirstLsn: First log sequence number in the backup LastLsn: Last log sequence number in the backup CheckpointLsn: Checkpoint LSN (for full backups) DatabaseBackupLsn: LSN of the most recent full backup (for diff/log backups) FullName: File path(s) to the backup file(s) RestoreTime: The target restore time (added by this function) When -IgnoreLogs is specified, transaction log backups are excluded from the output. When -IgnoreDiffs is specified, differential backups are excluded from the output. When -ContinuePoints is specified with an interrupted restore, LSN-based filtering ensures continuity. &nbsp;"
  },
  {
    "name": "Select-DbaDbSequenceNextValue",
    "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's not just a read operation.",
    "category": "Utilities",
    "tags": [
      "data",
      "sequence",
      "table"
    ],
    "verb": "Select",
    "popular": false,
    "url": "/Select-DbaDbSequenceNextValue",
    "popularityRank": 658,
    "synopsis": "Retrieves and increments the next value from a SQL Server sequence object.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Select-DbaDbSequenceNextValue View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves and increments the next value from a SQL Server sequence object. 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. This is useful for testing sequence behavior, troubleshooting sequence issues, or retrieving sequence values for application logic. Note that calling this function will permanently increment the sequence counter, so it's not just a read operation. Syntax Select-DbaDbSequenceNextValue [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [-Sequence] [[-Schema] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Selects the next value from the sequence TestSequence in the TestDB database on the sqldev01 instance PS C:\\> Select-DbaDbSequenceNextValue -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence Example 2: Using a pipeline this command selects the next value from the sequence TestSchema.TestSequence in the TestDB... PS C:\\> Get-DbaDatabase -SqlInstance sqldev01 -Database TestDB | Select-DbaDbSequenceNextValue -Sequence TestSequence -Schema TestSchema Using a pipeline this command selects the next value from the sequence TestSchema.TestSequence in the TestDB database on the sqldev01 instance. Required Parameters -Sequence Specifies the name of the sequence object to increment and retrieve the next value from. Accepts multiple sequence names when you need to get next values from several sequences in the same operation. This will permanently increment each sequence's internal counter. | Property | Value | | --- | --- | | Alias | Name | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database containing the sequence object you want to increment. Required when using SqlInstance parameter to identify which database contains the target sequence. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Specifies the schema that contains the sequence object. Defaults to 'dbo' if not specified. Use this when your sequence is created in a custom schema other than the default dbo schema. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | dbo | -InputObject Accepts database objects from Get-DbaDatabase via pipeline input. Use this to chain database selection with sequence operations when working with multiple databases or complex filtering scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.Int64 Returns the next value from the specified sequence object as a 64-bit integer. Each call to this function increments the sequence's internal counter and returns the next value in the sequence series. When 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 bigint data type). Example values: 1, 2, 3, 100, 1000, etc., depending on the sequence's start value, increment, and current state. &nbsp;"
  },
  {
    "name": "Select-DbaObject",
    "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 'Length as Size'\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.",
    "category": "Utilities",
    "tags": [],
    "verb": "Select",
    "popular": false,
    "url": "/Select-DbaObject",
    "popularityRank": 262,
    "synopsis": "Wrapper around Select-Object, extends property parameter.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Select-DbaObject View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters Synopsis Wrapper around Select-Object, extends property parameter. Description Wrapper around Select-Object, extends property parameter. This function allows specifying in-line transformation of the properties specified without needing to use complex hashtables. For example, renaming a property becomes as simple as 'Length as Size' Also supported: Specifying a typename Picking the default display properties Adding to an existing object without destroying its type See the description of the Property parameter for an exhaustive list of legal notations for in-line transformations. Syntax Select-DbaObject [-Property ] [-Alias ] [-ScriptProperty ] [-ScriptMethod ] [-InputObject ] [-ExcludeProperty ] [-ExpandProperty ] -Unique [-Last ] [-First ] [-Skip ] -Wait [-ShowProperty ] [-ShowExcludeProperty ] [-TypeName ] -KeepInputObject [] Select-DbaObject [-Property ] [-Alias ] [-ScriptProperty ] [-ScriptMethod ] [-InputObject ] [-ExcludeProperty ] [-ExpandProperty ] -Unique [-SkipLast ] [-ShowProperty ] [-ShowExcludeProperty ] [-TypeName ] -KeepInputObject [] Select-DbaObject [-InputObject ] -Unique -Wait [-Index ] [-ShowProperty ] [-ShowExcludeProperty ] [-TypeName ] -KeepInputObject [] &nbsp; Examples &nbsp; Example Example 1: Renaming a property: Get-ChildItem | Select-DbaObject Name, &quot;Length as Size&quot; Selects the properties Name and Length, renaming... Get-ChildItem | Select-DbaObject Name, \"Length as Size\" Selects the properties Name and Length, renaming Length to Size in the process. Example Example 2: Converting type: Import-Csv .\\file.csv | Select-DbaObject Name, &quot;Length as Size to DbaSize&quot; Selects the properties Name and... Import-Csv .\\file.csv | Select-DbaObject Name, \"Length as Size to DbaSize\" Selects the properties Name and Length, renaming Length to Size and converting it to [DbaSize] (a userfriendly representation of size numbers contained in the dbatools module) Example Example 3: Selecting from another object 1: $obj = [PSCustomObject]@{ Name = &quot;Foo&quot; } Get-ChildItem | Select-DbaObject FullName, Length, &quot;Name from obj&quot;... $obj = [PSCustomObject]@{ Name = \"Foo\" } Get-ChildItem | Select-DbaObject FullName, Length, \"Name from obj\" Selects the properties FullName and Length from the input and the Name property from the object stored in $obj Example Example 4: Selecting from another object 2: $list = @() $list += [PSCustomObject]@{ Type = &quot;Foo&quot;; ID = 1 } $list += [PSCustomObject]@{ Type = &quot;Bar&quot;; ID =... $list = @() $list += [PSCustomObject]@{ Type = \"Foo\"; ID = 1 } $list += [PSCustomObject]@{ Type = \"Bar\"; ID = 2 } $obj | Select-DbaObject Name, \"ID from list WHERE Type = Name\" This allows you to LEFT JOIN contents of another variable. Note that it can only do simple property-matching at this point. 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 Type property of equal value as Name on the input. Example Example 5: Naming and styling: Get-ChildItem | Select-DbaObject Name, Length, FullName, Used, LastWriteTime, Mode -TypeName MyType... Get-ChildItem | Select-DbaObject Name, Length, FullName, Used, LastWriteTime, Mode -TypeName MyType -ShowExcludeProperty Mode, Used Lists all items in the current path, selects the properties specified (whether they exist or not) , then ... Sets the name to \"MyType\" Hides the properties \"Mode\" and \"Used\" from the default display set, causing them to be hidden from default view Optional Parameters -Alias | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeProperty | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExpandProperty | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -First | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Index | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -KeepInputObject | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Last | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Property | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ScriptMethod | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ScriptProperty | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ShowExcludeProperty | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ShowProperty | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Skip | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SkipLast | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TypeName | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Unique | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Wait | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | &nbsp;"
  },
  {
    "name": "Set-DbaAgentAlert",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "alert"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAgentAlert",
    "popularityRank": 369,
    "synopsis": "Modifies properties of existing SQL Agent alerts including enabled status and name.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAgentAlert View Source Garry Bargsley (@gbargsley), garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies properties of existing SQL Agent alerts including enabled status and name. 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. Syntax Set-DbaAgentAlert [[-SqlInstance] ] [[-SqlCredential] ] [[-Alert] ] [[-NewName] ] [-Enabled] [-Disabled] [-Force] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Changes the alert to disabled PS C:\\> Set-DbaAgentAlert -SqlInstance sql1 -Alert 'Severity 025: Fatal Error' -Disabled Example 2: Changes multiple alerts to enabled PS C:\\> Set-DbaAgentAlert -SqlInstance sql1 -Alert 'Severity 025: Fatal Error', 'Error Number 825', 'Error Number 824' -Enabled Example 3: Changes multiple alerts to enabled on multiple servers PS C:\\> Set-DbaAgentAlert -SqlInstance sql1, sql2, sql3 -Alert 'Severity 025: Fatal Error', 'Error Number 825', 'Error Number 824' -Enabled Example 4: Doesn&#39;t Change the alert but shows what would happen PS C:\\> Set-DbaAgentAlert -SqlInstance sql1 -Alert 'Severity 025: Fatal Error' -Disabled -WhatIf Optional Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Alert Specifies the name(s) of the SQL Agent alerts to modify. Accepts multiple alert names for bulk operations. Use this when you need to update specific alerts by name across one or more instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NewName Sets a new name for the alert being modified. Only works when modifying a single alert. Use this when standardizing alert names across environments or fixing naming conventions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Enabled Enables the specified SQL Agent alert(s) by setting IsEnabled to true. Use this to reactivate alerts after maintenance or to ensure critical alerts are active across all instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Disabled Disables the specified SQL Agent alert(s) by setting IsEnabled to false. Use this during maintenance windows or to silence noisy alerts that are firing incorrectly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Bypasses confirmation prompts by setting ConfirmPreference to 'none'. Use this in automated scripts where you want to suppress interactive prompts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts SQL Agent alert objects from the pipeline, typically from Get-DbaAgentAlert. Use this when you want to filter alerts first, then modify the results in a pipeline operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.Alert Returns one Alert object for each alert that was modified. The returned objects include all properties from the Alert object with added connection context properties. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the alert IsEnabled: Boolean indicating if the alert is currently enabled NotificationMessage: The message sent when the alert fires AlertType: Type of alert (EventAlert, PerformanceConditionAlert, or TransactionLogAlert) Severity: The severity level that triggers this alert (if alert type is EventAlert) DatabaseName: The database name the alert applies to (if applicable) EventDescriptionKeyword: Keywords in the error message that trigger the alert LastOccurrenceDate: DateTime of the last time this alert was triggered OccurrenceCount: Number of times this alert has been triggered Additional properties available (from SMO Alert object): ID: Unique identifier for the alert CreateDate: DateTime when the alert was created DateLastModified: DateTime when the alert was last modified JobName: The SQL Agent job to execute when the alert fires PerformanceCondition: The performance condition that triggers the alert HasNotification: Boolean indicating if notification methods are configured All properties from the base SMO Alert object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Set-DbaAgentJob",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAgentJob",
    "popularityRank": 82,
    "synopsis": "Modifies existing SQL Server Agent job properties and notification settings.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAgentJob View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies existing SQL Server Agent job properties and notification settings. 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. Syntax Set-DbaAgentJob [[-SqlInstance] ] [[-SqlCredential] ] [[-Job] ] [[-Schedule] ] [[-ScheduleId] ] [[-NewName] ] [-Enabled] [-Disabled] [[-Description] ] [[-StartStepId] ] [[-Category] ] [[-OwnerLogin] ] [[-EventLogLevel] ] [[-EmailLevel] ] [[-NetsendLevel] ] [[-PageLevel] ] [[-EmailOperator] ] [[-NetsendOperator] ] [[-PageOperator] ] [[-DeleteLevel] ] [-Force] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Changes the job to disabled PS C:\\> Set-DbaAgentJob sql1 -Job Job1 -Disabled Example 2: Changes the owner of the job PS C:\\> Set-DbaAgentJob sql1 -Job Job1 -OwnerLogin user1 Example 3: Changes the job and sets the notification to write to the Windows Application event log on success PS C:\\> Set-DbaAgentJob -SqlInstance sql1 -Job Job1 -EventLogLevel OnSuccess Example 4: Changes the job and sets the notification to send an e-mail to the e-mail operator PS C:\\> Set-DbaAgentJob -SqlInstance sql1 -Job Job1 -EmailLevel OnFailure -EmailOperator dba Example 5: Changes multiple jobs to enabled PS C:\\> Set-DbaAgentJob -SqlInstance sql1 -Job Job1, Job2, Job3 -Enabled Example 6: Changes multiple jobs to enabled on multiple servers PS C:\\> Set-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job Job1, Job2, Job3 -Enabled Example 7: Doesn&#39;t Change the job but shows what would happen PS C:\\> Set-DbaAgentJob -SqlInstance sql1 -Job Job1 -Description 'Just another job' -Whatif Example 8: Changes a job with the name &quot;Job1&quot; on multiple servers to have another description PS C:\\> Set-DbaAgentJob -SqlInstance sql1, sql2, sql3 -Job 'Job One' -Description 'Job One' Example 9: Changes a job with the name &quot;Job1&quot; on multiple servers to have another description using pipe line PS C:\\> sql1, sql2, sql3 | Set-DbaAgentJob -Job Job1 -Description 'Job One' Optional Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies the name of the SQL Server Agent job to modify. Accepts wildcards and multiple job names. Use this to target specific jobs for configuration changes rather than modifying all jobs on an instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schedule Attaches existing shared schedules to the job by name. Accepts multiple schedule names. Use this when you need to assign predefined schedules to jobs without recreating scheduling logic. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ScheduleId Attaches existing shared schedules to the job by their numeric ID. Accepts multiple schedule IDs. Use this when you know the specific schedule ID numbers and want to avoid potential name conflicts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NewName Renames the job to the specified name. The new name must be unique within the SQL Server instance. Use this when standardizing job names across environments or fixing naming conventions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Enabled Enables the job so it can be executed by SQL Server Agent schedules or manual execution. Use this when reactivating disabled jobs or deploying jobs that should run immediately. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Disabled Disables the job to prevent it from running on schedule or manual execution. Use this when temporarily stopping jobs during maintenance windows or permanently deactivating obsolete jobs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Description Updates the job's description field with explanatory text about the job's purpose or functionality. Use this to document what the job does, when it should run, or special requirements for maintenance teams. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartStepId Sets which job step should execute first when the job runs. Must correspond to an existing step ID within the job. Use this when you need to change the job's execution flow or skip initial steps during testing or maintenance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Category Assigns the job to a specific job category for organizational purposes. Creates the category if it doesn't exist when used with -Force. Use this to group related jobs together for easier management and reporting in SQL Server Management Studio. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OwnerLogin Changes the job owner to the specified SQL Server login. The login must already exist on the instance. Use this when reassigning job ownership for security compliance or when the current owner login is being removed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EventLogLevel Controls when job execution results are logged to the Windows Application Event Log. Values: Never, OnSuccess, OnFailure, Always (or 0-3). Use this to integrate job monitoring with Windows event log monitoring systems or reduce log noise by only logging failures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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). Must be used with EmailOperator parameter. Use this to set up automated job failure notifications to the DBA team. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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). Must be used with NetsendOperator parameter. Note that net send is deprecated and rarely used in modern environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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). Must be used with PageOperator parameter. Use this for critical jobs requiring immediate attention when they fail. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this to assign job failure notifications to specific DBA team members or distribution lists. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NetsendOperator Specifies which SQL Server Agent operator receives network messages when NetsendLevel conditions are met. The operator must already exist. Rarely used in modern environments due to the deprecation of the net send functionality. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PageOperator Specifies which SQL Server Agent operator receives pager notifications when PageLevel conditions are met. The operator must already exist. Use this for high-priority jobs where immediate mobile notification is required for on-call DBAs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DeleteLevel Controls when the job should automatically delete itself after execution. Values: Never, OnSuccess, OnFailure, Always (or 0-3). Use this for one-time jobs like data migrations or temporary maintenance tasks that should clean up after completion. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 0,Never,1,OnSuccess,2,OnFailure,3,Always | -Force Bypasses validation checks and creates missing job categories when specified with the Category parameter. Use this when you want to create new categories during job updates without having to pre-create them separately. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts SQL Server Agent job objects from the pipeline, typically from Get-DbaAgentJob output. Use this to chain job operations together or when working with job objects retrieved from other dbatools commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.Job Returns one modified SQL Server Agent job object per job that was successfully updated. The returned object reflects all changes applied during the modification operation. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the SQL Server Agent job Enabled: Boolean indicating if the job is enabled for execution Description: Description of the job's purpose Owner: SQL Server login that owns the job Category: The job category name for organizational grouping CurrentRunStatus: Current execution status of the job (Idle, Running, Succeeded, Failed, etc.) LastRunDate: DateTime of the most recent job execution attempt LastRunOutcome: Outcome of the last execution (Succeeded, Failed, Retry, Cancelled) NextRunDate: DateTime when the job is scheduled to run next EventLogLevel: Setting for Windows event log notifications (Never, OnSuccess, OnFailure, Always) Additional properties available (from SMO Job object): ID: Unique identifier for the job JobID: The globally unique identifier (GUID) for the job StartStepID: The ID of the step that executes first OwnerLoginName: Login name of the job owner OperatorToEmail: Email operator for notifications OperatorToNetSend: Net send operator for notifications OperatorToPage: Pager operator for notifications EmailLevel: Email notification setting (0-3 or string equivalent) NetSendLevel: Net send notification setting (0-3 or string equivalent) PageLevel: Pager notification setting (0-3 or string equivalent) DeleteLevel: Auto-delete setting after execution (0-3 or string equivalent) DatabaseName: Default database for job steps IsSystemObject: Boolean indicating if this is a system-created job CreatedDate: DateTime when the job was created CreateByLogin: Login that created the job DateLastModified: DateTime of the most recent modification ModifiedByLogin: Login that made the last modification JobSteps: Collection of job steps in this job Schedules: Collection of schedules assigned to this job All properties from the base SMO Job object are accessible using Select-Object * even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Set-DbaAgentJobCategory",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "jobcategory"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAgentJobCategory",
    "popularityRank": 605,
    "synopsis": "Renames SQL Server Agent job categories to standardize naming conventions across instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAgentJobCategory View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Renames SQL Server Agent job categories to standardize naming conventions across instances. 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. Syntax Set-DbaAgentJobCategory [-SqlInstance] [[-SqlCredential] ] [[-Category] ] [[-NewName] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Change the name of the category from &#39;Category 1&#39; to &#39;Category 2&#39; PS C:\\> New-DbaAgentJobCategory -SqlInstance sql1 -Category 'Category 1' -NewName 'Category 2' Example 2: Rename multiple jobs in one go on multiple servers PS C:\\> Set-DbaAgentJobCategory -SqlInstance sql1, sql2 -Category Category1, Category2 -NewName cat1, cat2 Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Category Specifies the existing job category name(s) to rename. The category must already exist in the SQL Server Agent on the target instance. Use this to identify which job categories need standardized naming across your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NewName Specifies the new name(s) for the job category. The new name cannot already exist on the target instance. When renaming multiple categories, provide names in the same order as the Category parameter values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Bypasses confirmation prompts and performs the rename operation without asking for user confirmation. Use this when scripting bulk category renames where manual confirmation would be impractical. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.JobCategory Returns one job category object per successfully renamed category. The returned object represents the renamed SQL Server Agent job category with updated properties. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the job category ID: The unique identifier for the job category CategoryType: The type of category (LocalJob, MultiServerJob, or DatabaseMaintenance) Additional properties available (from SMO JobCategory object): Urn: The Uniform Resource Name of the job category object State: The current state of the SMO object (Existing, Creating, Pending, Dropping) All properties from the base SMO JobCategory object are accessible using Select-Object * even though only default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Set-DbaAgentJobOutputFile",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "sqlagent"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAgentJobOutputFile",
    "popularityRank": 560,
    "synopsis": "Configures the output file path for SQL Server Agent job steps to capture step execution logs.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAgentJobOutputFile View Source Rob Sewell, sqldbawithabeard.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures the output file path for SQL Server Agent job steps to capture step execution logs. 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. Syntax Set-DbaAgentJobOutputFile [-SqlInstance] [-SqlCredential ] [-Job ] [-Step ] -OutputFile [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the Job step for The Agent job on SERVERNAME to E:\\Logs\\AgentJobStepOutput.txt PS C:\\> Set-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Job 'The Agent Job' -OutPutFile E:\\Logs\\AgentJobStepOutput.txt Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | -OutputFile Specifies the complete file path where SQL Agent should write job step execution output and error messages. Use 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 extension. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For 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 connection instead of a SQL login, ensure it contains a backslash. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | -Job Specifies the SQL Server Agent job name whose step output files you want to configure. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Step Specifies which job step(s) within the target job should have their output file configured. Use 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 job has multiple steps, an interactive GUI will appear for step selection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Job: The SQL Agent job name containing the step JobStep: The name of the job step that was updated OutputFileName: The new output file path that was set OldOutputFileName: The previous output file path before the change &nbsp;"
  },
  {
    "name": "Set-DbaAgentJobOwner",
    "description": "This function standardizes SQL Agent job ownership by updating jobs that don't match a specified owner login. It's 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 'sa' account (or the renamed sysadmin account if 'sa' was renamed), but you can specify any valid login. The function automatically detects renamed 'sa' 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",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAgentJobOwner",
    "popularityRank": 372,
    "synopsis": "Updates SQL Server Agent job ownership to ensure jobs are owned by a specific login",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAgentJobOwner View Source Michael Fal (@Mike_Fal), mikefal.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Updates SQL Server Agent job ownership to ensure jobs are owned by a specific login Description This function standardizes SQL Agent job ownership by updating jobs that don't match a specified owner login. It's commonly used for security compliance, post-migration cleanup, and environment standardization where consistent job ownership is required. By default, jobs are reassigned to the 'sa' account (or the renamed sysadmin account if 'sa' was renamed), but you can specify any valid login. The function automatically detects renamed 'sa' accounts by finding the login with ID 1. Only 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. Jobs already owned by the target login are skipped, and detailed status information is returned for each job processed. Best practice reference: https://www.itprotoday.com/sql-server-tip-assign-ownership-jobs-sysadmin-account Syntax Set-DbaAgentJobOwner [[-SqlInstance] ] [[-SqlCredential] ] [[-Job] ] [[-ExcludeJob] ] [[-InputObject] ] [[-Login] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets SQL Agent Job owner to sa on all jobs where the owner does not match sa PS C:\\> Set-DbaAgentJobOwner -SqlInstance localhost Example 2: Sets SQL Agent Job owner to &#39;DOMAIN\\account&#39; on all jobs where the owner does not match &#39;DOMAIN\\account&#39; PS C:\\> Set-DbaAgentJobOwner -SqlInstance localhost -Login DOMAIN\\account Sets SQL Agent Job owner to 'DOMAIN\\account' on all jobs where the owner does not match 'DOMAIN\\account'. Note that Login must be a valid security principal that exists on the target server. Example 3: Sets SQL Agent Job owner to &#39;sa&#39; on the job1 and job2 jobs if their current owner does not match &#39;sa&#39; PS C:\\> Set-DbaAgentJobOwner -SqlInstance localhost -Job job1, job2 Example 4: Sets SQL Agent Job owner to sa on all jobs where the owner does not match sa on both sqlserver and sql2016 PS C:\\> 'sqlserver','sql2016' | Set-DbaAgentJobOwner Example 5: Sets SQL Agent Job owner to login2 where their current owner is login1 on instance vmsql PS C:\\> Get-DbaAgentJob -SqlInstance vmsql | Where-Object OwnerLoginName -eq login1 | Set-DbaAgentJobOwner -TargetLogin login2 | Out-Gridview Sets SQL Agent Job owner to login2 where their current owner is login1 on instance vmsql. Send result to gridview. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies which SQL Agent jobs to update ownership for. Accepts job names as strings and supports tab completion from the target server. Use this when you need to update ownership for specific jobs rather than processing all jobs on the instance. | Property | Value | | --- | --- | | Alias | Jobs | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJob Specifies SQL Agent jobs to skip during the ownership update process. Accepts job names as strings with tab completion. Useful for excluding critical jobs or jobs that must retain their current ownership for security or operational reasons. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts SQL Agent job objects from the pipeline, typically from Get-DbaAgentJob output. Use this for advanced filtering scenarios where you need to process jobs based on complex criteria like owner, category, or schedule properties. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Login Specifies the target login account that should own the SQL Agent jobs. Defaults to 'sa' or automatically detects the renamed sysadmin account (login ID 1). Must 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. | Property | Value | | --- | --- | | Alias | TargetLogin | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.Job Returns one Job object per SQL Agent job processed, with added connection context and operation status information. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The SQL Agent job name Category: The job category OwnerLoginName: The login name that owns the job (updated if operation was successful) Status: Operation result status (Skipped, Failed, or Successful) Notes: Additional information about the operation result (reason for skip/failure, empty on success) All 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 information. &nbsp;"
  },
  {
    "name": "Set-DbaAgentJobStep",
    "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",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "jobstep"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAgentJobStep",
    "popularityRank": 215,
    "synopsis": "Modifies properties of existing SQL Agent job steps or creates new ones with Force parameter.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAgentJobStep View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies properties of existing SQL Agent job steps or creates new ones with Force parameter. 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. Common 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. Note: 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 Syntax Set-DbaAgentJobStep [[-SqlInstance] ] [[-SqlCredential] ] [[-Job] ] [[-StepName] ] [[-NewName] ] [[-Subsystem] ] [[-SubsystemServer] ] [[-Command] ] [[-CmdExecSuccessCode] ] [[-OnSuccessAction] ] [[-OnSuccessStepId] ] [[-OnFailAction] ] [[-OnFailStepId] ] [[-Database] ] [[-DatabaseUser] ] [[-RetryAttempts] ] [[-RetryInterval] ] [[-OutputFileName] ] [[-Flag] ] [[-ProxyName] ] [[-InputObject] ] [-EnableException] [-Force] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Changes the name of the step in &quot;Job1&quot; with the name Step1 to Step2 PS C:\\> Set-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -NewName Step2 Example 2: Changes the database of the step in &quot;Job1&quot; with the name Step1 to msdb PS C:\\> Set-DbaAgentJobStep -SqlInstance sql1 -Job Job1 -StepName Step1 -Database msdb Example 3: Changes job steps in multiple jobs with the name Step1 to msdb PS C:\\> Set-DbaAgentJobStep -SqlInstance sql1 -Job Job1, Job2 -StepName Step1 -Database msdb Example 4: Changes job steps in multiple jobs on multiple servers with the name Step1 to msdb PS C:\\> Set-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1, Job2 -StepName Step1 -Database msdb Example 5: Changes the database of the step in &quot;Job1&quot; with the name Step1 to msdb for multiple servers PS C:\\> Set-DbaAgentJobStep -SqlInstance sql1, sql2, sql3 -Job Job1 -StepName Step1 -Database msdb Example 6: Changes the database of the step in &quot;Job1&quot; with the name Step1 to msdb for multiple servers using pipeline PS C:\\> sql1, sql2, sql3 | Set-DbaAgentJobStep -Job Job1 -StepName Step1 -Database msdb Example 7: SqlInstance = sqldev01 Job = dbatools1 StepName = &quot;Step 2&quot; Subsystem = &quot;CmdExec&quot; Command = &quot;enter command... PS C:\\> $jobStep = @{ PS C:\\> $newJobStep = Set-DbaAgentJobStep @jobStep SqlInstance = sqldev01 Job = dbatools1 StepName = \"Step 2\" Subsystem = \"CmdExec\" Command = \"enter command text here\" CmdExecSuccessCode = 0 OnSuccessAction = \"GoToStep\" OnSuccessStepId = 1 OnFailAction = \"GoToStep\" OnFailStepId = 1 Database = TestDB RetryAttempts = 2 RetryInterval = 5 OutputFileName = \"logCmdExec.txt\" Flag = [Microsoft.SqlServer.Management.Smo.Agent.JobStepFlags]::AppendAllCmdExecOutputToJobHistory ProxyName = \"dbatoolsci_proxy_1\" Force = $true } Updates 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. Optional Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job The name of the job or the job object itself. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StepName The name of the step. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NewName The new name for the step in case it needs to be renamed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Subsystem The subsystem used by the SQL Server Agent service to execute command. Allowed values 'ActiveScripting','AnalysisCommand','AnalysisQuery','CmdExec','Distribution','LogReader','Merge','PowerShell','QueueReader','Snapshot','Ssis','TransactSql' | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | ActiveScripting,AnalysisCommand,AnalysisQuery,CmdExec,Distribution,LogReader,Merge,PowerShell,QueueReader,Snapshot,Ssis,TransactSql | -SubsystemServer The subsystems AnalysisScripting, AnalysisCommand, AnalysisQuery require a server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Command The commands to be executed by the SQLServerAgent service through the subsystem. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CmdExecSuccessCode The value returned by a CmdExec subsystem command to indicate that command executed successfully. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -OnSuccessAction The action to perform if the step succeeds. Allowed values \"QuitWithSuccess\" (default), \"QuitWithFailure\", \"GoToNextStep\", \"GoToStep\". The text value van either be lowercase, uppercase or something in between as long as the text is correct. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | QuitWithSuccess,QuitWithFailure,GoToNextStep,GoToStep | -OnSuccessStepId The ID of the step in this job to execute if the step succeeds and OnSuccessAction is \"GoToNextStep\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -OnFailAction The action to perform if the step fails. Allowed values \"QuitWithFailure\" (default), \"QuitWithSuccess\", \"GoToNextStep\", \"GoToStep\". The text value van either be lowercase, uppercase or something in between as long as the text is correct. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | QuitWithSuccess,QuitWithFailure,GoToNextStep,GoToStep | -OnFailStepId The ID of the step in this job to execute if the step fails and OnFailAction is \"GoToNextStep\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Database The name of the database in which to execute a Transact-SQL step. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DatabaseUser The name of the user account to use when executing a Transact-SQL step. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RetryAttempts The number of retry attempts to use if this step fails. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RetryInterval The amount of time in minutes between retry attempts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -OutputFileName The name of the file in which the output of this step is saved. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Flag Sets the flag(s) for the job step. Flag Description ---------------------------------------------------------------------------- AppendAllCmdExecOutputToJobHistory Job history, including command output, is appended to the job history file. AppendToJobHistory Job history is appended to the job history file. AppendToLogFile Job history is appended to the SQL Server log file. AppendToTableLog Job history is appended to a log table. LogToTableWithOverwrite Job history is written to a log table, overwriting previous contents. None Job history is not appended to a file. ProvideStopProcessEvent Job processing is stopped. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | AppendAllCmdExecOutputToJobHistory,AppendToJobHistory,AppendToLogFile,AppendToTableLog,LogToTableWithOverwrite,None,ProvideStopProcessEvent | -ProxyName The name of the proxy that the job step runs as. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Allows pipeline input from Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force The force parameter will ignore some errors in the parameters and assume defaults. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.JobStep Returns 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. When using -Force, creates new job steps if they don't exist. When updating existing steps, returns the modified JobStep with all changes applied. All SMO JobStep object properties are accessible and reflect the modifications made by this function, including: Name: Job step name ID: Job step ID within the job Subsystem: Type of subsystem used (TransactSql, CmdExec, PowerShell, Ssis, etc.) Command: Command or script to execute DatabaseName: Database context for T-SQL steps DatabaseUserName: User account for T-SQL step execution CommandExecutionSuccessCode: Expected return code for success (CmdExec subsystem) OnSuccessAction: Action to perform if step succeeds (QuitWithSuccess, QuitWithFailure, GoToNextStep, GoToStep) OnSuccessStep: Target step ID for GoToStep success action OnFailAction: Action to perform if step fails (QuitWithFailure, QuitWithSuccess, GoToNextStep, GoToStep) OnFailStep: Target step ID for GoToStep failure action RetryAttempts: Number of retry attempts on failure RetryInterval: Minutes between retry attempts OutputFileName: File path for step output ProxyName: SQL Agent proxy account name JobStepFlags: Output flags (AppendToJobHistory, AppendToLogFile, etc.) CreateDate: DateTime when step was created LastModifiedDate: DateTime when step was last modified &nbsp;"
  },
  {
    "name": "Set-DbaAgentOperator",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "operator"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAgentOperator",
    "popularityRank": 469,
    "synopsis": "Modifies existing SQL Agent operator contact details, pager schedules, and failsafe settings.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAgentOperator View Source Tracy Boggiano (@TracyBoggiano), databasesuperhero.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies existing SQL Agent operator contact details, pager schedules, and failsafe settings. 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. Syntax Set-DbaAgentOperator [[-SqlInstance] ] [[-SqlCredential] ] [[-Operator] ] [[-Name] ] [[-EmailAddress] ] [[-NetSendAddress] ] [[-PagerAddress] ] [[-PagerDay] ] [[-SaturdayStartTime] ] [[-SaturdayEndTime] ] [[-SundayStartTime] ] [[-SundayEndTime] ] [[-WeekdayStartTime] ] [[-WeekdayEndTime] ] [-IsFailsafeOperator] [[-FailsafeNotificationMethod] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: This sets the operator named DBA with the above email address with default values to alerts everyday for all... PS C:\\> Set-DbaAgentOperator -SqlInstance sql01 -Operator DBA -EmailAddress operator@operator.com -PagerDay Everyday This sets the operator named DBA with the above email address with default values to alerts everyday for all hours of the day. Example 2: Creates a new operator named DBA on the sql01 instance with email address operator@operator.com, net send... PS C:\\> Set-DbaAgentOperator -SqlInstance sql01 -Operator DBA -EmailAddress operator@operator.com ` >> -NetSendAddress dbauser1 -PagerAddress dbauser1@pager.dbatools.io -PagerDay Everyday ` >> -SaturdayStartTime 070000 -SaturdayEndTime 180000 -SundayStartTime 080000 ` >> -SundayEndTime 170000 -WeekdayStartTime 060000 -WeekdayEndTime 190000 Creates 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, Saturday 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. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Name Renames the operator to the specified value. Use this when you need to change an operator's name while preserving all other settings and alert assignments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PagerDay Controls which days pager notifications are active for this operator. Use 'Weekdays' for business hours coverage, 'Weekend' for off-hours support, or specific days for rotating on-call schedules. Valid values are 'EveryDay', 'Weekdays', 'Weekend', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', and 'Saturday'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | EveryDay,Weekdays,Weekend,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday | -SaturdayStartTime Sets when pager notifications begin on Saturday in HHMMSS format (e.g., '080000' for 8:00 AM). Use this to define weekend on-call coverage hours for the operator. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SaturdayEndTime Sets when pager notifications end on Saturday in HHMMSS format (e.g., '180000' for 6:00 PM). Notifications outside this window will use email instead of pager for the operator. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SundayStartTime Sets when pager notifications begin on Sunday in HHMMSS format (e.g., '080000' for 8:00 AM). Use this to define weekend on-call coverage hours for the operator. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SundayEndTime Sets when pager notifications end on Sunday in HHMMSS format (e.g., '170000' for 5:00 PM). Notifications outside this window will use email instead of pager for the operator. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -WeekdayStartTime Sets when pager notifications begin on weekdays (Monday-Friday) in HHMMSS format (e.g., '060000' for 6:00 AM). Use this to define business hours pager coverage for the operator. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -WeekdayEndTime Sets when pager notifications end on weekdays (Monday-Friday) in HHMMSS format (e.g., '190000' for 7:00 PM). Notifications outside this window will use email instead of pager for the operator. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 existing failsafe operator. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FailsafeNotificationMethod Specifies how the failsafe operator receives notifications when primary operators cannot be reached. Use 'NotifyEmail' for standard alerts, 'Pager' for urgent notifications, or 'NotifyAll' for maximum coverage. Valid values are 'None', 'NotifyEmail', 'Pager', 'NetSend', 'NotifyAll'. Multiple methods can be combined except 'None' and 'NotifyAll' which must be used alone. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | NotifyEmail | | Accepted Values | 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.Operator Returns one modified Operator object for each operator updated. The object is returned after all changes have been committed to the SQL Server instance. All SMO Operator object properties are accessible and reflect the modifications made by this function, including: EmailAddress: Email address for notifications NetSendAddress: Network computer name for net send notifications PagerAddress: Pager email address for urgent notifications PagerDays: Bitmask value indicating days pager is active SaturdayPagerStartTime: Time when Saturday pager notifications begin (HH:MM:SS format) SaturdayPagerEndTime: Time when Saturday pager notifications end (HH:MM:SS format) SundayPagerStartTime: Time when Sunday pager notifications begin (HH:MM:SS format) SundayPagerEndTime: Time when Sunday pager notifications end (HH:MM:SS format) WeekdayPagerStartTime: Time when weekday pager notifications begin (HH:MM:SS format) WeekdayPagerEndTime: Time when weekday pager notifications end (HH:MM:SS format) Name: Operator name LastNotificationTime: DateTime of last operator notification ID: Unique operator identifier &nbsp;"
  },
  {
    "name": "Set-DbaAgentSchedule",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "jobstep"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAgentSchedule",
    "popularityRank": 233,
    "synopsis": "Modifies properties of existing SQL Agent job schedules",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAgentSchedule View Source Sander Stad (@sqlstad, sqlstad.nl) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies properties of existing SQL Agent job schedules 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. Syntax Set-DbaAgentSchedule [-SqlInstance] [[-SqlCredential] ] [-Job] [-Schedule] [[-NewName] ] [-Enabled] [-Disabled] [[-FrequencyType] ] [[-FrequencyInterval] ] [[-FrequencySubdayType] ] [[-FrequencySubdayInterval] ] [[-FrequencyRelativeInterval] ] [[-FrequencyRecurrenceFactor] ] [[-StartDate] ] [[-EndDate] ] [[-StartTime] ] [[-EndTime] ] [-EnableException] [-Force] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Changes the schedule for Job1 with the name &#39;daily&#39; to enabled PS C:\\> Set-DbaAgentSchedule -SqlInstance sql1 -Job Job1 -Schedule daily -Enabled Example 2: Changes the schedule for Job1 with the name daily to have a new name weekly PS C:\\> Set-DbaAgentSchedule -SqlInstance sql1 -Job Job1 -Schedule daily -NewName weekly -FrequencyType Weekly -FrequencyInterval Monday, Wednesday, Friday Example 3: Changes the start time of the schedule for Job1 to 11 PM for multiple jobs PS C:\\> Set-DbaAgentSchedule -SqlInstance sql1 -Job Job1, Job2, Job3 -Schedule daily -StartTime '230000' Example 4: Changes the schedule for Job1 with the name daily to enabled on multiple servers PS C:\\> Set-DbaAgentSchedule -SqlInstance sql1, sql2, sql3 -Job Job1 -Schedule daily -Enabled Example 5: Changes the schedule for Job1 with the name &#39;daily&#39; to enabled on multiple servers using pipe line PS C:\\> sql1, sql2, sql3 | Set-DbaAgentSchedule -Job Job1 -Schedule daily -Enabled Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -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. Use this when you need to change schedule properties for specific jobs without affecting other jobs that might share the same schedule name. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Schedule Specifies the name of the existing schedule to modify within the specified job. Schedule names are case-sensitive. Use this to target the specific schedule when a job has multiple schedules attached to it. | Property | Value | | --- | --- | | Alias | ScheduleName | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NewName Renames the schedule to the specified new name. The new name must be unique within the job's schedules. Use this when you need to rename schedules for better organization or to follow naming conventions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Enabled Activates the schedule so the job will run according to its configured timing. This overrides any disabled state. Use this to reactivate schedules that were previously disabled without changing their timing configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Disabled Deactivates the schedule so the job will not run, even if it meets the timing criteria. The schedule configuration remains unchanged. Use this to temporarily stop jobs without deleting their schedules during maintenance windows or troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use 'Daily' for jobs that run every day or every few days, 'Weekly' for jobs on specific weekdays, 'Monthly' for jobs on specific dates, 'MonthlyRelative' for jobs like \"first Monday of the month\", 'Once' for one-time execution, 'AgentStart' to run when SQL Agent starts, or 'OnIdle' when server is idle. This parameter works with FrequencyInterval to create the complete schedule pattern. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. For 'Daily': Use a number (1-365) for every N days or 'EveryDay'. For 'Weekly': Use day names like Monday, Tuesday or shortcuts like 'Weekdays', 'Weekend'. For 'Monthly': Use day numbers 1-31. For 'MonthlyRelative': Use day names for \"first Monday\" type schedules. This parameter works together with FrequencyType to define the exact timing pattern for your job schedule. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FrequencySubdayType Defines the unit of time for running jobs multiple times within a single day. This controls what the FrequencySubdayInterval value represents. Use 'Once' for jobs that run only once per day, 'Hours' for jobs that repeat every few hours, 'Minutes' for jobs that run every few minutes, or 'Seconds' for very frequent execution. This parameter is only relevant when you need jobs to execute more than once per day at regular intervals. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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 'Hours' means every 2 hours. Use 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. Valid ranges are 1-59 for seconds/minutes and 1-23 for hours. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this for schedules like \"first Monday of every month\" (First + Monday) or \"last Friday of every month\" (Last + Friday). Only applies when FrequencyType is 'MonthlyRelative'. Common values are 'First', 'Second', 'Third', 'Fourth', or 'Last'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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's the number of months. Use 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 MonthlyRelative frequency types. Must be at least 1, and is commonly used for less frequent maintenance tasks or reports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -StartDate Sets the earliest date when the schedule becomes active and the job can start running. Must be in yyyyMMdd format (e.g., '20240315'). Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartTime Sets the daily start time when the job can begin executing, using 24-hour format HHMMSS (e.g., '080000' for 8:00 AM, '143000' for 2:30 PM). Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EndTime Sets the daily end time when the job can no longer start executing, using 24-hour format HHMMSS (e.g., '180000' for 6:00 PM, '235959' for just before midnight). Use 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't kill running jobs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Bypasses some parameter validation errors by applying sensible defaults and removes any existing schedules with the same name before creating new ones. Use this when you want to overwrite existing schedules or when working with edge cases where strict validation might prevent legitimate schedule modifications. Be cautious as this can remove existing schedules without prompting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.JobSchedule Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the schedule Enabled/IsEnabled: Boolean indicating if the schedule is active FrequencyTypes: Schedule frequency type (Once, Daily, Weekly, Monthly, MonthlyRelative, AgentStart, OnIdle) FrequencyInterval: The interval at which the schedule runs based on frequency type FrequencySubDayTypes: Sub-daily frequency unit (Once, Seconds, Minutes, Hours) FrequencySubDayInterval: Number of sub-daily frequency units between executions ActiveStartDate: The date when the schedule becomes active ActiveEndDate: The date when the schedule stops being active ActiveStartTimeOfDay: The daily start time for job execution ActiveEndTimeOfDay: The daily end time for job execution Additional properties available (from SMO JobSchedule object): ScheduleUid: Unique identifier for the schedule FrequencyRelativeIntervals: Relative frequency interval for monthly schedules (First, Second, Third, Fourth, Last) FrequencyRecurrenceFactor: Number of weeks or months between schedule occurrences JobCount: Number of jobs using this schedule Parent: Reference to the parent JobServer object Urn: The Uniform Resource Name of the schedule object CreateDate: DateTime when the schedule was created DateLastModified: DateTime when the schedule was last modified All properties from the base SMO JobSchedule object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Set-DbaAgentServer",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "server"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAgentServer",
    "popularityRank": 436,
    "synopsis": "Configures SQL Server Agent service properties and operational settings",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAgentServer View Source Claudio Silva (@claudioessilva), claudioessilva.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures SQL Server Agent service properties and operational settings 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. Syntax Set-DbaAgentServer [[-SqlInstance] ] [[-SqlCredential] ] [[-InputObject] ] [[-AgentLogLevel] ] [[-AgentMailType] ] [[-AgentShutdownWaitTime] ] [[-DatabaseMailProfile] ] [[-ErrorLogFile] ] [[-IdleCpuDuration] ] [[-IdleCpuPercentage] ] [[-CpuPolling] ] [[-LocalHostAlias] ] [[-LoginTimeout] ] [[-MaximumHistoryRows] ] [[-MaximumJobHistoryRows] ] [[-NetSendRecipient] ] [[-ReplaceAlertTokens] ] [[-SaveInSentFolder] ] [[-SqlAgentAutoStart] ] [[-SqlAgentMailProfile] ] [[-SqlAgentRestart] ] [[-SqlServerRestart] ] [[-WriteOemErrorLog] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Changes the job history retention to 10000 rows with an maximum of 100 rows per job PS C:\\> Set-DbaAgentServer -SqlInstance sql1 -MaximumHistoryRows 10000 -MaximumJobHistoryRows 100 Example 2: Enable the CPU Polling configurations PS C:\\> Set-DbaAgentServer -SqlInstance sql1 -CpuPolling Enabled Example 3: Set the agent log level to Errors and Warnings on multiple servers PS C:\\> Set-DbaAgentServer -SqlInstance sql1, sql2, sql3 -AgentLogLevel 'Errors, Warnings' Example 4: Disable the CPU Polling configurations PS C:\\> Set-DbaAgentServer -SqlInstance sql1 -CpuPolling Disabled Example 5: Set the max history limitations PS C:\\> Set-DbaAgentServer -SqlInstance sql1 -MaximumJobHistoryRows 1000 -MaximumHistoryRows 10000 Set 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 Example 6: Disable the max history limitations PS C:\\> Set-DbaAgentServer -SqlInstance sql1 -MaximumJobHistoryRows 0 -MaximumHistoryRows -1 Disable 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 Optional Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts SQL Server Agent JobServer objects from Get-DbaAgentServer for pipeline operations. Use this when you need to configure multiple agent servers from a filtered list or modify settings on specific instances already retrieved. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -AgentLogLevel Controls the verbosity of SQL Server Agent logging in the agent error log. Use 'Errors' for production environments to minimize log size, 'Errors, Warnings' for standard monitoring, or 'All' when troubleshooting agent job failures. Higher logging levels help diagnose job execution issues but increase log file growth. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use 'DatabaseMail' for modern installations as SQL Agent Mail is deprecated and requires MAPI configuration. Database Mail provides better security, reliability, and doesn't require Outlook or Exchange MAPI on the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 0,SqlAgentMail,1,DatabaseMail | -AgentShutdownWaitTime Sets how long (in seconds) SQL Server waits for SQL Server Agent to shut down during service restart. Increase this value if you have long-running jobs that need more time to complete gracefully during shutdown. Default is typically 15 seconds; values between 5-600 seconds are supported. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -DatabaseMailProfile Specifies which Database Mail profile SQL Server Agent uses for sending job notifications and alerts. The profile must already exist in the instance's Database Mail configuration before setting this value. Use this to ensure agent notifications use the correct SMTP settings and sender address for your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ErrorLogFile Sets the file path where SQL Server Agent writes its error log. Change this when you need agent logs stored in a specific location for centralized monitoring or compliance requirements. Ensure the SQL Server Agent service account has write permissions to the specified path. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IdleCpuDuration Defines how long (in seconds) the CPU must remain below the idle threshold before SQL Server Agent considers the server idle. Use this with CpuPolling to schedule jobs only when the server isn't busy with other workloads. Values range from 20 seconds to 24 hours (86400 seconds); typical values are 600-1800 seconds for production servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -IdleCpuPercentage Sets the CPU usage percentage threshold below which SQL Server Agent considers the server idle. Configure this to prevent resource-intensive maintenance jobs from running during peak usage periods. Values between 10-100 percent; commonly set to 10-25% for production servers to ensure adequate idle detection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -CpuPolling Enables or disables CPU idle condition monitoring for job scheduling. Enable this to allow jobs with idle CPU conditions to run only when server CPU usage is low. Useful for scheduling maintenance tasks like index rebuilds or backups that should avoid peak usage periods. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Enabled,Disabled | -LocalHostAlias Specifies an alias that SQL Server Agent uses to refer to the local server in job steps and notifications. Set this when the server has multiple network names or when you want job notifications to reference a specific hostname. Commonly used in clustered environments or when the server is accessed by different DNS names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LoginTimeout Sets the timeout (in seconds) for SQL Server Agent connections to SQL Server instances. Increase this value if agent jobs frequently fail due to connection timeouts, especially in slow network environments. Values range from 5-45 seconds; default is typically 30 seconds. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaximumHistoryRows Controls the total number of job history rows retained in MSDB before old entries are purged. Set this to prevent MSDB growth from excessive job history; typical values are 10000-100000 rows depending on job frequency. Use -1 to disable limits (not recommended for production) or work with MaximumJobHistoryRows to control per-job retention. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaximumJobHistoryRows Sets the maximum number of history rows retained per individual job. Prevents any single job from consuming too much history space; typical values are 100-1000 rows per job. Use 0 to disable per-job limits when MaximumHistoryRows is set to -1, or set both parameters to control overall history retention. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -NetSendRecipient Specifies the network recipient for legacy net send notifications from SQL Server Agent. This feature is deprecated and rarely used in modern environments; Database Mail is the preferred notification method. Only configure this if you have legacy monitoring systems that still rely on net send messages. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ReplaceAlertTokens Controls whether SQL Server Agent replaces tokens in alert notification messages with actual values. Enable this to include dynamic information like error details, job names, or server information in alert emails. Tokens like $(ESCAPE_SQUOTE(A-ERR)) get replaced with actual error text when notifications are sent. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Enabled,Disabled | -SaveInSentFolder Controls whether copies of agent notification emails are saved to the Database Mail sent items. Enable this for audit trails and troubleshooting notification delivery issues. Disable to reduce Database Mail storage usage if you don't need to track sent notifications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Enabled,Disabled | -SqlAgentAutoStart Controls whether SQL Server Agent service starts automatically when SQL Server starts. Enable this on production servers to ensure scheduled jobs and monitoring continue after server restarts. Disable only in development environments where automatic job execution isn't desired. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Enabled,Disabled | -SqlAgentMailProfile Specifies the legacy SQL Agent Mail profile for notifications (deprecated feature). Only used when AgentMailType is set to 'SqlAgentMail'; DatabaseMailProfile is preferred for modern installations. The profile must exist in the SQL Agent Mail configuration, which requires MAPI setup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlAgentRestart Controls whether SQL Server Agent automatically restarts if it stops unexpectedly. Enable this on production servers to ensure continuous job scheduling and monitoring after agent failures. The agent will attempt to restart itself if the service terminates abnormally. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Enabled,Disabled | -SqlServerRestart Controls whether SQL Server Agent can restart the SQL Server service if it stops unexpectedly. Enable this in environments where automatic SQL Server recovery is desired, but use caution on production systems. This setting allows the agent to restart the database engine service automatically. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Enabled,Disabled | -WriteOemErrorLog Controls whether SQL Server Agent writes errors to the Windows Application Event Log. Enable this to integrate agent errors with centralized Windows event monitoring and alerting systems. Useful for environments that rely on Windows Event Log for monitoring and don't use SQL-specific monitoring tools. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Enabled,Disabled | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.JobServer Returns the updated JobServer object for the modified instance(s). Properties include all SQL Server Agent configuration settings that were modified, plus any existing settings. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The SQL Server Agent service name AgentLogLevel: Current logging level (Errors, Warnings, etc.) DatabaseMailProfile: Active Database Mail profile for notifications SqlAgentAutoStart: Boolean indicating if Agent auto-starts SqlAgentRestart: Boolean indicating if Agent auto-restarts on failure Additional properties available (from SMO JobServer object): AgentMailType: Mail system type (DatabaseMail or SqlAgentMail) AgentShutdownWaitTime: Seconds to wait for Agent shutdown CpuPolling/IsCpuPollingEnabled: CPU idle monitoring enabled status ErrorLogFile: Path to Agent error log IdleCpuDuration: Seconds before considering CPU idle IdleCpuPercentage: CPU percentage threshold for idle LoginTimeout: Connection timeout in seconds MaximumHistoryRows: Maximum job history rows retained MaximumJobHistoryRows: Maximum history rows per job NetSendRecipient: Legacy net send notification recipient ReplaceAlertTokensEnabled: Token replacement in alerts enabled status SaveInSentFolder: Save notification copies to mail sent items SqlAgentMailProfile: Legacy SQL Agent Mail profile SqlServerRestart: Agent can restart SQL Server WriteOemErrorLog: Write errors to Windows Event Log All properties from the base SMO JobServer object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Set-DbaAgListener",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAgListener",
    "popularityRank": 382,
    "synopsis": "Modifies the port number for Availability Group listeners on SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAgListener View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies the port number for Availability Group listeners on SQL Server instances. 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. Syntax Set-DbaAgListener [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Listener] ] [-Port] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Changes the port for the SharePoint AG Listener on sql2017 PS C:\\> Set-DbaAgListener -SqlInstance sql2017 -AvailabilityGroup SharePoint -Port 14333 Changes the port for the SharePoint AG Listener on sql2017. Prompts for confirmation. Example 2: Changes the port for selected AG listeners to 1433 PS C:\\> Get-DbaAgListener -SqlInstance sql2017 | Out-GridView -Passthru | Set-DbaAgListener -Port 1433 -Confirm:$false Changes the port for selected AG listeners to 1433. Does not prompt for confirmation. Required Parameters -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. Commonly changed to standardize ports across environments, resolve conflicts with other services, or meet security requirements. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | 0 | Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies the name of the availability group containing the listener to modify. Required when using SqlInstance parameter. Use this to target specific availability groups when multiple groups exist on the same instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Listener Specifies the name of specific listeners to modify within the availability group. Optional parameter to target only certain listeners. Use this when an availability group has multiple listeners and you only want to change the port for specific ones. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group listener objects from the pipeline, typically from Get-DbaAgListener. Allows you to chain commands together. Use this approach when you want to filter or select specific listeners before modifying their ports. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityGroupListener Returns 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 number applied. Properties available on the returned object include: Name: The name of the availability group listener AvailabilityGroup: The name of the parent availability group PortNumber: The port number for client connections (modified by this command) IPAddress: The IP address for the listener SubnetMask: The subnet mask for the listener Parent: Reference to the parent AvailabilityGroup object All properties from the base SMO AvailabilityGroupListener object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Set-DbaAgReplica",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAgReplica",
    "popularityRank": 163,
    "synopsis": "Modifies configuration properties of existing availability group replicas.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAgReplica View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies configuration properties of existing availability group replicas. 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. Common 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. Syntax Set-DbaAgReplica [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Replica] ] [[-AvailabilityMode] ] [[-FailoverMode] ] [[-BackupPriority] ] [[-ConnectionModeInPrimaryRole] ] [[-ConnectionModeInSecondaryRole] ] [[-SeedingMode] ] [[-SessionTimeout] ] [[-EndpointUrl] ] [[-ReadonlyRoutingConnectionUrl] ] [[-ReadOnlyRoutingList] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the backup priority to 5000 for the sql2016 replica for the SharePoint availability group on sql2016 PS C:\\> Set-DbaAgReplica -SqlInstance sql2016 -Replica sql2016 -AvailabilityGroup SharePoint -BackupPriority 5000 Example 2: Sets the backup priority to 5000 for the selected availability groups PS C:\\> Get-DbaAgReplica -SqlInstance sql2016 | Out-GridView -Passthru | Set-DbaAgReplica -BackupPriority 5000 Example 3: Equivalent to running &quot;ALTER AVAILABILITY GROUP PS C:\\> Get-DbaAgReplica -SqlInstance sql2016 -Replica Replica1 | >> Set-DbaAgReplica -ReadOnlyRoutingList Replica2, Replica3 Equivalent to running \"ALTER AVAILABILITY GROUP... MODIFY REPLICA... (READ_ONLY_ROUTING_LIST = ('Replica2', 'Replica3'));\" Example 4: Equivalent to running &quot;ALTER AVAILABILITY GROUP PS C:\\> Get-DbaAgReplica -SqlInstance sql2016 -Replica Replica1 | >> Set-DbaAgReplica -ReadOnlyRoutingList @(,('Replica2','Replica3')); Equivalent to running \"ALTER AVAILABILITY GROUP... MODIFY REPLICA... (READ_ONLY_ROUTING_LIST = (('Replica2', 'Replica3')));\" setting a load balanced routing list for when Replica1 is the primary replica. Example 5: Complete example showing the prerequisites for read-only routing PS C:\\> # Complete read-only routing setup for a two-replica AG PS C:\\> # Step 1: Configure secondary replica to accept read-only connections PS C:\\> Set-DbaAgReplica -SqlInstance $primary -AvailabilityGroup MyAG -Replica Secondary1 -ConnectionModeInSecondaryRole AllowReadIntentConnectionsOnly PS C:\\> PS C:\\> # Step 2: Set the routing URL for each replica PS C:\\> Set-DbaAgReplica -SqlInstance $primary -AvailabilityGroup MyAG -Replica Primary1 -ReadonlyRoutingConnectionUrl \"TCP://Primary1:1433\" PS C:\\> Set-DbaAgReplica -SqlInstance $primary -AvailabilityGroup MyAG -Replica Secondary1 -ReadonlyRoutingConnectionUrl \"TCP://Secondary1:1433\" PS C:\\> PS C:\\> # Step 3: Set the routing list (which replicas receive read-only traffic when this replica is primary) PS C:\\> Set-DbaAgReplica -SqlInstance $primary -AvailabilityGroup MyAG -Replica Primary1 -ReadOnlyRoutingList Secondary1, Primary1 Complete example showing the prerequisites for read-only routing. The routing list specifies where to route read-intent connections when Primary1 is the primary replica. Note that all replicas in the routing list must have their ReadonlyRoutingConnectionUrl configured first. Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies the name of the availability group that contains the replica to modify. Required when using SqlInstance parameter to identify which availability group the replica belongs to. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Replica Specifies the name of the availability group replica to modify. This is the server instance name that hosts the replica. Use this when targeting a specific replica within an availability group for configuration changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityMode Controls the data synchronization mode between primary and secondary replicas. SynchronousCommit ensures zero data loss but may impact performance, while AsynchronousCommit prioritizes performance over guaranteed data protection. Change this when you need to balance performance requirements against data protection needs across different replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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 availability scenarios. Set to Manual when you want to control failover decisions or when using AsynchronousCommit replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this to control which replica should be preferred for automated backup jobs, with 0 excluding the replica from backup consideration entirely. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 read-write access. Typically left as AllowAllConnections unless you need to restrict read-only workloads from connecting to the primary. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | AllowAllConnections,AllowReadWriteConnections | -ConnectionModeInSecondaryRole Determines connection access when this replica is secondary. Options include AllowNoConnections, AllowReadIntentConnectionsOnly (for read-only workloads), or AllowAllConnections. Configure this to enable read-only workloads on secondary replicas for reporting or to completely block connections for backup-only replicas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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 requires traditional backup and restore operations. Choose Automatic for convenience and reduced administrative overhead, or Manual when you need control over backup/restore timing or have network bandwidth constraints. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Increase this value in high-latency network environments or decrease it when you need faster failure detection, keeping the 10-second minimum recommendation in mind. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EndpointUrl Specifies the URL endpoint used for data mirroring communication between replicas, typically in the format 'TCP://servername:port'. Update this when changing network configurations, server names, or port assignments for availability group communication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ReadonlyRoutingConnectionUrl Specifies the connection string used by the availability group listener to route read-only connections to this secondary replica. Required when setting up read-only routing to distribute read workloads across secondary replicas for load balancing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ReadOnlyRoutingList Defines the ordered list of secondary replicas that should receive read-only connections when this replica is primary. Accepts arrays for priority-based routing or nested arrays for load-balanced routing. IMPORTANT: Read-only routing requires proper setup: 1. The availability group must have at least two replicas (primary + secondary) 2. Target replicas must exist in the availability group 3. Secondary replicas must have ConnectionModeInSecondaryRole set to AllowReadIntentConnectionsOnly or AllowAllConnections 4. Each replica in the routing list must have ReadonlyRoutingConnectionUrl configured 5. An availability group listener is required for read-only routing to function For more information, see: https://learn.microsoft.com/sql/database-engine/availability-groups/windows/configure-read-only-routing-for-an-availability-group-sql-server | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group replica objects from Get-DbaAgReplica for pipeline operations. Use this to modify multiple replicas or when working with replica objects retrieved from previous commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityReplica Returns 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. Properties available on the returned object include: Name: The name of the availability replica (server instance name) AvailabilityGroup: The name of the parent availability group AvailabilityMode: Current availability mode (SynchronousCommit or AsynchronousCommit) FailoverMode: Current failover mode (Automatic, Manual, or External) BackupPriority: Backup priority value (0-100) ConnectionModeInPrimaryRole: Connection mode when this replica is primary ConnectionModeInSecondaryRole: Connection mode when this replica is secondary EndpointUrl: The endpoint URL for availability group communication ReadonlyRoutingConnectionUrl: The URL used for read-only routing SeedingMode: Database seeding mode (Automatic or Manual) SessionTimeout: Session timeout value in seconds Parent: Reference to the parent AvailabilityGroup object All properties from the base SMO AvailabilityReplica object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Set-DbaAvailabilityGroup",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaAvailabilityGroup",
    "popularityRank": 197,
    "synopsis": "Modifies availability group configuration settings including DTC support, backup preferences, and failover conditions",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaAvailabilityGroup View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies availability group configuration settings including DTC support, backup preferences, and failover conditions 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. Syntax Set-DbaAvailabilityGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [-AllAvailabilityGroups] [-DtcSupportEnabled] [[-ClusterType] ] [[-AutomatedBackupPreference] ] [[-FailureConditionLevel] ] [[-HealthCheckTimeout] ] [-BasicAvailabilityGroup] [-DatabaseHealthTrigger] [-IsDistributedAvailabilityGroup] [[-ClusterConnectionOption] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Enables DTC for all availability groups on sql2016 PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2016 | Set-DbaAvailabilityGroup -DtcSupportEnabled Example 2: Disables DTC support for the availability group AG1 PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 | Set-DbaAvailabilityGroup -DtcSupportEnabled:$false Example 3: Disables DTC support for the availability group AG1 PS C:\\> Set-DbaAvailabilityGroup -SqlInstance sql2016 -AvailabilityGroup AG1 -DtcSupportEnabled:$false Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies the name(s) of specific availability groups to modify. Accepts multiple AG names as an array. Use this to target individual AGs instead of modifying all AGs on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllAvailabilityGroups Modifies configuration settings for every availability group on the target SQL Server instance. Use this switch when you need to apply the same configuration changes across all AGs simultaneously. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DtcSupportEnabled Enables or disables Distributed Transaction Coordinator (DTC) support for the availability group. Required when applications use distributed transactions across multiple databases in the AG. Set to $false to disable DTC support. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ClusterType Specifies the clustering technology used by the availability group. Only supported in SQL Server 2017 and above. Use 'Wsfc' for Windows Server Failover Clustering, 'External' for third-party cluster managers like Pacemaker on Linux, or 'None' for read-scale AGs without automatic failover. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | External,Wsfc,None | -AutomatedBackupPreference Controls which replica should be preferred for automated backup operations within the availability group. Use 'Secondary' to offload backups from the primary, 'SecondaryOnly' to prevent backups on primary, 'Primary' to always backup on primary, or 'None' to disable preference-based backup routing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | None,Primary,Secondary,SecondaryOnly | -FailureConditionLevel Sets the sensitivity level for automatic failover conditions in the availability group. Use 'OnServerDown' for basic failover, 'OnServerUnresponsive' for SQL Service issues, 'OnCriticalServerErrors' for critical SQL errors, 'OnModerateServerErrors' for moderate SQL errors, or 'OnAnyQualifiedFailureCondition' for maximum sensitivity. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Increase this value for busy systems or slow storage to reduce false failovers. Decrease for faster failover detection in stable environments. Default is 30000 (30 seconds). Changes take effect immediately without restart. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BasicAvailabilityGroup Configures the availability group as a Basic AG with limited functionality for Standard Edition licensing. Basic AGs support only one database, two replicas, and no read-access to secondary replicas. Used when full AG features aren't needed or licensed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DatabaseHealthTrigger Enables database-level health monitoring that can trigger automatic failovers based on individual database health status. When enabled, databases that become offline or experience critical errors can initiate AG failover. Useful for comprehensive monitoring beyond SQL Server instance health. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IsDistributedAvailabilityGroup Configures the availability group as a Distributed AG that spans multiple WSFC clusters or standalone instances. Used for disaster recovery scenarios across geographic locations or different domains. Requires SQL Server 2016 or later. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ClusterConnectionOption Specifies connection options for TDS 8.0 support in SQL Server 2025 and above. This allows the Windows Server Failover Cluster (WSFC) to connect to SQL Server instances using ODBC with TLS 1.3 encryption. The value is a string containing semicolon-delimited key-value pairs. Available keys: Encrypt: Controls connection encryption TrustServerCertificate: Whether to trust the server certificate HostNameInCertificate: Expected hostname in the certificate ServerCertificate: Path to server certificate This setting is persisted by WSFC in the registry and used continuously for cluster-to-instance communication. Note: PowerShell does not validate these values - invalid combinations will be rejected by SMO or the ODBC driver. Example: \"Encrypt=Strict;TrustServerCertificate=False\" For detailed documentation, see: https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-availability-group-transact-sql | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline operations. Use this to pipe specific AG objects directly to the function instead of specifying SqlInstance and AG names separately. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityGroup Returns one AvailabilityGroup object per availability group that was modified. The object contains the updated configuration properties that were changed by this command. Default display properties (via Select-DefaultView): Name: Name of the availability group AvailabilityReplicas: Collection of replica instances in the AG AutomatedBackupPreference: Current backup preference (None, Primary, Secondary, SecondaryOnly) BasicAvailabilityGroup: Boolean indicating if the AG is a Basic AG (Standard Edition) ClusterType: Clustering technology used (Wsfc, External, None) - SQL Server 2017+ DatabaseHealthTrigger: Boolean indicating if database health triggers failover DtcSupportEnabled: Boolean indicating if Distributed Transaction Coordinator support is enabled FailureConditionLevel: Failover sensitivity level (OnServerDown, OnServerUnresponsive, OnCriticalServerErrors, OnModerateServerErrors, OnAnyQualifiedFailureCondition) HealthCheckTimeout: Health check timeout in milliseconds IsDistributedAvailabilityGroup: Boolean indicating if this is a Distributed AG (SQL Server 2016+) Additional properties available (from SMO AvailabilityGroup object): ClusterConnectionOptions: Connection options for WSFC communication (SQL Server 2025+) Parent: Reference to the parent SQL Server object Databases: Collection of databases in the AG ListenerIPAddresses: Collection of listener IP addresses AvailabilityGroupListeners: Collection of AG listeners CreateDate: DateTime when the AG was created LastModificationTime: DateTime when the AG was last modified Urn: The Unified Resource Name for the AG State: Current state of the SMO object (Existing, Creating, Pending, etc.) All properties from the base SMO AvailabilityGroup object are accessible using Select-Object * even though only default properties are displayed without that cmdlet. &nbsp;"
  },
  {
    "name": "Set-DbaCmConnection",
    "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.",
    "category": "Utilities",
    "tags": [
      "computermanagement",
      "cim"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaCmConnection",
    "popularityRank": 538,
    "synopsis": "Configures remote computer connection settings for SQL Server host management.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Set-DbaCmConnection View Source Friedrich Weinmann (@FredWeinmann) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures remote computer connection settings for SQL Server host management. Description Configures connection objects that dbatools uses to manage remote SQL Server host computers via CIM, WMI, and PowerShell remoting. This function creates new connection records for computers not yet cached, or modifies existing connection settings for previously contacted hosts. Use 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. Syntax Set-DbaCmConnection [-ComputerName ] [-Credential ] [-OverrideExplicitCredential] [-OverrideConnectionPolicy] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-WindowsCredentialsAreBad] [-CimWinRMOptions ] [-CimDCOMOptions ] [-AddBadCredential ] [-RemoveBadCredential ] [-ClearBadCredential] [-ClearCredential] [-ResetCredential] [-ResetConnectionStatus] [-ResetConfiguration] [-EnableException] [-WhatIf] [-Confirm] [ ] Set-DbaCmConnection [-ComputerName ] [-UseWindowsCredentials] [-OverrideExplicitCredential] [-OverrideConnectionPolicy] [-DisabledConnectionTypes {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-DisableBadCredentialCache] [-DisableCimPersistence] [-DisableCredentialAutoRegister] [-EnableCredentialFailover] [-CimWinRMOptions ] [-CimDCOMOptions ] [-AddBadCredential ] [-RemoveBadCredential ] [-ClearBadCredential] [-ClearCredential] [-ResetCredential] [-ResetConnectionStatus] [-ResetConfiguration] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Retrieves the already existing connection to sql2014, removes the list of not working credentials and... PS C:\\> Get-DbaCmConnection sql2014 | Set-DbaCmConnection -ClearBadCredential -UseWindowsCredentials Retrieves 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. Example 2: Removes the credentials stored in $cred from all connections&#39; list of &quot;known to not work&quot; credentials PS C:\\> Get-DbaCmConnection | Set-DbaCmConnection -RemoveBadCredential $cred Removes the credentials stored in $cred from all connections' list of \"known to not work\" credentials. Handy to update changes in privilege. Example 3: At first, the current cached connections are stored in an xml file PS C:\\> Get-DbaCmConnection | Export-Clixml .\\connections.xml PS C:\\> Import-Clixml .\\connections.xml | Set-DbaCmConnection -ResetConfiguration At 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 to the connection cache. In 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. In 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. Optional Parameters -ComputerName Specifies the SQL Server host computer name to configure connection settings for. Accepts computer names, FQDNs, or IP addresses. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential The credential to register. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -UseWindowsCredentials Confirms that Windows credentials of the current user should be used for remote connections to the target computer. Set this when you know the current user account has sufficient privileges on the remote SQL Server host and want to avoid credential prompts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -OverrideExplicitCredential Forces dbatools to use cached working credentials instead of explicitly provided credentials when available. Enable this when you want the connection system to automatically use known-good credentials rather than failing with explicitly provided but incorrect credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -OverrideConnectionPolicy Allows this connection to bypass global connection type restrictions configured in dbatools settings. Use this when you need to enable specific connection methods (CIM, WMI, PowerShell remoting) for individual computers that are normally disabled globally. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisabledConnectionTypes Specifies which connection protocols to disable for this computer (CIM, WMI, PowerShell remoting, or combinations). Use this to block problematic connection methods on specific hosts while allowing others to work normally. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | None | -DisableBadCredentialCache Prevents dbatools from remembering credentials that fail authentication for this computer. Enable this when you're frequently changing credentials or troubleshooting authentication issues and don't want failed attempts cached. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisableCimPersistence Forces dbatools to create new CIM sessions for each operation instead of reusing existing sessions. Use this when experiencing issues with persistent CIM connections or when you need fresh authentication for each operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisableCredentialAutoRegister Prevents successful credentials from being automatically saved to the connection cache for future use. Enable this for security-sensitive environments where you don't want credentials stored in memory between operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableCredentialFailover Allows dbatools to automatically try previously successful credentials when the provided credentials fail. Use this to improve connection reliability by falling back to known working credentials when new ones don't authenticate properly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WindowsCredentialsAreBad Marks the current user's Windows credentials as non-functional for this remote computer. Set this when you know Windows authentication won't work for the target host and want to prevent automatic attempts with current user credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CimWinRMOptions Specifies advanced WinRM session options for CIM connections, such as authentication methods, timeouts, or proxy settings. Create this object using New-CimSessionOption and use when you need custom WinRM configuration for challenging network environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CimDCOMOptions Specifies advanced DCOM session options for CIM connections, including authentication, impersonation levels, or DCOM-specific settings. Create this object using New-CimSessionOption and use when connecting through firewalls or when WinRM isn't available. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AddBadCredential Adds specific credentials to the list of known non-working credentials for this computer. Use this to prevent dbatools from attempting credentials you know will fail, improving performance and avoiding account lockouts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RemoveBadCredential Removes previously flagged credentials from the bad credential list for this computer. Use this when credentials that previously failed have been updated or permissions have been granted. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ClearBadCredential Removes all entries from the bad credential cache for this computer. Use this when troubleshooting authentication issues or after bulk credential updates that might affect previously failed credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ClearCredential Removes any cached working credentials for this computer, forcing fresh authentication on next connection. Use this when credentials have changed or when you need to ensure the next connection uses newly provided credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ResetCredential Performs a complete credential reset by clearing both working and failed credential caches and resetting Windows credential status. Use this for comprehensive credential troubleshooting or when starting fresh with connection authentication for a host. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ResetConnectionStatus Clears all connection protocol test results, marking CIM, WMI, and PowerShell remoting as untested for this computer. Use this to force dbatools to re-test connection methods after network changes, firewall updates, or service configuration changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ResetConfiguration Restores all connection behavior settings to system defaults, removing any computer-specific overrides. Use this to return a connection to standard behavior after testing custom settings or when troubleshooting connection issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Dataplat.Dbatools.Connection.ManagementConnection Returns 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 remoting operations. Default display properties: ComputerName: The name of the SQL Server host computer for which connection settings were configured IsConnected: Boolean indicating whether a successful connection to the remote computer has been established CimRM: Current status of CIM (WinRM) connectivity (Unknown, Connected, Failed, Untested) CimDCOM: Current status of CIM (DCOM) connectivity (Unknown, Connected, Failed, Untested) Wmi: Current status of WMI connectivity (Unknown, Connected, Failed, Untested) PowerShellRemoting: Current status of PowerShell remoting connectivity (Unknown, Connected, Failed, Untested) Additional properties available (from ManagementConnection object): Credentials: Currently cached credentials for this connection UseWindowsCredentials: Boolean indicating whether Windows credentials of the current user are configured WindowsCredentialsAreBad: Boolean indicating whether Windows credentials have been marked as non-functional KnownBadCredentials: Collection of credentials known to fail authentication OverrideExplicitCredential: Boolean indicating whether cached credentials override explicit parameters OverrideConnectionPolicy: Boolean indicating whether global connection policies are bypassed DisabledConnectionTypes: Connection protocols disabled for this computer DisableBadCredentialCache: Boolean indicating whether failed credentials are cached DisableCimPersistence: Boolean indicating whether CIM sessions are recreated each time DisableCredentialAutoRegister: Boolean indicating whether successful credentials are auto-cached EnableCredentialFailover: Boolean indicating whether credential failover is enabled CimWinRMOptions: WinRM session options for CIM connections CimDCOMOptions: DCOM session options for CIM connections LastCimRM: DateTime of last CIM (WinRM) connection attempt LastCimDCOM: DateTime of last CIM (DCOM) connection attempt LastWmi: DateTime of last WMI connection attempt LastPowerShellRemoting: DateTime of last PowerShell remoting connection attempt &nbsp;"
  },
  {
    "name": "Set-DbaDbCompatibility",
    "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.",
    "category": "Database Operations",
    "tags": [
      "compatibility",
      "database"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbCompatibility",
    "popularityRank": 152,
    "synopsis": "Changes database compatibility levels to match SQL Server instance version or specified target level.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbCompatibility View Source Garry Bargsley, blog.garrybargsley.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Changes database compatibility levels to match SQL Server instance version or specified target level. 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. Syntax Set-DbaDbCompatibility [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Compatibility] {Version60 | Version65 | Version70 | Version80 | Version90 | Version100 | Version110 | Version120 | Version130 | Version140 | Version150 | Version160 | Version170 | Version180}] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Changes database compatibility level for all user databases on server sql2017a that have a Compatibility... PS C:\\> Set-DbaDbCompatibility -SqlInstance sql2017a Changes database compatibility level for all user databases on server sql2017a that have a Compatibility level that do not match Example 2: Changes database compatibility level for all user databases on server sql2019a to Version150 PS C:\\> Set-DbaDbCompatibility -SqlInstance sql2019a -Compatibility Version150 Example 3: Changes database compatibility level for database Test on server sql2022b to Version160 PS C:\\> Set-DbaDbCompatibility -SqlInstance sql2022b -Database Test -Compatibility Version160 Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to update compatibility levels for. Accepts wildcards for pattern matching. When omitted, processes all user databases on the target instance, excluding system databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Compatibility Sets a specific target compatibility level for all processed databases. Must be a valid CompatibilityLevel enum value like Version160, Version150, etc. When omitted, automatically updates each database to match its SQL Server instance version, which is typically desired after SQL Server upgrades. Use this parameter when you need databases to remain at a specific compatibility level rather than matching the current server version. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from the pipeline, typically from Get-DbaDatabase or other dbatools functions. Use this when you need to apply compatibility level changes to a pre-filtered set of databases or when chaining multiple dbatools commands together. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts for confirmation of every step. For example: Are you sure you want to perform this action? Performing the operation \"Update database\" on target \"pubs on SQL2016\\VNEXT\". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"): | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database where the compatibility level was successfully changed. No output is generated for databases already at the target compatibility level. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database whose compatibility level was changed Compatibility: The new compatibility level applied to the database PreviousCompatibility: The compatibility level the database had before the change &nbsp;"
  },
  {
    "name": "Set-DbaDbCompression",
    "description": "Compresses tables, indexes, and heaps across one or more databases using Row, Page, or intelligent recommendations based on Microsoft's 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.",
    "category": "Database Operations",
    "tags": [
      "compression",
      "table",
      "database"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbCompression",
    "popularityRank": 344,
    "synopsis": "Applies data compression to SQL Server tables and indexes to reduce storage space and improve performance.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbCompression View Source Jason Squires (@js_0505), jstexasdba@gmail.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Applies data compression to SQL Server tables and indexes to reduce storage space and improve performance. Description Compresses tables, indexes, and heaps across one or more databases using Row, Page, or intelligent recommendations based on Microsoft's 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. Syntax Set-DbaDbCompression [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Table] ] [[-CompressionType] ] [[-MaxRunTime] ] [[-PercentCompression] ] [-ForceOfflineRebuilds] [-SortInTempDB] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Set the compression run time to 60 minutes and will start the compression of tables/indexes that have a... PS C:\\> Set-DbaDbCompression -SqlInstance localhost -MaxRunTime 60 -PercentCompression 25 Set 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. Example 2: Utilizes Page compression for tables table1 and table2 in DBName on ServerA with no time limit PS C:\\> Set-DbaDbCompression -SqlInstance ServerA -Database DBName -CompressionType Page -Table table1, table2 Example 3: Will compress tables/indexes within the specified database that would show any % improvement with compression... PS C:\\> Set-DbaDbCompression -SqlInstance ServerA -Database DBName -PercentCompression 25 | Out-GridView Will 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. Example 4: Gets the compression suggestions from Test-DbaDbCompression into a variable, this can then be reviewed and... PS C:\\> $testCompression = Test-DbaDbCompression -SqlInstance ServerA -Database DBName PS C:\\> Set-DbaDbCompression -SqlInstance ServerA -Database DBName -InputObject $testCompression Gets the compression suggestions from Test-DbaDbCompression into a variable, this can then be reviewed and passed into Set-DbaDbCompression. Example 5: Set the compression run time to 60 minutes and will start the compression of tables/indexes for all databases... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Set-DbaDbCompression -SqlInstance ServerA -ExcludeDatabase Database -SqlCredential $cred -MaxRunTime 60 -PercentCompression 25 Set 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 higher between current and recommended will be compressed. Example 6: Set the compression run time to 60 minutes and will start the compression of tables/indexes across all listed... PS C:\\> $servers = 'Server1','Server2' PS C:\\> foreach ($svr in $servers) { >> Set-DbaDbCompression -SqlInstance $svr -MaxRunTime 60 -PercentCompression 25 | Export-Csv -Path C:\\temp\\CompressionAnalysisPAC.csv -Append >> } Set 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 of command is exported to a csv. Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to apply compression to. Accepts wildcard patterns and multiple database names. When omitted, all non-system databases on the instance will be processed. Use this to target specific databases when you don't want to compress everything. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during the compression operation. Accepts wildcard patterns and multiple database names. Use this when you want to compress most databases but exclude specific ones like databases under maintenance or with special requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Specifies which tables to compress within the selected databases. Accepts multiple table names and works with wildcard patterns. When omitted, all eligible tables in the database will be processed. Use this to target specific large tables or avoid compressing certain tables. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CompressionType Specifies the type of compression to apply: Recommended, Page, Row, or None. Default is 'Recommended' which analyzes each object and applies the optimal compression type. Use 'Page' or 'Row' to force all objects to the same compression level, or 'None' to remove compression. Recommended is best for mixed workloads where different objects benefit from different compression types. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Recommended | | Accepted Values | 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. Use this during business hours to ensure the operation completes within a maintenance window. A value of 0 (default) means no time limit. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use 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 process. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SortInTempDB Specifies that intermediate sort operations during index rebuilds should use the tempdb database. This can speed up index creation and reduce space usage in the user database at the expense of tempdb. Use this switch when rebuilding large indexes to avoid filling the user database's log or data files. Requires sufficient space in tempdb for the sort operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts compression recommendations from Test-DbaDbCompression and applies those specific recommendations instead of running a new analysis. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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 AlreadyProcessed property indicating whether the recommendation was applied. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The database name Schema: The schema name containing the table TableName: The name of the table IndexName: The name of the index; null for heap partitions, contains index name for indexed partitions Partition: The partition number (1-based, or 1 for non-partitioned objects) IndexID: The index ID number - 0 for heaps, greater than 0 for indexes IndexType: The type of index structure (Heap, ClusteredIndex, or other SMO index type values) CompressionTypeRecommendation: The compression type that was applied (ROW, PAGE, or NONE in uppercase) AlreadyProcessed: A flag indicating if the object was successfully processed (True or False as string) PercentScan: Placeholder property from Test-DbaDbCompression analysis (always null in output) PercentUpdate: Placeholder property from Test-DbaDbCompression analysis (always null in output) RowEstimatePercentOriginal: Placeholder property from Test-DbaDbCompression analysis (always null in output) PageEstimatePercentOriginal: Placeholder property from Test-DbaDbCompression analysis (always null in output) SizeCurrent: Placeholder property from Test-DbaDbCompression analysis (always null in output) SizeRequested: Placeholder property from Test-DbaDbCompression analysis (always null in output) PercentCompression: Placeholder property from Test-DbaDbCompression analysis (always null in output) When using CompressionType parameter (Row, Page, or None), returns objects for each partition that was compressed. When using CompressionType Recommended (default), returns objects from Test-DbaDbCompression with the AlreadyProcessed property added. In Recommended mode, only objects with CompressionTypeRecommendation that is not 'NO_GAIN' or '?' and meets the PercentCompression threshold are output. &nbsp;"
  },
  {
    "name": "Set-DbaDbDataClassification",
    "description": "Creates or updates data classification metadata on table columns by setting four extended properties:\n- sys_information_type_id: GUID identifying the information type\n- sys_information_type_name: Human-readable information type name\n- sys_sensitivity_label_id: GUID identifying the sensitivity label\n- sys_sensitivity_label_name: Human-readable sensitivity label name\n\nThis command performs an upsert: if a classification property already exists on the column it will be\nupdated, otherwise it will be created. You can update only the information type, only the sensitivity\nlabel, or both at once.\n\nBuilt-in GUID mappings are provided for well-known Microsoft Information Protection types and labels.\nIf InformationType or SensitivityLabel matches a known value, the corresponding ID will be set\nautomatically. Custom values are also supported by providing both the name and ID explicitly.\n\nKnown Information Types: Networking, Contact Info, Credentials, Credit Card, Banking, Financial,\nOther, Name, National ID, SSN, Health, Date Of Birth\n\nKnown Sensitivity Labels: Public, General, Confidential, Confidential - GDPR, Highly Confidential,\nHighly Confidential - GDPR\n\nRequires SQL Server 2005 or later due to use of sp_addextendedproperty / sp_updateextendedproperty.",
    "category": "Utilities",
    "tags": [
      "dataclassification",
      "classification",
      "compliance",
      "security"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbDataClassification",
    "popularityRank": 0,
    "synopsis": "Adds or updates data classification labels on SQL Server table columns",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbDataClassification View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Adds or updates data classification labels on SQL Server table columns Description Creates or updates data classification metadata on table columns by setting four extended properties: sys_information_type_id: GUID identifying the information type sys_information_type_name: Human-readable information type name sys_sensitivity_label_id: GUID identifying the sensitivity label sys_sensitivity_label_name: Human-readable sensitivity label name This command performs an upsert: if a classification property already exists on the column it will be updated, otherwise it will be created. You can update only the information type, only the sensitivity label, or both at once. Built-in GUID mappings are provided for well-known Microsoft Information Protection types and labels. If InformationType or SensitivityLabel matches a known value, the corresponding ID will be set automatically. Custom values are also supported by providing both the name and ID explicitly. Known Information Types: Networking, Contact Info, Credentials, Credit Card, Banking, Financial, Other, Name, National ID, SSN, Health, Date Of Birth Known Sensitivity Labels: Public, General, Confidential, Confidential - GDPR, Highly Confidential, Highly Confidential - GDPR Requires SQL Server 2005 or later due to use of sp_addextendedproperty / sp_updateextendedproperty. Syntax Set-DbaDbDataClassification [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Schema] ] [[-Table] ] [[-Column] ] [[-InformationType] ] [[-InformationTypeId] ] [[-SensitivityLabel] ] [[-SensitivityLabelId] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the classification for the EmailAddress column in the Customer table of AdventureWorks PS C:\\> Set-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks -Table Customer -Column EmailAddress -InformationType \"Contact Info\" -SensitivityLabel \"Confidential\" Sets the classification for the EmailAddress column in the Customer table of AdventureWorks. The InformationTypeId and SensitivityLabelId are automatically populated from the built-in mapping. Example 2: &quot;Highly Confidential&quot; Sets classification for a column in a non-dbo schema PS C:\\> Set-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks -Schema HumanResources -Table Employee -Column NationalIDNumber -InformationType \"National ID\" -SensitivityLabel Example 3: Updates the sensitivity label to &quot;Highly Confidential&quot; for all classified columns in AdventureWorks, keeping... PS C:\\> Get-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks | Set-DbaDbDataClassification -SensitivityLabel \"Highly Confidential\" Updates the sensitivity label to \"Highly Confidential\" for all classified columns in AdventureWorks, keeping the information type unchanged. Example 4: &quot;D22FA6E9-5EE4-3BDE-4C2B-A409604C4646&quot; -SensitivityLabel &quot;Highly Confidential - GDPR&quot; -Confirm:$false Sets a... PS C:\\> Set-DbaDbDataClassification -SqlInstance sql2019 -Database AdventureWorks -Table Orders -Column CreditCardNumber -InformationType \"Credit Card\" -InformationTypeId \"D22FA6E9-5EE4-3BDE-4C2B-A409604C4646\" -SensitivityLabel \"Highly Confidential - GDPR\" -Confirm:$false Sets a classification with an explicit GUID for the information type. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which database contains the table to classify. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema The schema of the table to classify. Defaults to \"dbo\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | dbo | -Table The table containing the column to classify. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Column The column to classify. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InformationType The information type name to assign. If this matches a known MIP type, InformationTypeId will be populated automatically. For custom types, provide InformationTypeId explicitly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InformationTypeId The GUID for the information type. Optional when InformationType matches a known MIP type. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SensitivityLabel The sensitivity label name to assign. If this matches a known MIP label, SensitivityLabelId will be populated automatically. For custom labels, provide SensitivityLabelId explicitly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SensitivityLabelId The GUID for the sensitivity label. Optional when SensitivityLabel matches a known MIP label. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts classification objects piped from Get-DbaDbDataClassification. When used, the Schema, Table, Column, and database context are taken from the piped object. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns the updated classification object with the same properties as Get-DbaDbDataClassification. &nbsp;"
  },
  {
    "name": "Set-DbaDbFileGroup",
    "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.",
    "category": "Database Operations",
    "tags": [
      "storage",
      "data",
      "file"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbFileGroup",
    "popularityRank": 437,
    "synopsis": "Modifies filegroup properties including default designation, read-only status, and auto-grow behavior.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbFileGroup View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies filegroup properties including default designation, read-only status, and auto-grow behavior. 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. Syntax Set-DbaDbFileGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-FileGroup] ] [-Default] [-ReadOnly] [-AutoGrowAllFiles] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the HRFG1 filegroup to auto grow all files and makes it the default filegroup on the TestDb database on... PS C:\\> Set-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -Default -AutoGrowAllFiles Sets the HRFG1 filegroup to auto grow all files and makes it the default filegroup on the TestDb database on the sqldev1 instance. Example 2: Sets the HRFG1 filegroup to not auto grow all files on the TestDb database on the sqldev1 instance PS C:\\> Set-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -AutoGrowAllFiles:$false Example 3: Sets the HRFG1 filegroup to read only on the TestDb database on the sqldev1 instance PS C:\\> Set-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -ReadOnly Example 4: Sets the HRFG1 filegroup to read/write on the TestDb database on the sqldev1 instance PS C:\\> Set-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 -ReadOnly:$false Example 5: Passes in the TestDB database from the sqldev1 instance and sets the HRFG1 filegroup to auto grow all files PS C:\\> Get-DbaDatabase -SqlInstance sqldev1 -Database TestDb | Set-DbaDbFileGroup -FileGroup HRFG1 -AutoGrowAllFiles Example 6: Passes in the HRFG1 filegroup from the TestDB database on the sqldev1 instance and sets it to auto grow all... PS C:\\> Get-DbaDbFileGroup -SqlInstance sqldev1 -Database TestDb -FileGroup HRFG1 | Set-DbaDbFileGroup -AutoGrowAllFiles Passes in the HRFG1 filegroup from the TestDB database on the sqldev1 instance and sets it to auto grow all files. Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases contain the filegroups to modify. Required when using SqlInstance parameter. Use this to target specific databases when working with filegroup configurations across multiple databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileGroup Specifies the name(s) of the filegroup(s) to modify. The filegroup must exist and contain at least one file. Use this to target specific filegroups when you need to change their default status, read-only setting, or auto-grow behavior. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Default Sets the filegroup as the default filegroup for new database objects like tables and indexes. Use this when restructuring storage layout or when you want new objects created in a specific filegroup instead of PRIMARY. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ReadOnly Controls the read-only status of the filegroup to prevent data modifications for archival or compliance purposes. Set to $true for read-only (common for historical data), or $false to restore read-write access. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AutoGrowAllFiles Enables proportional growth across all files in the filegroup when any file reaches its growth threshold. Use this to maintain balanced file sizes and prevent hotspots, especially important for tempdb and high-transaction filegroups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database or filegroup objects from Get-DbaDatabase or Get-DbaDbFileGroup via pipeline. Use this for efficient processing when working with multiple databases or filegroups from previous commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.FileGroup Returns the modified FileGroup object(s) after the specified changes have been applied. One object is returned per filegroup that was successfully modified. Default display properties: Name: The name of the filegroup IsDefault: Boolean indicating if this is the default filegroup for new objects ReadOnly: Boolean indicating if the filegroup is read-only AutogrowAllFiles: Boolean indicating if all files in the filegroup grow proportionally Additional properties available (from SMO FileGroup object): ID: The filegroup ID number Parent: Reference to the parent Database object Files: Collection of files contained in the filegroup FileGroupType: Type of filegroup (PRIMARY, FILESTREAM, MEMORY_OPTIMIZED, etc.) Urn: The Uniform Resource Name of the filegroup object State: The current state of the SMO object (Existing, Creating, Pending, etc.) All properties from the base SMO FileGroup object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Set-DbaDbFileGrowth",
    "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.",
    "category": "Database Operations",
    "tags": [
      "storage",
      "data",
      "log",
      "file",
      "growth"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbFileGrowth",
    "popularityRank": 300,
    "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",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbFileGrowth View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies auto-growth settings for database data and log files to use fixed-size increments instead of percentage-based growth. 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. Syntax Set-DbaDbFileGrowth [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-GrowthType] ] [[-Growth] ] [[-FileType] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the test database on sql2016 to a growth of 1GB PS C:\\> Set-DbaDbFileGrowth -SqlInstance sql2016 -Database test -GrowthType GB -Growth 1 Example 2: Sets the test database on sql2016 to a growth of 1GB PS C:\\> Get-DbaDatabase -SqlInstance sql2016 -Database test | Set-DbaDbFileGrowth -GrowthType GB -Growth 1 Example 3: Sets all database files on sql2017, sql2016, sql2012 to 64MB PS C:\\> Get-DbaDatabase | Set-DbaDbFileGrowth -SqlInstance sql2017, sql2016, sql2012 Example 4: Shows what would happen if the command were executed PS C:\\> Set-DbaDbFileGrowth -SqlInstance sql2017, sql2016, sql2012 -Database test -WhatIf Example 5: Sets growth to 1GB for only data files for database test PS C:\\> Set-DbaDbFileGrowth -SqlInstance sql2017 -Database test -GrowthType GB -Growth 1 -FileType Data Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to modify file growth settings for. Accepts an array of database names. Use this when you need to target specific databases rather than all databases on an instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -GrowthType Specifies the unit of measurement for the growth increment. Valid values are KB, MB, GB, or TB. Choose the appropriate unit based on your database size and expected growth patterns - MB for smaller databases, GB for larger ones. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | MB | | Accepted Values | KB,MB,GB,TB | -Growth Sets the numeric value for the fixed growth increment. Defaults to 64 when combined with the default MB unit. Use smaller values (16-64MB) for smaller databases or larger values (256MB-1GB) for high-growth production databases to balance performance and storage efficiency. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 64 | -FileType Controls which file types to modify - Data files only, Log files only, or All files (both data and log). Use 'Data' when you need different growth settings for data vs log files, or 'All' to standardize growth across all database files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | All | | Accepted Values | All,Data,Log | -InputObject Accepts database objects from Get-DbaDatabase for pipeline operations. Use this when you need to filter databases first or when working with database objects from other dbatools functions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database file that was modified. The output represents the updated file growth configuration after the changes have been applied. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database containing the file MaxSize: Maximum size the file can grow to; displays as dbasize object (KB, MB, GB, TB) GrowthType: How the file grows - either \"Percent\" or \"kb\" Growth: The growth increment value (percentage if GrowthType is Percent, kilobytes if kb) File: Logical name of the file within SQL Server FileName: Operating system file path State: Current state of the file (ONLINE, OFFLINE, etc.) &nbsp;"
  },
  {
    "name": "Set-DbaDbIdentity",
    "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",
    "category": "Utilities",
    "tags": [
      "dbcc"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbIdentity",
    "popularityRank": 552,
    "synopsis": "Checks and resets identity column values using DBCC CHECKIDENT",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbIdentity View Source Patrick Flynn (@sqllensman) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Checks and resets identity column values using DBCC CHECKIDENT Description Executes DBCC CHECKIDENT to verify the current identity value for tables with identity columns and optionally reseed them to a specific value. This is essential after bulk data operations, imports, or deletes that can leave identity values out of sync with actual table data. When run without ReSeedValue, it reports the current identity value and the maximum value in the identity column. When ReSeedValue is specified, it resets the identity counter to prevent duplicate key errors or close identity gaps. Read more: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql Syntax Set-DbaDbIdentity [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Table] ] [[-ReSeedValue] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Connects to AdventureWorks2014 on instance SqlServer2017 using Windows Authentication and runs the command... PS C:\\> Set-DbaDbIdentity -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Table 'Production.ScrapReason' Connects to AdventureWorks2014 on instance SqlServer2017 using Windows Authentication and runs the command DBCC CHECKIDENT('Production.ScrapReason') to return the current identity value. Example 2: Connects to AdventureWorks2014 on instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> 'Sql1','Sql2/sqlexpress' | Set-DbaDbIdentity -SqlCredential $cred -Database AdventureWorks2014 -Table 'Production.ScrapReason' Connects to AdventureWorks2014 on instances Sql1 and Sql2/sqlexpress using sqladmin credential and runs the command DBCC CHECKIDENT('Production.ScrapReason') to return the current identity value. Example 3: Checks the current identity value for all tables with an Identity in the AdventureWorks2014 database on the... PS C:\\> $query = \"SELECT SCHEMA_NAME(t.schema_id) +'.' + t.name AS TableName FROM sys.columns c INNER JOIN sys.tables t ON t.object_id = c.object_id WHERE is_identity = 1\" PS C:\\> $IdentityTables = Invoke-DbaQuery -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Query $query PS C:\\> foreach ($tbl in $IdentityTables) { PS C:\\> Set-DbaDbIdentity -SqlInstance SQLServer2017 -Database AdventureWorks2014 -Table $tbl.TableName PS C:\\> } Checks 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. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for identity values. If not specified, all databases on the instance will be processed. When using ReSeedValue, only a single database can be specified since reseeding requires targeting a specific table location. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Specifies which tables with identity columns to check or reseed. Use schema.table format for tables not in the default schema. When using ReSeedValue, only a single table can be specified since each table's identity must be reseeded individually. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ReSeedValue Sets the next identity value that will be assigned to new rows in the specified table. Use this after bulk operations, deletes, or imports that leave gaps in identity sequences or when the identity value needs correction. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per table checked or reseeded, containing the DBCC CHECKIDENT results and execution context. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database containing the table Table: The table name in schema.table format Cmd: The complete DBCC CHECKIDENT command that was executed IdentityValue: The current identity value from DBCC output (the next value to be assigned) ColumnValue: The maximum value found in the identity column (empty string when ReSeedValue is used) Output: The complete raw output text from the DBCC CHECKIDENT command &nbsp;"
  },
  {
    "name": "Set-DbaDbMailAccount",
    "description": "Modifies the configuration of an existing Database Mail account including account properties (display name, email address, description) and mail server settings (SMTP server name, port, SSL, and authentication). This command is useful for updating Database Mail accounts to use cloud email services like Office 365 or Gmail, or for updating credentials when passwords change.",
    "category": "Utilities",
    "tags": [
      "databasemail",
      "dbmail",
      "mail"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbMailAccount",
    "popularityRank": 0,
    "synopsis": "Modifies an existing Database Mail account on SQL Server",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbMailAccount View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies an existing Database Mail account on SQL Server Description Modifies the configuration of an existing Database Mail account including account properties (display name, email address, description) and mail server settings (SMTP server name, port, SSL, and authentication). This command is useful for updating Database Mail accounts to use cloud email services like Office 365 or Gmail, or for updating credentials when passwords change. Syntax Set-DbaDbMailAccount [[-SqlInstance] ] [[-SqlCredential] ] [[-Account] ] [[-InputObject] ] [[-DisplayName] ] [[-Description] ] [[-EmailAddress] ] [[-ReplyToAddress] ] [[-NewMailServerName] ] [[-Port] ] [-EnableSSL] [-UseDefaultCredentials] [[-UserName] ] [[-Password] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Updates the MaintenanceAlerts mail account on sql2017 to use port 587 with SSL enabled PS C:\\> Set-DbaDbMailAccount -SqlInstance sql2017 -Account 'MaintenanceAlerts' -Port 587 -EnableSSL Example 2: Migrates the Alerts mail account on sql2017 to Office 365 with SSL and basic authentication PS C:\\> $splatAccount = @{ >> SqlInstance = 'sql2017' >> Account = 'Alerts' >> NewMailServerName = 'smtp.office365.com' >> Port = 587 >> EnableSSL = $true >> UserName = 'alerts@company.com' >> Password = (ConvertTo-SecureString 'app-password' -AsPlainText -Force) >> } PS C:\\> Set-DbaDbMailAccount @splatAccount Example 3: Uses the pipeline to update the MaintenanceAlerts account to use port 25 with SSL disabled PS C:\\> Get-DbaDbMailAccount -SqlInstance sql2017 -Account 'MaintenanceAlerts' | Set-DbaDbMailAccount -Port 25 -EnableSSL:$false Example 4: Configures the DomainRelay mail account to use Windows integrated authentication PS C:\\> Set-DbaDbMailAccount -SqlInstance sql2017 -Account 'DomainRelay' -UseDefaultCredentials Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Account Specifies one or more Database Mail account names to modify. Used in combination with -SqlInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts MailAccount objects from the pipeline, typically from Get-DbaDbMailAccount. Allows you to chain Database Mail commands together. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -DisplayName Updates the friendly name that appears in the 'From' field of outgoing emails. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Description Updates the optional documentation text describing the account's purpose and usage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EmailAddress Updates the sender email address that appears in outgoing messages from this Database Mail account. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ReplyToAddress Updates the alternate email address for replies when different from the sender address. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NewMailServerName Renames or replaces the SMTP server hostname for the mail account. Use this to migrate to a different SMTP server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Port Updates the TCP port number used to connect to the SMTP server. Common values are 25 (standard SMTP), 465 (SMTPS), and 587 (SMTP with STARTTLS). Use 587 for Office 365 and Gmail which require STARTTLS. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableSSL Enables or disables SSL/TLS encryption for the SMTP connection. Use -EnableSSL:$false to explicitly disable SSL. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UseDefaultCredentials Enables or disables Windows integrated authentication (the SQL Server service account credentials) for SMTP authentication. Use -UseDefaultCredentials:$false to explicitly disable Windows authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UserName Updates the username for SMTP authentication. For Office 365, use the full email address. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Password Updates the password for SMTP authentication as a SecureString. Create with: ConvertTo-SecureString 'yourpassword' -AsPlainText -Force | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Mail.MailAccount Returns the updated MailAccount object from the specified SQL Server instance. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: Unique identifier for the mail account Name: Name of the mail account DisplayName: Friendly name that appears in the 'From' field of emails Description: Description of the account's purpose EmailAddress: Sender email address for outgoing messages ReplyToAddress: Alternate email address for replies IsBusyAccount: Boolean indicating if the account is currently processing emails MailServers: Collection of mail servers associated with this account &nbsp;"
  },
  {
    "name": "Set-DbaDbMirror",
    "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.",
    "category": "Utilities",
    "tags": [
      "mirroring",
      "mirror",
      "ha"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbMirror",
    "popularityRank": 415,
    "synopsis": "Configures database mirroring partner, witness, safety level, and operational state settings.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbMirror View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures database mirroring partner, witness, safety level, and operational state settings. 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. Syntax Set-DbaDbMirror [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Partner] ] [[-Witness] ] [[-SafetyLevel] ] [[-State] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Prompts for confirmation then sets the partner to TCP://SQL2008.ad.local:5374 for the database &quot;dbtools&quot; PS C:\\> Set-DbaDbMirror -SqlInstance sql2005 -Database dbatools -Partner TCP://SQL2008.ad.local:5374 Example 2: Does not prompt for confirmation and sets the witness to TCP://SQL2012.ad.local:5502 for the database... PS C:\\> Set-DbaDbMirror -SqlInstance sql2005 -Database dbatools -Witness TCP://SQL2012.ad.local:5502 -Confirm:$false Does not prompt for confirmation and sets the witness to TCP://SQL2012.ad.local:5502 for the database \"dbtools\" Example 3: Sets the safety level to Full for databases selected from a grid view PS C:\\> Get-DbaDatabase -SqlInstance sql2005 | Out-GridView -PassThru | Set-DbaDbMirror -SafetyLevel Full -Confirm:$false Sets the safety level to Full for databases selected from a grid view. Does not prompt for confirmation. Example 4: Does not prompt for confirmation and sets the state to suspend for the database &quot;dbtools&quot; PS C:\\> Set-DbaDbMirror -SqlInstance sql2005 -Database dbatools -State Suspend -Confirm:$false Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database(s) to configure mirroring settings for. Accepts multiple database names. Use this to target specific mirrored databases when you need to modify partner, witness, safety level, or state settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Partner Sets the mirroring partner server endpoint in TCP://servername:port format. This establishes or changes the mirror partnership. Use this when setting up initial mirroring or changing the partner server after a configuration change or migration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Witness Sets the witness server endpoint in TCP://servername:port format to enable automatic failover in high-safety mode. Use this to add witness functionality for automatic failover or to change the witness server location. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SafetyLevel Controls transaction safety mode: 'Full' for synchronous high-safety, 'Off' for asynchronous high-performance. Use 'Full' when you need zero data loss with automatic failover, or 'Off' for better performance with potential data loss during failover. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Full,Off,None | -State Changes the operational state of the mirroring session. Options include Suspend, Resume, Failover, or RemoveWitness. Use this to temporarily pause mirroring during maintenance, resume after suspension, perform manual failover, or remove witness functionality. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | ForceFailoverAndAllowDataLoss,Failover,RemoveWitness,Resume,Suspend,Off | -InputObject Accepts database objects from Get-DbaDatabase pipeline input for batch operations. Use this to configure mirroring settings across multiple databases efficiently by piping database objects from other dbatools commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Database Returns 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 to the pipeline. When only -Partner, -Witness, or -SafetyLevel parameters are specified, no output is returned (configuration-only operations with no object output). Default display properties from the returned Database object include: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Database name Status: Current database status (Normal, Offline, Recovering, etc.) RecoveryModel: Database recovery model (Full, Simple, BulkLogged) Owner: Database owner login name All properties from the SMO Database object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Set-DbaDbOwner",
    "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 'sa' (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't a Windows group, and isn't 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",
    "category": "Database Operations",
    "tags": [
      "database",
      "owner",
      "dbowner"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbOwner",
    "popularityRank": 68,
    "synopsis": "Changes database ownership to a specified login when current ownership doesn't match the target.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbOwner View Source Michael Fal (@Mike_Fal), mikefal.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Changes database ownership to a specified login when current ownership doesn't match the target. 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. By default, the function sets ownership to 'sa' (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't a Windows group, and isn't already mapped as a user within the database. You can target all databases on an instance or filter to specific databases. Best Practice reference: http://weblogs.sqlteam.com/dang/archive/2008/01/13/Database-Owner-Troubles.aspx Syntax Set-DbaDbOwner [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-InputObject] ] [[-TargetLogin] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets database owner to &#39;sa&#39; on all databases where the owner does not match &#39;sa&#39; PS C:\\> Set-DbaDbOwner -SqlInstance localhost Example 2: Sets the database owner to DOMAIN\\account on all databases where the owner does not match DOMAIN\\account PS C:\\> Set-DbaDbOwner -SqlInstance localhost -TargetLogin DOMAIN\\account Example 3: Sets database owner to &#39;sa&#39; on the db1 and db2 databases if their current owner does not match &#39;sa&#39; PS C:\\> Set-DbaDbOwner -SqlInstance sqlserver -Database db1, db2 Example 4: Sets database owner to &#39;sa&#39; on the db1 and db2 databases if their current owner does not match &#39;sa&#39; PS C:\\> $db = Get-DbaDatabase -SqlInstance localhost -Database db1, db2 PS C:\\> $db | Set-DbaDbOwner -TargetLogin DOMAIN\\account Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to change ownership for. Accepts database names and supports wildcards for pattern matching. When omitted, all user databases on the instance will be processed. System databases are automatically excluded. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during ownership changes. Useful when processing all databases but need to exclude specific ones. Accepts database names and supports wildcards for pattern matching. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase for pipeline operations. Use this when you need to filter databases with specific criteria before changing ownership. Allows for complex database selection logic beyond simple name matching. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -TargetLogin Specifies the login to set as the new database owner. Defaults to 'sa' (or the renamed sysadmin account if sa was renamed). The 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. | Property | Value | | --- | --- | | Alias | Login | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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 actually modified produce output. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database whose owner was changed Owner: The login name that is now the database owner &nbsp;"
  },
  {
    "name": "Set-DbaDbQueryStoreOption",
    "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.",
    "category": "Utilities",
    "tags": [
      "querystore"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbQueryStoreOption",
    "popularityRank": 342,
    "synopsis": "Configures Query Store settings to control query performance data collection and retention.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbQueryStoreOption View Source Enrico van de Laar (@evdlaar) , Tracy Boggiano (@TracyBoggiano) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures Query Store settings to control query performance data collection and retention. 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. This 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. Syntax Set-DbaDbQueryStoreOption [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-AllDatabases] [[-State] ] [[-FlushInterval] ] [[-CollectionInterval] ] [[-MaxSize] ] [[-CaptureMode] ] [[-CleanupMode] ] [[-StaleQueryThreshold] ] [[-MaxPlansPerQuery] ] [[-WaitStatsCaptureMode] ] [[-CustomCapturePolicyExecutionCount] ] [[-CustomCapturePolicyTotalCompileCPUTimeMS] ] [[-CustomCapturePolicyTotalExecutionCPUTimeMS] ] [[-CustomCapturePolicyStaleThresholdHours] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: -AllDatabases Configure the Query Store settings for all user databases in the ServerA\\SQL Instance PS C:\\> Set-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode All -CleanupMode Auto -StaleQueryThreshold 100 Example 2: Only configure the FlushInterval setting for all Query Store databases in the ServerA\\SQL Instance PS C:\\> Set-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -FlushInterval 600 Example 3: -StaleQueryThreshold 100 Configure the Query Store settings for the AdventureWorks database in the... PS C:\\> Set-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -Database AdventureWorks -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode all -CleanupMode Auto -StaleQueryThreshold 100 Configure the Query Store settings for the AdventureWorks database in the ServerA\\SQL Instance. Example 4: -StaleQueryThreshold 100 Configure the Query Store settings for all user databases except the AdventureWorks... PS C:\\> Set-DbaDbQueryStoreOption -SqlInstance ServerA\\SQL -Exclude AdventureWorks -State ReadWrite -FlushInterval 600 -CollectionInterval 10 -MaxSize 100 -CaptureMode all -CleanupMode Auto -StaleQueryThreshold 100 Configure the Query Store settings for all user databases except the AdventureWorks database in the ServerA\\SQL Instance. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential SqlLogin to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance.. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to configure Query Store options for. Accepts database names, wildcards, or database objects from Get-DbaDatabase. Use this when you need to configure Query Store for specific databases instead of all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from Query Store configuration changes. System databases (master, tempdb, model) are automatically excluded. Useful when you want to configure most databases but skip certain ones like staging or temporary databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllDatabases Configures Query Store options for all user databases on the instance. System databases are automatically excluded. Use this switch when you want to apply consistent Query Store settings across all user databases without specifying individual database names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Set to ReadWrite to start collecting query performance data, or ReadOnly when troubleshooting performance issues without adding new data overhead. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | ReadWrite,ReadOnly,Off | -FlushInterval Sets how frequently Query Store flushes runtime statistics from memory to disk, in seconds. Default is 900 seconds (15 minutes). Lower 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -CollectionInterval Defines how often Query Store aggregates runtime statistics into discrete time intervals, in minutes. Default is 60 minutes. Shorter intervals provide finer granularity for performance analysis but consume more storage; longer intervals reduce storage overhead but provide less detailed trending data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaxSize Sets the maximum storage space Query Store can consume in the database, in megabytes. Default is 100 MB. Configure based on your database size and query volume; busy OLTP databases may need several GB, while smaller databases can use the default. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 defined capture policies (SQL 2019+). Use Auto for most production environments to avoid capturing trivial queries; use All for comprehensive troubleshooting or development environments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Set to Auto to prevent Query Store from reaching capacity and stopping data collection; use Off only when you want manual control over data retention. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Auto,Off | -StaleQueryThreshold Specifies how many days Query Store retains data for queries that haven't executed recently, used by automatic cleanup processes. Set to 30-90 days for most environments; longer retention helps with historical analysis but consumes more space, shorter retention frees space faster. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaxPlansPerQuery Limits how many execution plans Query Store retains for each individual query. Default is 200 plans per query (SQL Server 2017+). Higher values help track plan variations in dynamic environments but consume more space; lower values reduce storage but may miss important plan changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -WaitStatsCaptureMode Enables or disables wait statistics collection in Query Store (SQL Server 2017+). Options are On or Off. Enable wait stats capture when you need detailed performance analysis including what queries are waiting for; disable to reduce overhead in high-throughput systems. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use values like 5-10 to capture queries that run regularly but avoid one-time or rarely executed queries that don't impact performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -CustomCapturePolicyTotalCompileCPUTimeMS Sets minimum compilation CPU time threshold in milliseconds for capturing queries when CaptureMode is Custom (SQL Server 2019+). Set to values like 1000ms (1 second) to capture queries with significant compilation overhead, helping identify queries that need plan guides or parameter optimization. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -CustomCapturePolicyTotalExecutionCPUTimeMS Sets minimum total execution CPU time threshold in milliseconds for capturing queries when CaptureMode is Custom (SQL Server 2019+). Use values like 100ms to focus on queries consuming significant CPU resources, filtering out lightweight queries that don't impact overall performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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+). Set to 24-168 hours (1-7 days) to balance between capturing actively used queries and avoiding resource consumption on dormant queries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts for confirmation of every step. For example: Are you sure you want to perform this action? Performing the operation \"Changing Desired State\" on target \"pubs on SQL2016\\VNEXT\". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"): | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.QueryStoreOptions Returns 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 immediately verify the results of the configuration changes. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database ActualState: Current Query Store state (ReadWrite, ReadOnly, or Off) DataFlushIntervalInSeconds: Interval in seconds for flushing data to storage StatisticsCollectionIntervalInMinutes: Interval in minutes for statistics collection MaxStorageSizeInMB: Maximum storage size allocated for Query Store (in megabytes) CurrentStorageSizeInMB: Current storage size being used by Query Store (in megabytes) QueryCaptureMode: Query capture mode (All, Auto, None, or Custom) SizeBasedCleanupMode: Cleanup mode when max storage is exceeded (Off, Auto) StaleQueryThresholdInDays: Number of days after which a query is considered stale for cleanup Additional properties for SQL Server 2017 (v14) and later: MaxPlansPerQuery: Maximum number of plans tracked per query WaitStatsCaptureMode: Wait statistics capture mode (Off, On) Additional properties for SQL Server 2019 (v15) and later: CustomCapturePolicyExecutionCount: Custom capture policy execution count threshold CustomCapturePolicyTotalCompileCPUTimeMS: Custom capture policy compile CPU time threshold in milliseconds CustomCapturePolicyTotalExecutionCPUTimeMS: Custom capture policy execution CPU time threshold in milliseconds CustomCapturePolicyStaleThresholdHours: Custom capture policy stale threshold in hours All 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 varies based on the SQL Server version of the target instance. &nbsp;"
  },
  {
    "name": "Set-DbaDbRecoveryModel",
    "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.",
    "category": "Database Operations",
    "tags": [
      "recoverymodel",
      "database"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbRecoveryModel",
    "popularityRank": 127,
    "synopsis": "Changes the recovery model for specified databases on SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbRecoveryModel View Source Viorel Ciucu (@viorelciucu), cviorel.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Changes the recovery model for specified databases on SQL Server instances. 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. Syntax Set-DbaDbRecoveryModel [-SqlCredential ] -RecoveryModel [-Database ] [-ExcludeDatabase ] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [ ] Set-DbaDbRecoveryModel -SqlInstance [-SqlCredential ] -RecoveryModel [-Database ] [-ExcludeDatabase ] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [ ] Set-DbaDbRecoveryModel [-SqlCredential ] -RecoveryModel [-Database ] [-ExcludeDatabase ] [-AllDatabases] [-EnableException] -InputObject [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the Recovery Model to BulkLogged for database [model] on SQL Server instance sql2014 PS C:\\> Set-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Database model -Confirm:$true -Verbose Sets the Recovery Model to BulkLogged for database [model] on SQL Server instance sql2014. User is requested to confirm the action. Example 2: Sets the Recovery Model to Simple for database [TestDB] on SQL Server instance sql2014 PS C:\\> Get-DbaDatabase -SqlInstance sql2014 -Database TestDB | Set-DbaDbRecoveryModel -RecoveryModel Simple -Confirm:$false Sets the Recovery Model to Simple for database [TestDB] on SQL Server instance sql2014. Confirmation is not required. Example 3: Sets the Recovery Model to Simple for database [TestDB] on SQL Server instance sql2014 PS C:\\> Set-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel Simple -Database TestDB -Confirm:$false Sets the Recovery Model to Simple for database [TestDB] on SQL Server instance sql2014. Confirmation is not required. Example 4: Sets the Recovery Model to Simple for ALL user and system databases (except TEMPDB) on SQL Server instance... PS C:\\> Set-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel Simple -AllDatabases -Confirm:$false Sets the Recovery Model to Simple for ALL user and system databases (except TEMPDB) on SQL Server instance sql2014. Runs without asking for confirmation. Example 5: Sets the Recovery Model to BulkLogged for [TestDB1] and [TestDB2] databases on SQL Server instance sql2014 PS C:\\> Set-DbaDbRecoveryModel -SqlInstance sql2014 -RecoveryModel BulkLogged -Database TestDB1, TestDB2 -Confirm:$false -Verbose Sets the Recovery Model to BulkLogged for [TestDB1] and [TestDB2] databases on SQL Server instance sql2014. Runs without asking for confirmation. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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 BulkLogged for bulk operations with reduced logging. This change affects backup strategy requirements and transaction log growth patterns for the target databases. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | | Accepted Values | Simple,Full,BulkLogged | -InputObject Accepts database objects from Get-DbaDatabase or similar commands through the pipeline. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to change the recovery model for. Accepts database names as strings or wildcard patterns. Use this when you need to target specific databases instead of all databases on the instance. Required unless using -AllDatabases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip when changing recovery models. Useful when combined with -AllDatabases to exclude specific databases. Commonly used to exclude databases that should maintain their current recovery model for operational reasons. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllDatabases Required switch when you want to change the recovery model for all databases on the instance. This safety parameter prevents accidentally modifying all databases without explicit confirmation. Automatically excludes tempdb and database snapshots. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts for confirmation. For example: Are you sure you want to perform this action? Performing the operation \"ALTER DATABASE [model] SET RECOVERY Full\" on target \"[model] on WERES14224\". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is \"Y\"): | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Database Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Database name Status: Current database status (EmergencyMode, Normal, Offline, Recovering, RecoveryPending, Restoring, Standby, Suspect) IsAccessible: Boolean indicating if the database is currently accessible RecoveryModel: Database recovery model (Full, Simple, or BulkLogged) - this will be the newly set value LastFullBackup: DateTime of the most recent full backup LastDiffBackup: DateTime of the most recent differential backup LastLogBackup: DateTime of the most recent transaction log backup Note: 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 for that database. When -WhatIf is used, no output objects are returned. All other properties from the underlying SMO Database object remain accessible via Select-Object * even though only the properties listed above are displayed by default. &nbsp;"
  },
  {
    "name": "Set-DbaDbSchema",
    "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.",
    "category": "Database Operations",
    "tags": [
      "schema",
      "database"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbSchema",
    "popularityRank": 410,
    "synopsis": "Changes the owner of database schemas to reassign security and object ownership responsibilities",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbSchema View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Changes the owner of database schemas to reassign security and object ownership responsibilities 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. Syntax Set-DbaDbSchema [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [-Schema] [-SchemaOwner] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Updates the TestSchema1 schema in the example1 database in the sqldev01 instance PS C:\\> Set-DbaDbSchema -SqlInstance sqldev01 -Database example1 -Schema TestSchema1 -SchemaOwner dbatools Updates the TestSchema1 schema in the example1 database in the sqldev01 instance. The dbatools user will be the new owner of the schema. Example 2: Passes in the example1 db via pipeline and updates the TestSchema1 and TestSchema2 schemas and assigns the... PS C:\\> Get-DbaDatabase -SqlInstance sqldev01, sqldev02 -Database example1 | Set-DbaDbSchema -Schema TestSchema1, TestSchema2 -SchemaOwner dbatools Passes in the example1 db via pipeline and updates the TestSchema1 and TestSchema2 schemas and assigns the dbatools user as the owner of the schemas. Required Parameters -Schema Specifies the name(s) of the database schemas whose ownership will be changed. Accepts multiple schema names. Common scenarios include transferring ownership from developers to service accounts or standardizing ownership after migrations. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -SchemaOwner Specifies the database user or role that will become the new owner of the specified schemas. Must be a valid database principal. Typically used to assign ownership to service accounts, application users, or standardized roles like db_owner. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases contain the schemas to be updated. Required when using SqlInstance parameter. Use this to target specific databases where you need to change schema ownership. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase via pipeline input. Use this to work with database objects already retrieved. Useful when you want to filter databases first or work with databases from multiple instances in a single operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Schema Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the schema that was updated IsSystemObject: Boolean indicating if this is a built-in system schema or custom user-defined schema Owner: The new owner of the schema (updated to the value specified by -SchemaOwner) Additional properties available (from SMO Schema object): DatabaseName: The name of the database containing the schema DatabaseId: The unique identifier (ID) of the database CreateDate: DateTime when the schema was created DateLastModified: DateTime when the schema was last modified ID: The schema's unique object ID within the database Urn: The Urn identifier for the schema All 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. &nbsp;"
  },
  {
    "name": "Set-DbaDbSequence",
    "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.",
    "category": "Utilities",
    "tags": [
      "data",
      "sequence",
      "table"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbSequence",
    "popularityRank": 654,
    "synopsis": "Modifies properties of existing SQL Server sequence objects",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbSequence View Source Adam Lancaster, github.com/lancasteradam Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies properties of existing SQL Server sequence objects 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. Syntax Set-DbaDbSequence [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [-Sequence] [[-Schema] ] [[-RestartWith] ] [[-IncrementBy] ] [[-MinValue] ] [[-MaxValue] ] [-Cycle] [[-CacheSize] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Modifies the sequence TestSequence in the TestDB database on the sqldev01 instance PS C:\\> Set-DbaDbSequence -SqlInstance sqldev01 -Database TestDB -Sequence TestSequence -RestartWith 10000 -IncrementBy 10 Modifies the sequence TestSequence in the TestDB database on the sqldev01 instance. The sequence will restart with 10000 and increment by 10. Example 2: Using a pipeline this command modifies the sequence named TestSchema.TestSequence in the TestDB database on... PS C:\\> Get-DbaDatabase -SqlInstance sqldev01 -Database TestDB | Set-DbaDbSequence -Sequence TestSequence -Schema TestSchema -Cycle Using 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. Required Parameters -Sequence Specifies the name of the sequence object to modify. This is the sequence you want to update properties for. Must be an existing sequence in the specified schema, otherwise the function will fail. | Property | Value | | --- | --- | | Alias | Name | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target database containing the sequence to modify. Accepts multiple database names. Required when using SqlInstance parameter to identify which database contains the sequence. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Specifies the schema containing the sequence to modify. Defaults to 'dbo' if not specified. Use this when your sequence exists in a custom schema rather than the default dbo schema. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | dbo | -RestartWith Sets the next value the sequence will return when NEXT VALUE FOR is called. Immediately resets the sequence to this value. Use this to fix sequence gaps, realign sequences after data imports, or reset sequences for testing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -IncrementBy Sets how much the sequence value increases (or decreases if negative) with each NEXT VALUE FOR call. Common values are 1 for sequential numbering or larger values for reserving ranges. Cannot be zero. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MinValue Sets the lowest value the sequence can generate. Once reached, sequence behavior depends on the Cycle setting. Use this to establish data range constraints or prevent sequences from going below business-required minimums. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaxValue Sets the highest value the sequence can generate. Once reached, sequence behavior depends on the Cycle setting. Use this to prevent sequences from exceeding data type limits or business-defined maximum values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Cycle Enables the sequence to restart from MinValue after reaching MaxValue (or vice versa for negative increments). Use this for scenarios like rotating through a fixed set of values or when sequences need to wrap around. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CacheSize Sets the number of sequence values SQL Server pre-allocates in memory for faster access. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -InputObject Accepts database objects from Get-DbaDatabase via pipeline to modify sequences across multiple databases. Use this for batch operations when you need to modify the same sequence in multiple databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Sequence Returns the updated Sequence object for each modified sequence, with all properties reflecting the changes applied. Default display properties (when piping to Select-Object): Name: The name of the sequence object Schema: The schema containing the sequence Owner: The principal that owns the sequence StartValue: The starting value for the sequence CurrentValue: The current value of the sequence IncrementValue: The increment applied with each NEXT VALUE FOR call MinValue: The minimum value the sequence can generate MaxValue: The maximum value the sequence can generate IsCycleEnabled: Boolean indicating if the sequence cycles after reaching MinValue or MaxValue SequenceCacheType: The cache setting (NoCache, CacheWithSize, or DefaultCache) CacheSize: The number of pre-allocated values (when applicable) *All properties from the SMO Sequence object are accessible using Select-Object . Additional properties include:** CreationDate: DateTime when the sequence was created LastModificationTime: DateTime when the sequence was last modified Urn: The Uniform Resource Name (URN) of the sequence object State: The SMO object state (Existing, Creating, Pending, Dropping, etc.) Parent: Reference to the parent Database object &nbsp;"
  },
  {
    "name": "Set-DbaDbState",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "state"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDbState",
    "popularityRank": 71,
    "synopsis": "Modifies database read/write access, online status, and user access modes",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDbState View Source Simone Bizzotto (@niphold) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies database read/write access, online status, and user access modes 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. This function handles three categories of database state changes: Read/Write access: Sets databases to READ_ONLY for reporting scenarios or READ_WRITE for normal operations Online status: Brings databases ONLINE, takes them OFFLINE for maintenance, or sets EMERGENCY mode for corruption recovery User access: Restricts database access to SINGLE_USER for maintenance, RESTRICTED_USER for admin-only access, or MULTI_USER for normal operations Database detachment: Safely detaches databases by first removing them from Availability Groups and breaking mirroring relationships when -Force is specified The -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. Returns an object with SqlInstance, Database, RW, Status, Access, and Notes properties. The Notes field contains error details when state changes fail. Syntax Set-DbaDbState [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-AllDatabases] [-ReadOnly] [-ReadWrite] [-Online] [-Offline] [-Emergency] [-Detached] [-SingleUser] [-RestrictedUser] [-MultiUser] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Set-DbaDbState -SqlInstance [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-AllDatabases] [-ReadOnly] [-ReadWrite] [-Online] [-Offline] [-Emergency] [-Detached] [-SingleUser] [-RestrictedUser] [-MultiUser] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Set-DbaDbState [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-AllDatabases] [-ReadOnly] [-ReadWrite] [-Online] [-Offline] [-Emergency] [-Detached] [-SingleUser] [-RestrictedUser] [-MultiUser] [-Force] [-EnableException] -InputObject [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the HR database as OFFLINE PS C:\\> Set-DbaDbState -SqlInstance sqlserver2014a -Database HR -Offline Example 2: Sets all databases of the sqlserver2014a instance, except for HR, as READ_ONLY PS C:\\> Set-DbaDbState -SqlInstance sqlserver2014a -AllDatabases -Exclude HR -ReadOnly -Force Example 3: Finds all offline databases and sets them to online PS C:\\> Get-DbaDbState -SqlInstance sql2016 | Where-Object Status -eq 'Offline' | Set-DbaDbState -Online Example 4: Sets the HR database as SINGLE_USER PS C:\\> Set-DbaDbState -SqlInstance sqlserver2014a -Database HR -SingleUser Example 5: Sets the HR database as SINGLE_USER, dropping all other connections (and rolling back open transactions) PS C:\\> Set-DbaDbState -SqlInstance sqlserver2014a -Database HR -SingleUser -Force Example 6: Gets the databases from Get-DbaDatabase, and sets them as SINGLE_USER, dropping all other connections (and... PS C:\\> Get-DbaDatabase -SqlInstance sqlserver2014a -Database HR | Set-DbaDbState -SingleUser -Force Gets the databases from Get-DbaDatabase, and sets them as SINGLE_USER, dropping all other connections (and rolling back open transactions) Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase or Get-DbaDbState through the pipeline. Use this to chain commands together, allowing you to filter databases first then modify their states in a single operation. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to modify state for. Accepts single database name, comma-separated list, or wildcards. Use this when you need to target specific databases instead of all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from the state change operation when using -AllDatabases. Useful when you want to modify most databases but skip critical production databases or those undergoing maintenance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllDatabases Indicates that the operation should target all user databases on the instance. Required safety parameter to prevent accidental modification of all databases when no specific database is specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ReadOnly Sets the database to read_ONLY mode, preventing any data modifications. Use this for creating reporting databases, preparing for backups, or when you need to ensure data integrity during maintenance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ReadWrite Sets the database to read_WRITE mode, allowing normal data modifications. Use this to restore normal operations after maintenance or to enable writes on a previously read-only database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Online Brings the database online and makes it available for normal operations. Use this to restore database availability after maintenance, upgrades, or recovery operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Offline Takes the database offline, making it inaccessible to users and applications. Use this for maintenance tasks like file moves, hardware upgrades, or when you need to ensure no connections during critical operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Emergency Sets the database to EMERGENCY mode for corruption recovery scenarios. Use this when the database won't start normally due to corruption and you need to attempt data recovery or run emergency repairs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Detached Safely detaches the database from the SQL Server instance, removing it from sys.databases. Use this when moving databases between instances or when you need to work with database files directly. Requires -Force for mirrored or AG databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SingleUser Restricts database access to a single connection, typically for administrative tasks. Use this during maintenance operations, database restores, or when you need exclusive access to prevent user interference. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -RestrictedUser Limits database access to members of db_owner, dbcreator, or sysadmin roles only. Use this during maintenance windows when you need to allow admin access while blocking regular users. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MultiUser Restores normal multi-user access to the database, allowing all authorized connections. Use this to return the database to normal operations after completing single-user or restricted-user maintenance tasks. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Rolls back open transactions immediately and kills active connections to allow the state change to proceed. Use this when normal state changes fail due to blocking connections, but be aware it will cause transaction rollbacks and connection drops. Required for detaching databases that are in Availability Groups or mirroring relationships. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database modified, with the following properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) DatabaseName: The name of the database that was modified RW: The read/write access mode (READ_ONLY or READ_WRITE) Status: The database status (ONLINE, OFFLINE, EMERGENCY, or DETACHED) Access: The user access mode (SINGLE_USER, RESTRICTED_USER, or MULTI_USER) Notes: Error details if the state change failed; null if successful (semicolon-separated list if multiple errors) Database: The SMO Database object (not displayed by default but accessible) &nbsp;"
  },
  {
    "name": "Set-DbaDefaultPath",
    "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",
    "category": "Backup & Restore",
    "tags": [
      "storage",
      "data",
      "logs",
      "backup"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaDefaultPath",
    "popularityRank": 418,
    "synopsis": "Configures the default file paths for new databases and backups on SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaDefaultPath View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures the default file paths for new databases and backups on SQL Server instances 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. The 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. To change the error log location, use Set-DbaStartupParameter Syntax Set-DbaDefaultPath [-SqlInstance] [[-SqlCredential] ] [[-Type] ] [-Path] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the data and backup default paths on sql01\\sharepoint to C:\\mssql\\sharepoint\\data PS C:\\> Set-DbaDefaultPath -SqlInstance sql01\\sharepoint -Type Data, Backup -Path C:\\mssql\\sharepoint\\data Example 2: Shows what what happen if the command would have run PS C:\\> Set-DbaDefaultPath -SqlInstance sql01\\sharepoint -Type Data, Log -Path C:\\mssql\\sharepoint\\data -WhatIf Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | -Path The directory path where SQL Server will create new database files or backups by default. Must be a valid path accessible to the SQL Server service account with appropriate permissions. Use UNC paths for shared storage or local paths like C:\\Data for dedicated storage volumes. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies which default path types to configure: Data (new database data files), Log (new database log files), or Backup (backup operations). Use Data and Log when standardizing database file locations across instances or moving files to faster storage. Backup path changes take effect immediately, while Data and Log changes require a SQL Server service restart. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | | Accepted Values | Data,Backup,Log | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance where changes were committed. The object contains the current default path settings for the specified instance. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Data: The current default path for new database data files (from $server.DefaultFile) Log: The current default path for new database log files (from $server.DefaultLog) Backup: The current default path for backup operations (from $server.BackupDirectory) Note: When changing Data or Log paths, the SQL Server service must be restarted for changes to take effect. Backup path changes are immediate. &nbsp;"
  },
  {
    "name": "Set-DbaEndpoint",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "endpoint"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaEndpoint",
    "popularityRank": 507,
    "synopsis": "Modifies SQL Server endpoint properties including owner and protocol type.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaEndpoint View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies SQL Server endpoint properties including owner and protocol type. 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. Syntax Set-DbaEndpoint [[-SqlInstance] ] [[-SqlCredential] ] [[-Endpoint] ] [[-Owner] ] [[-Type] ] [-AllEndpoints] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets all endpoint owners to sa on sql2016 PS C:\\> Set-DbaEndpoint -SqlInstance sql2016 -AllEndpoints -Owner sa Example 2: Changes the endpoint type to Tsql on endpoint ep1 PS C:\\> Get-DbaEndpoint -SqlInstance sql2016 -Endpoint ep1 | Set-DbaEndpoint -Type TSql Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 standardizing endpoint ownership across your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Changes the endpoint protocol type between DatabaseMirroring, ServiceBroker, Soap, or TSql. Use DatabaseMirroring for availability group configurations, ServiceBroker for application messaging, TSql for custom client connections, or Soap for web service integrations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 control over which endpoints get updated. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Endpoint Returns one modified Endpoint object for each endpoint that was changed. The endpoint object reflects the updated property values after the Alter() operation is committed. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the endpoint EndpointType: The type of endpoint (DatabaseMirroring, ServiceBroker, Soap, or TSql) ProtocolType: The communication protocol used by the endpoint Owner: The login name that owns the endpoint IsSystemObject: Boolean indicating if this is a system endpoint CreateDate: DateTime when the endpoint was created All properties from the SMO Endpoint object are accessible using Select-Object * for more detailed analysis. &nbsp;"
  },
  {
    "name": "Set-DbaErrorLogConfig",
    "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.",
    "category": "Server Management",
    "tags": [
      "instance",
      "errorlog",
      "logging"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaErrorLogConfig",
    "popularityRank": 448,
    "synopsis": "Configures SQL Server error log retention and size rollover settings",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaErrorLogConfig View Source Shawn Melton (@wsmelton), wsmelton.github.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures SQL Server error log retention and size rollover settings 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. This 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. To set the Path to the ErrorLog, use Set-DbaStartupParameter -ErrorLog. Note that this command requires remote, administrative access to the Windows/WMI server, similar to SQL Configuration Manager. Syntax Set-DbaErrorLogConfig [-SqlInstance] [[-SqlCredential] ] [[-LogCount] ] [[-LogSize] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the number of error log files to 25 on sql2017 and sql2014 PS C:\\> Set-DbaErrorLogConfig -SqlInstance sql2017,sql2014 -LogCount 25 Example 2: Sets the size of the error log file, before it rolls over, to 102400 KB (100 MB) on sql2014 PS C:\\> Set-DbaErrorLogConfig -SqlInstance sql2014 -LogSize 102400 Example 3: Sets the number of error log files to 25 and size before it will roll over to 500 KB on sql2012 PS C:\\> Set-DbaErrorLogConfig -SqlInstance sql2012 -LogCount 25 -LogSize 500 Required Parameters -SqlInstance The target SQL Server instance or instances | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LogCount Sets the number of error log files SQL Server retains before deleting the oldest ones. Must be between 6 and 99. Use this to balance disk space with troubleshooting history - more files provide longer history but consume more disk space. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this to prevent error logs from growing too large and to ensure regular log rotation without manual intervention. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance containing the current error log configuration settings. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name in computer\\instance format LogCount: The number of error log files SQL Server retains (integer between 6 and 99) LogSize: The maximum size of each error log file in kilobytes; returns as dbasize object for automatic unit formatting The 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 without changes. &nbsp;"
  },
  {
    "name": "Set-DbaExtendedProperty",
    "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.",
    "category": "Utilities",
    "tags": [
      "general",
      "extendedproperties"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaExtendedProperty",
    "popularityRank": 491,
    "synopsis": "Updates the value of existing extended properties on SQL Server database objects",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaExtendedProperty View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Updates the value of existing extended properties on SQL Server database objects 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. Works 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. Syntax Set-DbaExtendedProperty [-InputObject] [-Value] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the value of appversion to 1.1.0 on the mydb database PS C:\\> Get-DbaDatabase -SqlInstance localhost -Database mydb | Get-DbaExtendedProperty -Name appversion | Set-DbaExtendedProperty -Value \"1.1.0\" Example 2: Sets the value of appversion to 1.1.0 on the mytable table of the mydb database PS C:\\> Get-DbaDbTable -SqlInstance localhost -Database mydb -Table mytable | Get-DbaExtendedProperty -Name appversion | Set-DbaExtendedProperty -Value \"1.1.0\" Required Parameters -InputObject Accepts extended property objects from Get-DbaExtendedProperty to update their values. Use this to pipeline specific extended properties that you want to modify. Typically used after filtering extended properties by name, object type, or other criteria to batch update property values across multiple database objects. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Value Specifies the new value to assign to the extended property. Accepts any string value including version numbers, descriptions, or configuration data. Common uses include updating application version numbers, modifying documentation text, or changing configuration values stored as extended properties. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.ExtendedProperty Returns the updated ExtendedProperty object for each extended property modified. The returned object reflects all changes made by the Alter() method. Default properties returned: Name: The name of the extended property Value: The updated value that was set Additional properties available (from SMO ExtendedProperty object): ID: The identifier of the extended property Parent: The parent object that this extended property is attached to State: The current state of the SMO object (Existing, Creating, Pending, etc.) Urn: The Uniform Resource Name (URN) of the extended property Properties: Collection of SQL Server object properties All properties from the base SMO ExtendedProperty object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Set-DbaExtendedProtection",
    "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 > Protocols for \"InstanceName\".",
    "category": "Server Management",
    "tags": [
      "instance",
      "security"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaExtendedProtection",
    "popularityRank": 622,
    "synopsis": "Configures Extended Protection for Authentication on SQL Server network protocols",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Set-DbaExtendedProtection View Source Claudio Silva (@claudioessilva), claudioessilva.eu Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures Extended Protection for Authentication on SQL Server network protocols 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. This 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. The 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 > Protocols for \"InstanceName\". Syntax Set-DbaExtendedProtection [[-SqlInstance] ] [[-Credential] ] [[-Value] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Set Extended Protection of SQL Engine on the default (MSSQLSERVER) instance on localhost to &quot;Off&quot; PS C:\\> Set-DbaExtendedProtection Set Extended Protection of SQL Engine on the default (MSSQLSERVER) instance on localhost to \"Off\". Requires (and checks for) RunAs admin. Example 2: Set Extended Protection of SQL Engine on the default (MSSQLSERVER) instance on localhost to &quot;Required&quot; PS C:\\> Set-DbaExtendedProtection -Value Required Set Extended Protection of SQL Engine on the default (MSSQLSERVER) instance on localhost to \"Required\". Requires (and checks for) RunAs admin. Example 3: Set Extended Protection of SQL Engine for the SQL2008R2SP2 on sql01 to &quot;Off&quot; PS C:\\> Set-DbaExtendedProtection -SqlInstance sql01\\SQL2008R2SP2 Set Extended Protection of SQL Engine for the SQL2008R2SP2 on sql01 to \"Off\". Uses Windows Credentials to both connect and modify the registry. Example 4: Set Extended Protection of SQL Engine for the SQL2008R2SP2 on sql01 to &quot;Allowed&quot; PS C:\\> Set-DbaExtendedProtection -SqlInstance sql01\\SQL2008R2SP2 -Value Allowed Set Extended Protection of SQL Engine for the SQL2008R2SP2 on sql01 to \"Allowed\". Uses Windows Credentials to both connect and modify the registry. Example 5: Shows what would happen if the command were executed PS C:\\> Set-DbaExtendedProtection -SqlInstance sql01\\SQL2008R2SP2 -WhatIf Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the computer (not SQL Server instance) using alternative Windows credentials | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Value Specifies the Extended Protection level for SQL Server network protocols. Accepts \"Off\", \"Allowed\", or \"Required\" (or equivalent integers 0, 1, 2). Use \"Off\" to disable Extended Protection, \"Allowed\" to accept both protected and unprotected connections, or \"Required\" to enforce Extended Protection for all client connections. Defaults to \"Off\" when not specified. Setting to \"Required\" may prevent older applications from connecting unless they support Extended Protection authentication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Off | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per target SQL Server instance containing the Extended Protection configuration that was applied. Properties: ComputerName: The computer name where the registry change was made InstanceName: The SQL Server instance name (e.g., MSSQLSERVER, SQL2019) SqlInstance: The full SQL Server instance name in computer\\instance format ExtendedProtection: The Extended Protection setting value with human-readable description (e.g., \"0 - Off\", \"1 - Allowed\", \"2 - Required\") &nbsp;"
  },
  {
    "name": "Set-DbaLogin",
    "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.",
    "category": "Security",
    "tags": [
      "login"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaLogin",
    "popularityRank": 55,
    "synopsis": "Modifies SQL Server login properties including passwords, permissions, roles, and account status",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaLogin View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies SQL Server login properties including passwords, permissions, roles, and account status 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. Syntax Set-DbaLogin [[-SqlInstance] ] [[-SqlCredential] ] [[-Login] ] [[-SecurePassword] ] [[-PasswordHash] ] [[-DefaultDatabase] ] [-Unlock] [-PasswordMustChange] [[-NewName] ] [-Disable] [-Enable] [-DenyLogin] [-GrantLogin] [-PasswordPolicyEnforced] [-PasswordExpirationEnabled] [[-AddRole] ] [[-RemoveRole] ] [[-InputObject] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Set the new password for login1 using a credential, unlock the account and set the option that the user must... PS C:\\> $SecurePassword = (Get-Credential NoUsernameNeeded).Password PS C:\\> $cred = New-Object System.Management.Automation.PSCredential (\"username\", $SecurePassword) PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login login1 -SecurePassword $cred -Unlock -PasswordMustChange Set the new password for login1 using a credential, unlock the account and set the option that the user must change password at next logon. Example 2: Enable the login PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login login1 -Enable Example 3: Enable multiple logins PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login login1, login2, login3, login4 -Enable Example 4: Enable multiple logins on multiple instances PS C:\\> Set-DbaLogin -SqlInstance sql1, sql2, sql3 -Login login1, login2, login3, login4 -Enable Example 5: Disable the login PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login login1 -Disable Example 6: Deny the login to connect to the instance PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login login1 -DenyLogin Example 7: Grant the login to connect to the instance PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login login1 -GrantLogin Example 8: Enforces the password policy on a login PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login login1 -PasswordPolicyEnforced Example 9: Disables enforcement of the password policy on a login PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login login1 -PasswordPolicyEnforced:$false Example 10: Add the server role &quot;serveradmin&quot; to the login PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login test -AddRole serveradmin Example 11: Remove the server role &quot;bulkadmin&quot; to the login PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login test -RemoveRole bulkadmin Example 12: Disable the login from the pipeline PS C:\\> $login = Get-DbaLogin -SqlInstance sql1 -Login test PS C:\\> $login | Set-DbaLogin -Disable Example 13: Set the default database to master on a login PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login login1 -DefaultDatabase master Example 14: Unlocks the login1 on the sql1 instance using the technique described at... PS C:\\> Set-DbaLogin -SqlInstance sql1 -Login login1 -Unlock -Force Unlocks 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/ Example 15: Sets the password for login1 on sql2 using a hashed password value from another instance PS C:\\> $hash = \"0x02001234567890ABCDEF...\" PS C:\\> Set-DbaLogin -SqlInstance sql2 -Login login1 -PasswordHash $hash Example 16: Gets the password hash from sql1 and applies it to sql2, syncing the password between instances PS C:\\> $sourceLogin = Get-DbaLogin -SqlInstance sql1 -Login app_user PS C:\\> $hash = Get-LoginPasswordHash -Login $sourceLogin PS C:\\> Set-DbaLogin -SqlInstance sql2 -Login app_user -PasswordHash $hash Optional Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Specifies one or more SQL Server login names to modify. Accepts an array for batch operations. Use this to target specific login accounts when performing password resets, account management, or role assignments. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecurePassword Sets a new password for the login using either a PSCredential object or SecureString. Required when using -PasswordMustChange. Create secure passwords with Get-Credential or ConvertTo-SecureString to avoid plain text exposure in scripts. | Property | Value | | --- | --- | | Alias | Password | | Required | False | | Pipeline | false | | Default Value | | -PasswordHash Sets the login password using a hashed password value (0x...). This is used for transferring logins between instances without knowing the actual password. The hash must be in the format returned by Get-LoginPasswordHash or extracted from sys.sql_logins. Cannot be used with -SecurePassword or -PasswordMustChange. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DefaultDatabase Changes the default database that the login connects to after authentication. Must be an existing database name. Use this when users need to land in a specific database instead of master, such as application-specific databases. | Property | Value | | --- | --- | | Alias | DefaultDB | | Required | False | | Pipeline | false | | Default Value | | -Unlock Unlocks a locked SQL Server login account that has been disabled due to failed authentication attempts. Use with -SecurePassword to set a new password while unlocking, or with -Force to unlock without changing the password. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -PasswordMustChange Forces the user to change their password at next login. Requires -SecurePassword and both PasswordPolicyEnforced and PasswordExpirationEnabled to be enabled. Use this for security compliance when setting temporary passwords or after potential password compromises. | Property | Value | | --- | --- | | Alias | MustChange | | Required | False | | Pipeline | false | | Default Value | False | -NewName Renames the login to a new name. The new name must not already exist on the SQL Server instance. Use this when standardizing login naming conventions or correcting login names during organizational changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Disable Disables the login account, preventing authentication while preserving the account and its permissions. Use this for temporary account suspension during investigations or when employees are on extended leave. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Enable Enables a previously disabled login account, restoring authentication access with all existing permissions intact. Use this to reactivate accounts after temporary suspension or when employees return from extended leave. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DenyLogin Explicitly denies the login permission to connect to the SQL Server instance. The account remains but cannot authenticate. Use this for permanent access restriction while maintaining the login for audit trails or future reference. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -GrantLogin Grants or restores the login permission to connect to the SQL Server instance, reversing a previous deny action. Use this to restore access for logins that were previously denied without recreating the entire account. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -PasswordPolicyEnforced Enables or disables Windows password policy enforcement for the login (check_policy). Must be enabled to use password expiration checks. Use this to apply corporate password complexity and lockout policies to SQL Server authentication accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -PasswordExpirationEnabled Enables or disables password expiration checking for the login (check_expiration). Requires PasswordPolicyEnforced to be enabled first. Use this to enforce regular password changes according to Windows password age policies for SQL Server accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AddRole Grants one or more server-level roles to the login. Accepts: bulkadmin, dbcreator, diskadmin, processadmin, public, securityadmin, serveradmin, setupadmin, sysadmin. Use this to assign specific server privileges without granting full sysadmin rights, following the principle of least privilege. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this to reduce login privileges during access reviews or when job responsibilities change. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this for bulk operations when you need to modify logins based on specific criteria like locked status or role membership. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Force Unlocks a login account without requiring a password reset by temporarily manipulating password policy settings. Use this when you need to unlock accounts but cannot change the password, preserving the original password for the user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Login Returns 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. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: Login name DenyLogin: Boolean indicating if login is denied access to the instance IsDisabled: Boolean indicating if the login is disabled IsLocked: Boolean indicating if the login is locked due to failed authentication attempts PasswordPolicyEnforced: Boolean indicating if Windows password policy is enforced for the login PasswordExpirationEnabled: Boolean indicating if password expiration is enforced for the login MustChangePassword: Boolean indicating if the password must be changed at next login PasswordChanged: Boolean indicating if the password was changed in this operation ServerRole: Comma-separated list of server roles assigned to the login Notes: String containing any notes or errors encountered during the operation Additional properties available (from SMO Login object): LoginType: Type of login (SqlLogin, WindowsUser, WindowsGroup, Certificate, AsymmetricKey) DefaultDatabase: Default database the login connects to CreateDate: DateTime when the login was created DateLastModified: DateTime of the last modification PasswordExpirationEnabled: Password expiration setting PasswordPolicyEnforced: Password policy enforcement setting DaysSinceLastLogin: Number of days since the login last authenticated Sid: Security identifier for the login All properties from the base SMO Login object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Set-DbaMaxDop",
    "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's 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.",
    "category": "Utilities",
    "tags": [
      "maxdop",
      "utility"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaMaxDop",
    "popularityRank": 319,
    "synopsis": "Configures SQL Server maximum degree of parallelism (MaxDOP) at instance or database level",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaMaxDop View Source Claudio Silva (@claudioessilva) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures SQL Server maximum degree of parallelism (MaxDOP) at instance or database level 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's 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. Syntax Set-DbaMaxDop [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-MaxDop] ] [[-InputObject] ] [-AllDatabases] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets Max DOP to the recommended value for servers sql2008 and sql2012 PS C:\\> Set-DbaMaxDop -SqlInstance sql2008, sql2012 Example 2: Sets Max DOP to 4 for server sql2014 PS C:\\> Set-DbaMaxDop -SqlInstance sql2014 -MaxDop 4 Example 3: Gets the recommended Max DOP from Test-DbaMaxDop and applies it to to sql2008 PS C:\\> Test-DbaMaxDop -SqlInstance sql2008 | Set-DbaMaxDop Example 4: Set recommended Max DOP for database db1 on server sql2016 PS C:\\> Set-DbaMaxDop -SqlInstance sql2016 -Database db1 Example 5: Set recommended Max DOP for all databases on server sql2016 PS C:\\> Set-DbaMaxDop -SqlInstance sql2016 -AllDatabases Optional Parameters -SqlInstance The target SQL Server instance or instances. Defaults to localhost. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to configure with database-scoped MaxDOP settings. Only works on SQL Server 2016 and higher. Use this when you need different MaxDOP values for specific databases with unique workload characteristics. Cannot be combined with AllDatabases or ExcludeDatabase parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to skip when applying database-scoped MaxDOP settings. Only works on SQL Server 2016 and higher. Use this when you want to configure most databases but leave certain ones (like system databases) unchanged. Cannot be combined with Database or AllDatabases parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaxDop Sets a specific MaxDOP value instead of using the recommended value from Test-DbaMaxDop. Use this when you have specific performance requirements or want to override the automatic recommendations. Common values are 1 (disable parallelism), 2-4 (typical OLTP), or higher values for data warehouse workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | -1 | -InputObject Accepts the output from Test-DbaMaxDop to avoid re-analyzing server hardware and current settings. Use this when you want to review the recommendations first or apply settings from a previously saved analysis. Can be piped directly from Test-DbaMaxDop for streamlined workflows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -AllDatabases Applies database-scoped MaxDOP settings to all databases on the instance. Only works on SQL Server 2016 and higher. Use this when you want consistent MaxDOP values across all databases rather than relying on instance-level settings. Cannot be combined with Database or ExcludeDatabase parameters. | Property | Value | | --- | --- | | Alias | All | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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 configuration is being modified. Instance-level MaxDOP configuration (default): Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) PreviousInstanceMaxDopValue: The MaxDOP value before this change CurrentInstanceMaxDop: The newly configured MaxDOP value (number of processors) Database-level MaxDOP configuration (SQL Server 2016+, with -Database, -AllDatabases, or -ExcludeDatabase): Properties: InstanceName: The SQL Server instance name Database: The name of the database with the new MaxDOP setting PreviousDatabaseMaxDopValue: The MaxDOP value for this database before this change CurrentDatabaseMaxDopValue: The newly configured MaxDOP value for this database &nbsp;"
  },
  {
    "name": "Set-DbaMaxMemory",
    "description": "Modifies the SQL Server 'Max Server Memory' 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's 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't account for everything that may\nbe going on in your specific environment.",
    "category": "Performance",
    "tags": [
      "maxmemory",
      "memory"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaMaxMemory",
    "popularityRank": 145,
    "synopsis": "Configures SQL Server 'Max Server Memory' setting using calculated recommendations or explicit values",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaMaxMemory View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures SQL Server 'Max Server Memory' setting using calculated recommendations or explicit values Description Modifies the SQL Server 'Max Server Memory' configuration to prevent SQL Server from consuming all available system memory. This setting controls how much memory SQL Server can allocate for its buffer pool and other memory consumers, leaving adequate memory for the operating system and other applications. When no explicit value is provided, the function calculates an optimal recommendation using a proven formula that reserves memory based on total system RAM. This formula accounts for operating system overhead, scales appropriately for servers with different memory configurations, and can handle multiple SQL Server instances on the same server. Inspired by Jonathan Kehayias's post about SQL Server Max memory (http://bit.ly/sqlmemcalc), this uses a formula to determine the default optimum RAM to use, then sets the SQL max value to that number. Jonathan notes that the formula used provides a general recommendation that doesn't account for everything that may be going on in your specific environment. Syntax Set-DbaMaxMemory [[-SqlInstance] ] [[-SqlCredential] ] [[-Max] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Set max memory to the recommended on just one server named &quot;sqlserver1&quot; PS C:\\> Set-DbaMaxMemory sqlserver1 Example 2: Explicitly set max memory to 2048 on just one server, &quot;sqlserver1&quot; PS C:\\> Set-DbaMaxMemory -SqlInstance sqlserver1 -Max 2048 Example 3: Find all servers in SQL Server Central Management Server that have Max SQL memory set to higher than the... PS C:\\> Get-DbaRegServer -SqlInstance sqlserver | Test-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total } | Set-DbaMaxMemory Find all servers in SQL Server Central Management Server that have Max SQL memory set to higher than the total memory of the server (think 2147483647), then pipe those to Set-DbaMaxMemory and use the default recommendation. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Max Specifies the explicit maximum memory value in megabytes for SQL Server to use. When provided, this overrides the automatic memory recommendation calculation. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -InputObject Accepts output objects from Test-DbaMaxMemory containing memory analysis results for one or more SQL Server instances. Use this to pipeline memory testing results directly into memory configuration, allowing you to review recommendations before applying changes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance showing the configured memory settings. This object is derived from Test-DbaMaxMemory output with added tracking properties. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Total: Total system memory available on the server in megabytes MaxValue: The newly configured SQL Server max memory setting in megabytes PreviousMaxValue: The previous SQL Server max memory setting in megabytes before this change &nbsp;"
  },
  {
    "name": "Set-DbaNetworkCertificate",
    "description": "Sets the network certificate for SQL Server instance in two possible ways. This setting is found in Configuration Manager.\n\nWithout the Certificate or Thumbprint parameter (Way One): Calls Test-DbaNetworkCertificate to retrieve\ninformation about the currently configured certificate and available suitable certificates.\nReturns without changes if the currently configured certificate is still valid.\nConfigures the suitable certificate if exactly one is available.\nFails if more than one or no suitable certificate is found.\n\nWith the Certificate or Thumbprint parameter (Way Two): Calls Test-DbaNetworkCertificate to retrieve\ninformation about the currently configured certificate and available suitable certificates.\nReturns without changes if the given certificate match the currently configured certificate that is still valid.\nConfigures the given certificate if it is returned as a suitable certificate.\nIf the given certificate is not returned as a suitable certificate, the command gets detailed information\nabout why the given certificate is not suitable and fails with that information.\n\nThis command also grants read permissions for the service account on the certificate's private key.\n\nThe currently configured certificate can be unset by using the parameter -UnsetCertificate.\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/\nhttps://learn.microsoft.com/en-us/sql/database-engine/configure-windows/certificate-requirements",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaNetworkCertificate",
    "popularityRank": 58,
    "synopsis": "Sets the network certificate for SQL Server instance",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Set-DbaNetworkCertificate View Source Chrissy LeMaire (@cl), netnerds.net , Refactored by Andreas Jordan (@andreasjordan) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Sets the network certificate for SQL Server instance Description Sets the network certificate for SQL Server instance in two possible ways. This setting is found in Configuration Manager. Without the Certificate or Thumbprint parameter (Way One): Calls Test-DbaNetworkCertificate to retrieve information about the currently configured certificate and available suitable certificates. Returns without changes if the currently configured certificate is still valid. Configures the suitable certificate if exactly one is available. Fails if more than one or no suitable certificate is found. With the Certificate or Thumbprint parameter (Way Two): Calls Test-DbaNetworkCertificate to retrieve information about the currently configured certificate and available suitable certificates. Returns without changes if the given certificate match the currently configured certificate that is still valid. Configures the given certificate if it is returned as a suitable certificate. If the given certificate is not returned as a suitable certificate, the command gets detailed information about why the given certificate is not suitable and fails with that information. This command also grants read permissions for the service account on the certificate's private key. The currently configured certificate can be unset by using the parameter -UnsetCertificate. References: https://www.itprotoday.com/sql-server/7-steps-ssl-encryption https://azurebi.jppp.org/2016/01/23/using-lets-encrypt-certificates-for-secure-sql-server-connections/ https://blogs.msdn.microsoft.com/sqlserverfaq/2016/09/26/creating-and-registering-ssl-certificates/ https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/certificate-requirements Syntax Set-DbaNetworkCertificate [[-SqlInstance] ] [[-Credential] ] [[-Certificate] ] [[-Thumbprint] ] [-UnsetCertificate] [-RestartService] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates and imports a new certificate signed by an Active Directory CA on localhost then sets the network... PS C:\\> New-DbaComputerCertificate | Set-DbaNetworkCertificate -SqlInstance localhost\\SQL2008R2SP2 Creates 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. Example 2: Sets the network certificate for the SQL2008R2SP2 instance if exactly one suitable certificate is found PS C:\\> Set-DbaNetworkCertificate -SqlInstance localhost\\SQL2008R2SP2 Example 3: Sets the network certificate for the SQL2008R2SP2 instance to the certificate with the thumbprint of... PS C:\\> Set-DbaNetworkCertificate -SqlInstance sql1\\SQL2008R2SP2 -Thumbprint 1223FB1ACBCA44D3EE9640F81B6BA14A92F3D6E2 Sets the network certificate for the SQL2008R2SP2 instance to the certificate with the thumbprint of 1223FB1ACBCA44D3EE9640F81B6BA14A92F3D6E2 in LocalMachine\\My on sql1 Example 4: Unsets the network certificate for the SQL2008R2SP2 instance and restarts the SQL Server service PS C:\\> Set-DbaNetworkCertificate -SqlInstance localhost\\SQL2008R2SP2 -UnsetCertificate -RestartService Optional Parameters -SqlInstance The target SQL Server instance or instances. Defaults to localhost. | Property | Value | | --- | --- | | Alias | ComputerName | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to the computer (not sql instance) using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -Certificate Specifies the X509Certificate2 object to configure as the network certificate for SQL Server. Use this when piping certificate objects from other dbatools commands like New-DbaComputerCertificate. The certificate must exist in the LocalMachine certificate store and have a private key for SQL Server to use it for SSL connections. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Thumbprint Specifies the thumbprint (SHA-1 hash) of the certificate to configure as the network certificate. Use this when you know the specific certificate thumbprint from certificates already installed in LocalMachine\\My. Must be a 40-character hexadecimal string (no spaces). The certificate must have a private key and the SQL Server service account will be granted read permissions to it. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -UnsetCertificate Unsets the currently configured network certificate for the SQL Server instance. This will remove the certificate configuration, and SQL Server will not use any certificate for SSL connections. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -RestartService Forces an automatic restart of the SQL Server service after setting the network certificate. Certificate changes require a service restart to take effect - without this switch you'll need to manually restart SQL Server. Use this when you want the SSL configuration to be immediately active, but be aware it will cause a brief service interruption. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance processed, containing the following properties: ComputerName: The name of the computer where the SQL Server instance is hosted InstanceName: The SQL Server instance name (e.g., MSSQLSERVER, SQL2008R2SP2) SqlInstance: The full SQL Server instance name (computer\\instance) ServiceAccount: The service account running the SQL Server instance CertificateThumbprint: The SHA-1 thumbprint of the newly configured certificate in lowercase Notes: Summary of actions performed, including whether an old certificate was replaced &nbsp;"
  },
  {
    "name": "Set-DbaNetworkConfiguration",
    "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'll 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",
    "category": "Utilities",
    "tags": [
      "network",
      "connection",
      "sqlwmi"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaNetworkConfiguration",
    "popularityRank": 294,
    "synopsis": "Modifies SQL Server network protocol settings including TCP/IP, Named Pipes, and Shared Memory configurations.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Set-DbaNetworkConfiguration View Source Andreas Jordan (@JordanOrdix), ordix.de Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies SQL Server network protocol settings including TCP/IP, Named Pipes, and Shared Memory configurations. 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. Common 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. Network configuration changes require a SQL Server service restart to take effect - use the RestartService parameter to handle this automatically, otherwise you'll need to restart the service manually afterward. Uses remote SQL WMI by default with PowerShell remoting as a fallback. Requires administrative privileges on the target server. For detailed property explanations see: https://docs.microsoft.com/en-us/sql/tools/configuration-manager/sql-server-network-configuration Syntax Set-DbaNetworkConfiguration [-SqlInstance] [-Credential ] [-EnableProtocol ] [-DisableProtocol ] [-DynamicPortForIPAll] [-StaticPortForIPAll ] [-IpAddress ] [-RestartService] [-EnableException] [-WhatIf] [-Confirm] [ ] Set-DbaNetworkConfiguration [-Credential ] [-RestartService] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Ensures that the shared memory network protocol for the default instance on sql2016 is enabled PS C:\\> Set-DbaNetworkConfiguration -SqlInstance sql2016 -EnableProtocol SharedMemory -RestartService Ensures that the shared memory network protocol for the default instance on sql2016 is enabled. Restarts the service if needed. Example 2: Ensures that the TCP/IP network protocol is enabled and configured to use the ports 14331 and 14332 for all... PS C:\\> Set-DbaNetworkConfiguration -SqlInstance sql2016\\test -StaticPortForIPAll 14331, 14332 -RestartService Ensures that the TCP/IP network protocol is enabled and configured to use the ports 14331 and 14332 for all IP addresses. Restarts the service if needed. Example 3: Changes the value of the KeepAlive property for the default instance on sqlserver2014a and restarts the... PS C:\\> $netConf = Get-DbaNetworkConfiguration -SqlInstance sqlserver2014a PS C:\\> $netConf.TcpIpProperties.KeepAlive = 60000 PS C:\\> $netConf | Set-DbaNetworkConfiguration -RestartService -Confirm:$false Changes the value of the KeepAlive property for the default instance on sqlserver2014a and restarts the service. Does not prompt for confirmation. Example 4: Ensures that the TCP/IP network protocol is enabled and configured to only listen on port 1433 of IP address... PS C:\\> Set-DbaNetworkConfiguration -SqlInstance sql2016\\test -IpAddress 192.168.3.41:1433 -RestartService Ensures that the TCP/IP network protocol is enabled and configured to only listen on port 1433 of IP address 192.168.3.41. Restarts the service if needed. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts a network configuration object from Get-DbaNetworkConfiguration for making complex property changes. Use this when you need to modify specific TCP/IP properties like KeepAlive values or make multiple configuration changes. The Get-DbaNetworkConfiguration command must use -OutputType Full to provide the complete configuration object. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Credential object used to connect to the Computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableProtocol Enables a specific SQL Server network protocol for client connections. Use SharedMemory for local-only connections, NamedPipes for legacy applications, or TcpIp for remote access. TCP/IP is required for remote connections and most modern applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | SharedMemory,NamedPipes,TcpIp | -DisableProtocol Disables a specific SQL Server network protocol to prevent client connections via that method. Commonly used to disable unneeded protocols for security or troubleshooting purposes. Be cautious disabling TCP/IP as it will prevent all remote connections to the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | SharedMemory,NamedPipes,TcpIp | -DynamicPortForIPAll Configures the instance to use a random port assigned by Windows for all IP addresses. Use this for non-production environments or when you don't need predictable port numbers. Automatically enables TCP/IP protocol and sets ListenAll to true, clearing any existing static port configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -StaticPortForIPAll Configures the instance to use specific port numbers for all IP addresses instead of dynamic ports. Essential for production environments where firewall rules require predictable port numbers. Automatically enables TCP/IP protocol and sets ListenAll to true. Accepts multiple ports as comma-separated values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IpAddress Restricts the instance to listen only on specified IP addresses instead of all available interfaces. Use this on multi-homed servers to control which network interfaces accept SQL Server connections. Format 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\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RestartService Automatically restarts the SQL Server service when network configuration changes are made. Network configuration changes only take effect after a service restart, so use this to avoid manual restarts. Without this parameter, you must manually restart the SQL Server service for changes to become active. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance whose network configuration was modified, containing the details of changes applied and service restart status. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Changes: Array of strings describing each configuration change made (e.g., \"Changed TcpIpEnabled to True\") RestartNeeded: Boolean indicating whether a SQL Server service restart is required for changes to take effect Restarted: Boolean indicating whether the SQL Server service was successfully restarted Exception: System.Exception object if an error occurred during WMI operations (may be present if changes failed) All 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 to take effect. &nbsp;"
  },
  {
    "name": "Set-DbaPowerPlan",
    "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/",
    "category": "Performance",
    "tags": [
      "powerplan",
      "os",
      "configure",
      "utility"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaPowerPlan",
    "popularityRank": 463,
    "synopsis": "Configures Windows power plan on SQL Server host computers to optimize database performance.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Set-DbaPowerPlan View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures Windows power plan on SQL Server host computers to optimize database performance. 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. Windows 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. If 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. References: https://support.microsoft.com/en-us/kb/2207548 http://www.sqlskills.com/blogs/glenn/windows-power-plan-effects-on-newer-intel-processors/ Syntax Set-DbaPowerPlan [-ComputerName] [[-Credential] ] [[-PowerPlan] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the Power Plan to High Performance PS C:\\> Set-DbaPowerPlan -ComputerName sql2017 Sets the Power Plan to High Performance. Skips it if its already set. Example 2: Sets the Power Plan to Balanced for Server1 and Server2 PS C:\\> 'Server1', 'Server2' | Set-DbaPowerPlan -PowerPlan Balanced Sets the Power Plan to Balanced for Server1 and Server2. Skips it if its already set. Example 3: Connects using alternative Windows credential and sets the Power Plan to High Performance PS C:\\> $cred = Get-Credential 'Domain\\User' PS C:\\> Set-DbaPowerPlan -ComputerName sql2017 -Credential $cred Connects using alternative Windows credential and sets the Power Plan to High Performance. Skips it if its already set. Example 4: Sets the Power Plan to &quot;Maximum Performance&quot; PS C:\\> Set-DbaPowerPlan -ComputerName sqlcluster -PowerPlan 'Maximum Performance' Sets the Power Plan to \"Maximum Performance\". Skips it if its already set. Example 5: Uses the Power Plan of oldserver as best practice and sets the Power Plan of newserver1 and newserver2... PS C:\\> Get-DbaPowerPlan -ComputerName oldserver | Set-DbaPowerPlan -ComputerName newserver1, newserver2 Uses the Power Plan of oldserver as best practice and sets the Power Plan of newserver1 and newserver2 accordingly. Required Parameters -ComputerName Specifies the Windows host computers where SQL Server instances are running to configure the power plan. Accepts multiple server names and connects via WMI and PowerShell remoting to change OS-level power settings. Use the actual Windows computer names, not SQL Server instance names. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | Optional Parameters -Credential Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -PowerPlan Specifies the Windows power plan to set on the target computers. Defaults to \"High Performance\" when not specified. Use this when your organization has a custom power plan or specific requirements beyond the default recommendation. Run Get-DbaPowerPlan -ComputerName -List to see all available power plans on each computer before setting. | Property | Value | | --- | --- | | Alias | CustomPowerPlan,RecommendedPowerPlan | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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 their power plan changed. Default display properties (via Select-DefaultView): ComputerName: The target computer name PreviousPowerPlan: The name of the power plan that was active before the operation ActivePowerPlan: The name of the current active power plan (same as PreviousPowerPlan if no change, updated if changed) IsChanged: Boolean indicating whether the power plan was changed (True if changed, False if already set to the target plan) *Additional properties available using Select-Object :** PreviousInstanceId: The unique GUID identifier of the power plan that was active before the operation ActiveInstanceId: The unique GUID identifier of the current active power plan &nbsp;"
  },
  {
    "name": "Set-DbaPrivilege",
    "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, Generate Security Audits, and Create Global Objects. 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).",
    "category": "Utilities",
    "tags": [
      "privilege",
      "security"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaPrivilege",
    "popularityRank": 199,
    "synopsis": "Grants essential Windows privileges to SQL Server service accounts for optimal performance and security.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Set-DbaPrivilege View Source Klaas Vandenberghe (@PowerDbaKlaas) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Grants essential Windows privileges to SQL Server service accounts for optimal performance and security. 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, Generate Security Audits, and Create Global Objects. 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. Requires Local Admin rights on destination computer(s). Syntax Set-DbaPrivilege [[-ComputerName] ] [[-Credential] ] [-Type] [-EnableException] [[-User] ] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Adds the SQL Service account(s) on computer sqlserver2014a to the local privileges &#39;SeManageVolumePrivilege&#39;... PS C:\\> Set-DbaPrivilege -ComputerName sqlserver2014a -Type LPIM,IFI Adds the SQL Service account(s) on computer sqlserver2014a to the local privileges 'SeManageVolumePrivilege' and 'SeLockMemoryPrivilege'. Example 2: Adds the SQL Service account(s) on computers sql1, sql2 and sql3 to the local privilege... PS C:\\> 'sql1','sql2','sql3' | Set-DbaPrivilege -Type IFI Adds the SQL Service account(s) on computers sql1, sql2 and sql3 to the local privilege 'SeManageVolumePrivilege'. Required Parameters -Type Specifies which Windows privileges to grant to the SQL Server service accounts. Accepts one or more values: 'IFI' (Instant File Initialization), 'LPIM' (Lock Pages in Memory), 'BatchLogon' (Log on as a batch job), 'SecAudit' (Generate security audits), 'ServiceLogon' (Log on as a service), and 'CreateGlobalObjects' (Create global objects). These privileges are essential for SQL Server performance and functionality - IFI speeds up database file operations, LPIM prevents memory paging for better performance, the logon rights ensure services can start properly, and CreateGlobalObjects is required by certain backup solutions (e.g. Dell PowerProtect, Redgate, Veritas) whose SQL backup agents need to create named objects in the Global namespace. Multiple privileges can be specified together for comprehensive SQL Server optimization. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | | Accepted Values | IFI,LPIM,BatchLogon,SecAudit,ServiceLogon,CreateGlobalObjects | Optional Parameters -ComputerName The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Credential object used to connect to the computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -User Specifies a custom user account to receive the privileges instead of automatically discovering SQL Server service accounts. Use 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't work in your environment. Accepts domain accounts (DOMAIN\\User) or local accounts - ensure the account exists and will be used by SQL Server services. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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 Verbose level). &nbsp;"
  },
  {
    "name": "Set-DbaResourceGovernor",
    "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.",
    "category": "Utilities",
    "tags": [
      "resourcegovernor"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaResourceGovernor",
    "popularityRank": 640,
    "synopsis": "Configures SQL Server Resource Governor to control workload resource allocation and sets classifier functions.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaResourceGovernor View Source John McCall (@lowlydba), lowlydba.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures SQL Server Resource Governor to control workload resource allocation and sets classifier functions. 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. This 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. Commonly 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. Syntax Set-DbaResourceGovernor [-SqlInstance] [[-SqlCredential] ] [-Enabled] [-Disabled] [[-ClassifierFunction] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets Resource Governor to enabled for the instance sql2016 PS C:\\> Set-DbaResourceGovernor -SqlInstance sql2016 -Enabled Example 2: Sets Resource Governor to disabled for the instance dev1 on sq2012 PS C:\\> Set-DbaResourceGovernor -SqlInstance sql2012\\dev1 -Disabled Example 3: Sets Resource Governor to enabled for the instance dev1 on sq2012 and sets the classifier function to be... PS C:\\> Set-DbaResourceGovernor -SqlInstance sql2012\\dev1 -ClassifierFunction 'fnRGClassifier' -Enabled Sets Resource Governor to enabled for the instance dev1 on sq2012 and sets the classifier function to be 'fnRGClassifier'. Example 4: Sets Resource Governor to enabled for the instance dev1 on sq2012 and sets the classifier function to be NULL PS C:\\> Set-DbaResourceGovernor -SqlInstance sql2012\\dev1 -ClassifierFunction 'NULL' -Enabled Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Credential object used to connect to the Windows server as a different user | Property | Value | | --- | --- | | Alias | Credential | | Required | False | | Pipeline | false | | Default Value | | -Enabled Enables Resource Governor on the SQL Server instance to activate workload resource management. Use this when you need to enforce resource limits and allocations for different workload groups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Disabled Disables Resource Governor on the SQL Server instance, removing all resource controls and workload management. All sessions will use unlimited resources from the default resource pool when Resource Governor is disabled. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ClassifierFunction Specifies the name of a user-defined function in the master database that determines which workload group incoming sessions should use. The function must return a workload group name or ID based on session properties like login name or application name. Use 'NULL' to remove the current classifier function and route all sessions to the default workload group. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.ResourceGovernor Returns the modified Resource Governor object reflecting the new enabled/disabled state and classifier function assignment. Output is piped from Get-DbaResourceGovernor which provides detailed configuration details. Default display properties (via Get-DbaResourceGovernor): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Enabled: Boolean indicating if Resource Governor is currently enabled ClassifierFunction: Name of the classifier function currently assigned (NULL if none) RecoveryPriority: Recovery priority setting for resource allocation State: Current state of the Resource Governor (Existing, Creating, etc.) All properties from the base SMO ResourceGovernor object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Set-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.",
    "category": "Utilities",
    "tags": [
      "resourcepool",
      "resourcegovernor"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaRgResourcePool",
    "popularityRank": 679,
    "synopsis": "Modifies CPU, memory, and IOPS limits for existing SQL Server Resource Governor pools.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaRgResourcePool View Source John McCall (@lowlydba), lowlydba.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies CPU, memory, and IOPS limits for existing SQL Server Resource Governor pools. Description Modifies resource allocation settings for existing Resource Governor pools to control how much CPU, memory, and disk I/O different workloads can consume. This lets you adjust performance limits after analyzing workload patterns or when server capacity changes. Works with both internal pools (for SQL Server queries) and external pools (for R Services, Python, or other external processes). The Resource Governor is automatically reconfigured to apply changes immediately unless you skip reconfiguration. Syntax Set-DbaRgResourcePool [-SqlInstance ] [-SqlCredential ] [-ResourcePool ] [-Type ] [-MinimumCpuPercentage ] [-MaximumCpuPercentage ] [-CapCpuPercentage ] [-MinimumMemoryPercentage ] [-MaximumMemoryPercentage ] [-MinimumIOPSPerVolume ] [-MaximumIOPSPerVolume ] [-SkipReconfigure] [-InputObject ] [-EnableException] [-WhatIf] [-Confirm] [ ] Set-DbaRgResourcePool [-SqlInstance ] [-SqlCredential ] [-ResourcePool ] [-Type ] [-MinimumCpuPercentage ] [-MaximumCpuPercentage ] [-CapCpuPercentage ] [-MinimumMemoryPercentage ] [-MaximumMemoryPercentage ] [-MinimumIOPSPerVolume ] [-MaximumIOPSPerVolume ] [-SkipReconfigure] [-InputObject ] [-EnableException] [-WhatIf] [-Confirm] [ ] Set-DbaRgResourcePool [-SqlInstance ] [-SqlCredential ] [-ResourcePool ] [-Type ] [-MinimumCpuPercentage ] [-MaximumCpuPercentage ] [-CapCpuPercentage ] [-MinimumMemoryPercentage ] [-MaximumMemoryPercentage ] [-MinimumIOPSPerVolume ] [-MaximumIOPSPerVolume ] [-MaximumProcesses ] [-SkipReconfigure] [-InputObject ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Configures a resource pool named &quot;poolAdmin&quot; for the instance sql2016 with a Maximum CPU Percent of 5 PS C:\\> Set-DbaRgResourcePool-SqlInstance sql2016 -ResourcePool \"poolAdmin\" -MaximumCpuPercentage 5 Example 2: Configures a resource pool named &quot;poolDeveloper&quot; for the instance dev1 on sq2012 PS C:\\> Set-DbaRgResourcePool-SqlInstance sql2012\\dev1 -ResourcePool \"poolDeveloper\" -SkipReconfigure Configures a resource pool named \"poolDeveloper\" for the instance dev1 on sq2012. Reconfiguration is skipped and the Resource Governor will not be able to use the new resource pool until it is reconfigured. Example 3: Configures all user internal resource pools to have a minimum memory percent of 10 for the instance sql2016... PS C:\\> Get-DbaRgResourcePool -SqlInstance sql2016 -Type \"Internal\" | Where-Object { $_.IsSystemObject -eq $false } | Set-DbaRgResourcePool -MinMemoryPercent 10 Configures all user internal resource pools to have a minimum memory percent of 10 for the instance sql2016 by piping output from Get-DbaRgResourcePool. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | -SqlCredential Credential object used to connect to the Windows server as a different user | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ResourcePool Specifies the name of the existing resource pool to modify. Use this to target specific pools like 'poolAdmin' or 'poolDeveloper' when you need to adjust their resource limits. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies whether to modify Internal or External resource pools. Internal pools control SQL Server queries and connections, while External pools manage R Services, Python, or other external processes. Defaults to Internal if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Internal | | Accepted Values | Internal,External | -MinimumCpuPercentage Sets the guaranteed minimum CPU percentage (0-100) that this pool will always receive during CPU contention. Use this to ensure critical workloads get sufficient CPU even when the server is busy. For example, set to 20 to guarantee a pool always gets at least 20% of available CPU. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | 0 | -MaximumCpuPercentage Sets the maximum CPU percentage (1-100) that this pool can consume during CPU contention. Use this to prevent runaway queries from monopolizing CPU resources. For example, set to 30 to limit a development pool to 30% of available CPU. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | 0 | -CapCpuPercentage Sets an absolute hard cap (1-100) on CPU usage that cannot be exceeded even when CPU is available. Unlike MaximumCpuPercentage, this limit applies regardless of server load or contention. Only available on SQL Server 2012 and later. Use this for strict resource isolation requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | 0 | -MinimumMemoryPercentage Sets the minimum memory percentage (0-100) that is reserved exclusively for this pool and cannot be shared. Use this to guarantee memory for critical workloads that must have dedicated memory allocation. For example, set to 15 to ensure a production pool always has at least 15% of server memory reserved. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | 0 | -MaximumMemoryPercentage Sets the maximum memory percentage (1-100) that this pool can consume from total server memory. Use this to prevent memory-intensive workloads from consuming all available memory. Defaults to 100, meaning no memory restrictions. Set lower values like 50 to limit pool memory usage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | 0 | -MinimumIOPSPerVolume Sets the minimum guaranteed IOPS per disk volume that this pool will receive during I/O contention. Use this to ensure critical workloads get sufficient disk I/O performance even when storage is busy. For example, set to 1000 to guarantee at least 1000 IOPS per volume for a production pool. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | 0 | -MaximumIOPSPerVolume Sets the maximum IOPS per disk volume that this pool can consume during I/O operations. Use this to prevent I/O-intensive workloads from overwhelming disk subsystems and affecting other pools. For example, set to 5000 to limit a reporting pool to 5000 IOPS per volume. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | 0 | -MaximumProcesses Sets the maximum number of external processes allowed in this external resource pool. Only applies to External pool types used for R Services, Python, or other external runtime processes. Set to 0 for unlimited processes (limited only by server resources), or specify a number like 10 to restrict concurrent external processes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -SkipReconfigure Prevents automatic reconfiguration of the Resource Governor after making pool changes. Use this when making multiple pool modifications and you want to reconfigure manually later. Without reconfiguration, your pool changes won't take effect until you manually reconfigure the Resource Governor. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts resource pool objects piped from Get-DbaRgResourcePool for bulk modifications. Use this to modify multiple pools at once by piping them from Get-DbaRgResourcePool. Eliminates the need to specify SqlInstance and ResourcePool parameters when working with existing pool objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.ResourcePool or Microsoft.SqlServer.Management.Smo.ExternalResourcePool Returns the modified resource pool object with added connection context properties. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: Unique identifier for the resource pool Name: Name of the resource pool CapCpuPercentage: CPU percentage cap for the pool (SQL Server 2012+) IsSystemObject: Boolean indicating if this is a system resource pool MaximumCpuPercentage: Maximum CPU percentage the pool can consume MaximumIopsPerVolume: Maximum IOPS per disk volume for the pool MaximumMemoryPercentage: Maximum memory percentage the pool can consume MinimumCpuPercentage: Guaranteed minimum CPU percentage for the pool MinimumIopsPerVolume: Guaranteed minimum IOPS per disk volume for the pool MinimumMemoryPercentage: Guaranteed minimum memory percentage for the pool WorkloadGroups: Collection of workload groups associated with this pool All properties from the base SMO ResourcePool or ExternalResourcePool objects are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Set-DbaRgWorkloadGroup",
    "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).",
    "category": "Utilities",
    "tags": [
      "resourcepool",
      "resourcegovernor"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaRgWorkloadGroup",
    "popularityRank": 680,
    "synopsis": "Modifies Resource Governor workload group settings to control query resource consumption and limits.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaRgWorkloadGroup View Source John McCall (@lowlydba), lowlydba.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies Resource Governor workload group settings to control query resource consumption and limits. 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. Use 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. Changes automatically trigger a Resource Governor reconfiguration unless skipped, and plan-affecting settings only apply to new query plans after clearing the procedure cache. Supports both internal resource pools (standard workloads) and external resource pools (R/Python integration scenarios). Syntax Set-DbaRgWorkloadGroup [[-SqlInstance] ] [[-SqlCredential] ] [[-WorkloadGroup] ] [[-ResourcePool] ] [[-ResourcePoolType] ] [[-Importance] ] [[-RequestMaximumMemoryGrantPercentage] ] [[-RequestMaximumCpuTimeInSeconds] ] [[-RequestMemoryGrantTimeoutInSeconds] ] [[-MaximumDegreeOfParallelism] ] [[-GroupMaximumRequests] ] [-SkipReconfigure] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Configures a workload group named &quot;groupAdmin&quot; in the resource pool &quot;poolAdmin&quot; for the instance sql2016 PS C:\\> Set-DbaRgWorkloadGroup -SqlInstance sql2016 -WorkloadGroup \"groupAdmin\" -ResourcePool \"poolAdmin\" Example 2: Configures a workload group named &quot;groupSuperUsers&quot; by setting the maximum number of group requests to 2 for... PS C:\\> Get-DbaRgWorkloadGroup | Where-Object Name -eq \"groupSuperUsers\" | Set-DbaRgWorkloadGroup -GroupMaximumRequests 2 Configures a workload group named \"groupSuperUsers\" by setting the maximum number of group requests to 2 for the instance sql2016. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Credential object used to connect to the Windows server as a different user | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -WorkloadGroup Name of the specific workload group to modify within the resource pool. Use this to target individual workload groups when you need to adjust resource limits for specific application categories or user groups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ResourcePool Name of the resource pool that contains the workload group to be modified. Required when specifying WorkloadGroup by name rather than piping from Get-DbaRgWorkloadGroup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ResourcePoolType Specifies whether to target Internal resource pools (standard SQL workloads) or External resource pools (R/Python integration scenarios). Choose Internal for typical database workloads, or External when managing Machine Learning Services resource allocation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Internal,External | -Importance Sets the relative priority level for requests within this workload group compared to other groups in the same resource pool. Use HIGH for critical business applications, MEDIUM for standard workloads, or LOW for background processes that can tolerate delays. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | LOW,MEDIUM,HIGH | -RequestMaximumMemoryGrantPercentage Sets the maximum percentage of the resource pool's memory that any single query can request for operations like sorting and hashing. Values range from 1-100 percent. Use lower values to prevent single queries from monopolizing memory resources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RequestMaximumCpuTimeInSeconds Defines the maximum CPU time in seconds that any single request can consume before being terminated. Set this to prevent runaway queries from consuming excessive CPU resources. Use 0 for unlimited CPU time. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RequestMemoryGrantTimeoutInSeconds Sets how long queries can wait for memory grants before timing out with insufficient memory errors. Increase this for environments with heavy memory contention, or decrease to fail fast when memory is unavailable. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -MaximumDegreeOfParallelism Controls the maximum number of parallel processors that queries in this workload group can use. Override the server-level MAXDOP setting for specific workload groups to optimize resource allocation based on workload characteristics. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -GroupMaximumRequests Limits the total number of concurrent requests that can execute simultaneously within this workload group. Use this to prevent resource pool saturation by limiting how many queries from this group can run at once. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -SkipReconfigure Prevents automatic Resource Governor reconfiguration after making workload group changes. Use this when making multiple configuration changes and you want to reconfigure manually once at the end to minimize disruption. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts workload group objects piped from Get-DbaRgWorkloadGroup for bulk configuration operations. Allows you to modify multiple workload groups across different instances in a single pipeline operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.WorkloadGroup Returns 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 resource constraints. The 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 changes. Properties available on the returned WorkloadGroup objects include: Name: Name of the workload group Importance: Relative priority level (LOW, MEDIUM, or HIGH) RequestMaximumMemoryGrantPercentage: Maximum memory percentage per query request RequestMaximumCpuTimeInSeconds: Maximum CPU time per request RequestMemoryGrantTimeoutInSeconds: Memory grant timeout setting MaximumDegreeOfParallelism: Maximum parallel processors for queries GroupMaximumRequests: Maximum concurrent requests limit Parent: Reference to the parent ResourcePool or ExternalResourcePool object &nbsp;"
  },
  {
    "name": "Set-DbaSpConfigure",
    "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'll 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.",
    "category": "Utilities",
    "tags": [
      "spconfigure"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaSpConfigure",
    "popularityRank": 155,
    "synopsis": "Modifies SQL Server instance-level configuration settings through sp_configure",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaSpConfigure View Source Nic Cain, sirsql.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies SQL Server instance-level configuration settings through sp_configure 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. For dynamic settings, changes take effect immediately. For static settings, you'll receive a warning that SQL Server must be restarted before the new value becomes active. Built-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. Syntax Set-DbaSpConfigure [[-SqlInstance] ] [[-SqlCredential] ] [[-Value] ] [[-Name] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Adjusts the Scan for startup stored procedures configuration value to 1 and notifies the user that this... PS C:\\> Set-DbaSpConfigure -SqlInstance localhost -Name ScanForStartupProcedures -Value 1 Adjusts the Scan for startup stored procedures configuration value to 1 and notifies the user that this requires a SQL restart to take effect Example 2: Sets the values for XPCmdShellEnabled and IsSqlClrEnabled on sql2017 and sql2014 to False PS C:\\> Get-DbaSpConfigure -SqlInstance sql2017, sql2014 -Name XPCmdShellEnabled, IsSqlClrEnabled | Set-DbaSpConfigure -Value $false Example 3: Adjusts the xp_cmdshell configuration value to 1 PS C:\\> Set-DbaSpConfigure -SqlInstance localhost -Name XPCmdShellEnabled -Value 1 Example 4: Returns information on the action that would be performed PS C:\\> Set-DbaSpConfigure -SqlInstance localhost -Name XPCmdShellEnabled -Value 1 -WhatIf Returns information on the action that would be performed. No actual change will be made. Optional Parameters -SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Value Sets the new configuration value within the setting's valid range (minimum to maximum). The function validates the value against SQL Server's defined limits to prevent invalid configurations that could prevent startup or cause performance issues. | Property | Value | | --- | --- | | Alias | NewValue,NewConfig | | Required | False | | Pipeline | false | | Default Value | 0 | -Name Specifies which SQL Server configuration setting to modify, such as 'max server memory (MB)', 'xp_cmdshell', or 'cost threshold for parallelism'. Use this when targeting specific settings by name instead of piping from Get-DbaSpConfigure. | Property | Value | | --- | --- | | Alias | Config,ConfigName | | Required | False | | Pipeline | false | | Default Value | | -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 based on current values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per configuration setting successfully modified. Each object contains the change details including the configuration name and before/after values. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ConfigName: Name of the configuration setting that was modified PreviousValue: The previous configured value before the change (integer) NewValue: The new value that was set (integer) If 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. &nbsp;"
  },
  {
    "name": "Set-DbaSpn",
    "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",
    "category": "Server Management",
    "tags": [
      "spn"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaSpn",
    "popularityRank": 106,
    "synopsis": "Sets an SPN for a given service account in active directory (and also enables delegation to the same SPN by default)",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Set-DbaSpn View Source Drew Furgiuele (@pittfurg), port1433.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Sets an SPN for a given service account in active directory (and also enables delegation to the same SPN by default) 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. Note: This function supports -WhatIf Syntax Set-DbaSpn [-SPN] [-ServiceAccount] [[-Credential] ] [-NoDelegation] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Connects to Active Directory and adds a provided SPN to the given account PS C:\\> Set-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account PS C:\\> Set-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account -EnableException Connects to Active Directory and adds a provided SPN to the given account. Connects to Active Directory and adds a provided SPN to the given account, suppressing all error messages and throw exceptions that can be caught instead Example 2: Connects to Active Directory and adds a provided SPN to the given account PS C:\\> Set-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account -Credential ad\\sqldba Connects to Active Directory and adds a provided SPN to the given account. Uses alternative account to connect to AD. Example 3: Connects to Active Directory and adds a provided SPN to the given account, without the delegation PS C:\\> Set-DbaSpn -SPN MSSQLSvc/SQLSERVERA.domain.something -ServiceAccount domain\\account -NoDelegation Example 4: Sets all missing SPNs for sql2016 PS C:\\> Test-DbaSpn -ComputerName sql2016 | Where-Object { $_.isSet -eq $false } | Set-DbaSpn Example 5: Displays what would happen trying to set all missing SPNs for sql2016 PS C:\\> Test-DbaSpn -ComputerName sql2016 | Where-Object { $_.isSet -eq $false } | Set-DbaSpn -WhatIf Required Parameters -SPN Specifies the Service Principal Name to register in Active Directory for SQL Server Kerberos authentication. Must follow the format 'MSSQLSvc/hostname:port' or 'MSSQLSvc/FQDN:port' for named instances. Use this to enable Kerberos authentication and eliminate double-hop authentication issues. | Property | Value | | --- | --- | | Alias | RequiredSPN | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | -ServiceAccount Specifies the Active Directory account that runs the SQL Server service and will own the SPN. Can be a domain user account (domain\\username) or computer account (computername$) depending on your SQL Server service configuration. This account must exist in Active Directory and you must have permissions to modify its properties. | Property | Value | | --- | --- | | Alias | InstanceServiceAccount,AccountName | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -Credential The credential you want to use to connect to Active Directory to make the changes | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -NoDelegation Prevents automatic configuration of Kerberos constrained delegation for the specified SPN. Use this when you want to manually configure delegation later or when delegation is not required for your environment. By default, the function enables constrained delegation to allow the service account to authenticate to other services. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command was executed | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Turns confirmations before changes on or off | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one or two objects per service account processed, depending on delegation configuration: SPN Registration Result Object (always returned): Name (string) - The Service Principal Name that was added ServiceAccount (string) - The Active Directory account that owns the SPN Property (string) - Always \"servicePrincipalName\" indicating the AD property that was modified IsSet (boolean) - True if the SPN was successfully added, False if the operation failed Notes (string) - Status message: \"Successfully added SPN\" or \"Failed to add SPN\" Delegation Configuration Result Object (conditionally returned): Name (string) - The Service Principal Name for which delegation was configured ServiceAccount (string) - The Active Directory account for which delegation was configured Property (string) - Always \"msDS-AllowedToDelegateTo\" indicating the AD property that was modified IsSet (boolean) - True if constrained delegation was successfully enabled, False if the operation failed Notes (string) - Status message: \"Successfully added constrained delegation\" or \"Failed to add constrained delegation\" The delegation object is only returned when: The SPN was successfully added (IsSet = $true for the first object) AND the -NoDelegation parameter was NOT specified AND the ShouldProcess check passed (when -WhatIf is not used) When -NoDelegation is specified, only the SPN registration object is returned. &nbsp;"
  },
  {
    "name": "Set-DbaStartupParameter",
    "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't 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",
    "category": "Utilities",
    "tags": [
      "startup",
      "parameter",
      "configure"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaStartupParameter",
    "popularityRank": 165,
    "synopsis": "Modifies SQL Server startup parameters stored in the Windows registry",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Set-DbaStartupParameter View Source Stuart Moore (@napalmgram), stuart-moore.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Modifies SQL Server startup parameters stored in the Windows registry 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. This 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. The 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't start. For 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 Syntax Set-DbaStartupParameter [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [[-MasterData] ] [[-MasterLog] ] [[-ErrorLog] ] [[-TraceFlag] ] [-CommandPromptStart] [-MinimalStart] [[-MemoryToReserve] ] [-SingleUser] [[-SingleUserDetails] ] [-NoLoggingToWinEvents] [-StartAsNamedInstance] [-DisableMonitoring] [-IncreasedExtents] [-TraceFlagOverride] [[-StartupConfig] ] [-Offline] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Will configure the SQL Instance server1\\instance1 to startup up in Single User mode at next startup PS C:\\> Set-DbaStartupParameter -SqlInstance server1\\instance1 -SingleUser Example 2: Will configure the SQL Instance sql2016 to IncreasedExtents = True (-E) PS C:\\> Set-DbaStartupParameter -SqlInstance sql2016 -IncreasedExtents Example 3: Shows what would happen if you attempted to configure the SQL Instance sql2016 to IncreasedExtents = False... PS C:\\> Set-DbaStartupParameter -SqlInstance sql2016 -IncreasedExtents:$false -WhatIf Shows what would happen if you attempted to configure the SQL Instance sql2016 to IncreasedExtents = False (no -E) Example 4: This will append Trace Flags 8032 and 8048 to the startup parameters PS C:\\> Set-DbaStartupParameter -SqlInstance server1\\instance1 -TraceFlag 8032,8048 Example 5: This will remove all trace flags and set SingleUser to false PS C:\\> Set-DbaStartupParameter -SqlInstance sql2016 -SingleUser:$false -TraceFlagOverride Example 6: This will set Trace Flags 8032 and 8048 to the startup parameters, removing any existing Trace Flags PS C:\\> Set-DbaStartupParameter -SqlInstance server1\\instance1 -SingleUser -TraceFlag 8032,8048 -TraceFlagOverride Example 7: This will remove all trace flags and set SingleUser to false from an offline instance PS C:\\> Set-DbaStartupParameter -SqlInstance sql2016 -SingleUser:$false -TraceFlagOverride -Offline Example 8: This will attempt to change the ErrorLog path to c:\\sql\\ PS C:\\> Set-DbaStartupParameter -SqlInstance sql2016 -ErrorLog c:\\Sql\\ -Offline This 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: Set-DbaStartupParameter -SqlInstance sql2016 -ErrorLog c:\\Sql\\ -Offline -Force Example 9: In this example we take a copy of the existing startup configuration of server1\\instance1 We then change the... PS C:\\> $StartupConfig = Get-DbaStartupParameter -SqlInstance server1\\instance1 PS C:\\> Set-DbaStartupParameter -SqlInstance server1\\instance1 -SingleUser -NoLoggingToWinEvents PS C:\\> #Restart your SQL instance with the tool of choice PS C:\\> #Do Some work PS C:\\> Set-DbaStartupParameter -SqlInstance server1\\instance1 -StartupConfig $StartupConfig PS C:\\> #Restart your SQL instance with the tool of choice and you're back to normal In this example we take a copy of the existing startup configuration of server1\\instance1 We then change the startup parameters ahead of some work After the work has been completed, we can push the original startup parameters back to server1\\instance1 and resume normal operation Required Parameters -SqlInstance The SQL Server instance to be modified If the Sql Instance is offline path parameters will be ignored as we cannot test the instance's access to the path. If you want to force this to work then please use the Force switch | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Windows Credential with permission to log on to the server running the SQL instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MasterData Specifies the file path to the master database data file (master.mdf). Required when relocating system databases or recovering from corrupted system files. Use 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 accessible by the SQL Server service account. Will be ignored if SqlInstance is offline unless the Force parameter is used, as the function validates the path accessibility when the instance is online. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MasterLog Specifies the file path to the master database log file (mastlog.ldf). Required when relocating system databases or recovering from corrupted system files. Use 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 account. Will be ignored if SqlInstance is offline unless the Force parameter is used, as the function validates the path accessibility when the instance is online. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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 service account. Will be ignored if SqlInstance is offline unless the Force parameter is used, as the function validates the path accessibility when the instance is online. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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 to existing trace flags. Use TraceFlagOverride parameter to replace all existing trace flags instead of appending to them. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CommandPromptStart Enables faster startup when SQL Server is launched from command prompt rather than as a Windows service. Bypasses Service Control Manager initialization routines. Use this when you need to start SQL Server manually for troubleshooting or testing scenarios where you'll be running sqlservr.exe directly from command line instead of using service management tools. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when SQL Server won't start normally due to configuration problems like excessive memory allocation, corrupted configuration settings, or problematic startup procedures. Essential for emergency recovery scenarios. Note that many features will be unavailable in minimal start mode, making it suitable only for troubleshooting and corrective actions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MemoryToReserve Specifies the amount of memory in megabytes to reserve outside the SQL Server buffer pool for system components and extended procedures. Use 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 reserved memory hosts DLL files, distributed query providers, and automation objects. Default value is 256 MB, but you may need to increase this on servers with heavy use of extended procedures or CLR integration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this for emergency maintenance, database recovery operations, or when you need exclusive access to troubleshoot corruption or perform administrative tasks that require isolation. Combine with SingleUserDetails parameter to restrict access to a specific login for additional security during maintenance windows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this to ensure only authorized personnel can access the instance during maintenance windows, preventing applications or other users from grabbing the single available connection. Can specify a login name, domain account, or application name. Automatically quoted if the value contains spaces. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. SQL Server will continue writing to its own error log files regardless of this setting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -StartAsNamedInstance Enables starting a named instance of SQL Server, ensuring proper instance identification and network connectivity for non-default instances. Use 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 server. Required for named instances to register properly with SQL Server Browser service and establish correct network endpoints. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisableMonitoring Disables SQL Server's internal performance monitoring and statistics collection to reduce overhead on high-performance systems. Use 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 SQLPERF data, some DMVs, and many extended events. Warning: This significantly reduces your ability to diagnose performance issues and should only be used when monitoring overhead is confirmed to impact critical workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncreasedExtents Increases the number of extents allocated for each file in a file group, improving allocation efficiency for databases with multiple data files. Use this on systems with multiple data files per filegroup to reduce allocation contention and improve performance during heavy insert/update operations. Particularly beneficial for tempdb configurations with multiple data files or user databases designed with multiple files for performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when you need to completely reset the trace flag configuration or remove problematic trace flags that are causing issues. If no TraceFlag values are provided with this switch, all existing trace flags will be removed from the startup parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -StartupConfig Applies a complete startup configuration object previously captured with Get-DbaStartupParameter. Restores all startup parameters to match the saved configuration. Use this to quickly restore previous startup configurations after troubleshooting, rollback changes during maintenance, or standardize startup parameters across multiple instances. Automatically enables TraceFlagOverride, so all existing trace flags will be replaced with those from the saved configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Offline Performs startup parameter changes without attempting to connect to the SQL Server instance, improving performance when you know the instance is not running. Use this when modifying startup parameters for instances that are intentionally stopped or when you want to avoid connection overhead on known offline instances. When using this switch, file path parameters (MasterData, MasterLog, ErrorLog) cannot be validated and will be ignored unless the Force parameter is also specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Bypasses file path validation for MasterData, MasterLog, and ErrorLog parameters, allowing changes even when paths cannot be verified. Use 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. Exercise caution as invalid paths will prevent SQL Server from starting, requiring manual registry editing to correct. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Object with added NoteProperties Returns the startup parameter object from Get-DbaStartupParameter with additional context properties added: Base properties (from Get-DbaStartupParameter): CommandPromptStart (boolean) - Whether command prompt start flag (-c) is enabled DisableMonitoring (boolean) - Whether performance monitoring is disabled (-x) ErrorLog (string) - Path to the error log file (-e parameter) IncreasedExtents (boolean) - Whether increased extents flag (-E) is enabled MasterData (string) - Path to master database data file (-d parameter) MasterLog (string) - Path to master database log file (-l parameter) MemoryToReserve (int) - Memory reserved in MB (-g parameter) MinimalStart (boolean) - Whether minimal start flag (-f) is enabled NoLoggingToWinEvents (boolean) - Whether Windows event logging is disabled (-n) ParameterString (string) - Complete startup parameter string as stored in registry SingleUser (boolean) - Whether single-user mode (-m) is enabled SingleUserDetails (string) - Specific login allowed in single-user mode (if specified) StartAsNamedInstance (boolean) - Whether named instance flag (-s) is enabled TraceFlags (string) - Comma-separated list of enabled trace flags (-T parameters) Added properties: OriginalStartupParameters (string) - The startup parameter string before any modifications (added to all outputs) Notes (string) - Message indicating changes were made and restart is required (added when Credential parameter not provided) &nbsp;"
  },
  {
    "name": "Set-DbaTcpPort",
    "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.",
    "category": "Utilities",
    "tags": [
      "network",
      "connection",
      "tcp",
      "configure"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaTcpPort",
    "popularityRank": 291,
    "synopsis": "Configures SQL Server TCP port settings for specified instances and IP addresses.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Set-DbaTcpPort View Source @H0s0n77 Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures SQL Server TCP port settings for specified instances and IP addresses. 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. The 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. Important: 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. Syntax Set-DbaTcpPort [-SqlInstance] [[-Credential] ] [-Port] [[-IpAddress] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Sets the port number 1433 for all IP Addresses on the default instance on sql2017 PS C:\\> Set-DbaTcpPort -SqlInstance sql2017 -Port 1433 Sets the port number 1433 for all IP Addresses on the default instance on sql2017. Prompts for confirmation. Example 2: Sets the port number 1433 for IP 192.168.1.22 on the sqlexpress instance on winserver PS C:\\> Set-DbaTcpPort -SqlInstance winserver\\sqlexpress -IpAddress 192.168.1.22 -Port 1433 -Confirm:$false Sets the port number 1433 for IP 192.168.1.22 on the sqlexpress instance on winserver. Does not prompt for confirmation. Example 3: Sets the port number 1337 for all IP Addresses on SqlInstance sql2017 and sql2019 using the credentials for... PS C:\\> Set-DbaTcpPort -SqlInstance sql2017, sql2019 -port 1337 -Credential ad\\dba -Force Sets 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. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Port Specifies the TCP port number for SQL Server to listen on, replacing any existing static or dynamic port configuration. Use this to move SQL Server off the default port 1433 for security hardening or to configure custom ports for named instances. Accepts any valid port number between 1 and 65535, with common choices being 1433 (default), 1434, or organization-specific port ranges. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -Credential Credential object used to connect to the Windows server itself as a different user (like SQL Configuration Manager). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IpAddress Specifies which IP address should listen on the configured port instead of applying to all IP addresses. Use this for multi-homed servers where you need SQL Server to listen only on specific network interfaces. When omitted, the port change applies to all IP addresses (IPAll setting), which is the typical configuration for most servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Automatically restarts the SQL Server Database Engine service to apply the new port configuration immediately. Use this when you need the port change to take effect right away instead of waiting for the next service restart. Without this parameter, you must manually restart SQL Server before the new port settings become active. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.Void This command does not return any output to the pipeline. It modifies SQL Server network configuration and optionally restarts services. When -Force is used, the Database Engine service is restarted to apply the port configuration changes immediately. &nbsp;"
  },
  {
    "name": "Set-DbaTempDbConfig",
    "description": "Configures tempdb database files to follow Microsoft's 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's logical cores, but you can override this behavior. It validates the current tempdb configuration to ensure it won't 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'll need to shrink it manually before running this function. A SQL Server restart is required for tempdb changes to take effect.",
    "category": "Utilities",
    "tags": [
      "tempdb",
      "configuration"
    ],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbaTempDbConfig",
    "popularityRank": 143,
    "synopsis": "Configures tempdb database files according to Microsoft best practices for optimal performance",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbaTempDbConfig View Source Michael Fal (@Mike_Fal), mikefal.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures tempdb database files according to Microsoft best practices for optimal performance Description Configures tempdb database files to follow Microsoft's 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. The function automatically determines the appropriate number of data files based on your server's logical cores, but you can override this behavior. It validates the current tempdb configuration to ensure it won't 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. Additional 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'll need to shrink it manually before running this function. A SQL Server restart is required for tempdb changes to take effect. Syntax Set-DbaTempDbConfig [-SqlInstance] [[-SqlCredential] ] [[-DataFileCount] ] [-DataFileSize] [[-LogFileSize] ] [[-DataFileGrowth] ] [[-LogFileGrowth] ] [[-DataPath] ] [[-LogPath] ] [[-OutFile] ] [-OutputScriptOnly] [-DisableGrowth] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Creates tempdb with a number of data files equal to the logical cores where each file is equal to 1000MB... PS C:\\> Set-DbaTempDbConfig -SqlInstance localhost -DataFileSize 1000 Creates 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. Example 2: Creates tempdb with 8 data files, each one sized at 125MB, with a log file of 250MB PS C:\\> Set-DbaTempDbConfig -SqlInstance localhost -DataFileSize 1000 -DataFileCount 8 Example 3: Provides a SQL script output to configure tempdb according to the passed parameters PS C:\\> Set-DbaTempDbConfig -SqlInstance localhost -DataFileSize 1000 -OutputScriptOnly Example 4: Disables the growth for the data and log files PS C:\\> Set-DbaTempDbConfig -SqlInstance localhost -DataFileSize 1000 -DisableGrowth Example 5: Returns the T-SQL script representing tempdb configuration PS C:\\> Set-DbaTempDbConfig -SqlInstance localhost -DataFileSize 1000 -OutputScriptOnly Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -DataFileSize Sets the total size in MB for all tempdb data files combined. This value gets evenly divided across all data files. For example, 1000MB with 4 files creates four 250MB files. Choose based on your workload's tempdb usage patterns and available storage. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | 0 | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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). Override 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -LogFileSize Sets the tempdb log file size in MB. When omitted, the existing log file size remains unchanged. Use this to resize the log file when current sizing doesn't match your tempdb transaction volume requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -DataFileGrowth Controls the growth increment for tempdb data files in MB when they need to expand. Defaults to 512 MB. Set 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 512 | -LogFileGrowth Controls the growth increment for the tempdb log file in MB when it needs to expand. Defaults to 512 MB. Size this according to your transaction log activity in tempdb to minimize auto-growth events during peak workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 512 | -DataPath Sets the folder path(s) where tempdb data files will be created. When omitted, uses the current tempdb data file location. Specify multiple paths to distribute files across different drives for performance. Files are distributed round-robin across the provided paths. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LogPath Sets the folder path where the tempdb log file will be created. When omitted, uses the current tempdb log file location. Consider placing the log file on a separate drive from data files to reduce I/O contention for write-heavy tempdb workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OutFile Saves the generated T-SQL script to the specified file path instead of executing it. Useful for storing configuration scripts in source control or running them later through scheduled maintenance processes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -OutputScriptOnly Returns the generated T-SQL script without executing it against the SQL Server instance. Use this to review the configuration changes before applying them, or to run the script manually during maintenance windows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisableGrowth Prevents tempdb files from auto-growing by setting growth to 0. Overrides any values specified for -DataFileGrowth and -LogFileGrowth. Use this when you want to pre-size tempdb files appropriately and prevent unexpected growth during production workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject (default behavior) Returns configuration details after successfully applying tempdb settings. Contains the following properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DataFileCount: The number of data files configured (int) DataFileSize: Total size for all data files combined; dbasize object convertible to Bytes, KB, MB, GB, TB SingleDataFileSize: Size of each individual data file; dbasize object convertible to Bytes, KB, MB, GB, TB LogSize: Size of the transaction log file; dbasize object convertible to Bytes, KB, MB, GB, TB DataPath: Path(s) where tempdb data files are located (string or string array) LogPath: Path where the tempdb log file is located (string) DataFileGrowth: Growth increment for data files; dbasize object convertible to Bytes, KB, MB, GB, TB LogFileGrowth: Growth increment for log file; dbasize object convertible to Bytes, KB, MB, GB, TB System.String[] (when -OutputScriptOnly is specified) Returns array of T-SQL ALTER DATABASE statements that would configure tempdb without executing them. System.Void (when -OutFile is specified) No output is returned to the pipeline when -OutFile is used; the T-SQL script is written directly to the specified file path. &nbsp;"
  },
  {
    "name": "Set-DbatoolsConfig",
    "description": "This function creates or changes configuration values. These can be used to provide dynamic configuration information outside the PowerShell variable system.",
    "category": "Utilities",
    "tags": [],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbatoolsConfig",
    "popularityRank": 65,
    "synopsis": "Sets configuration entries.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbatoolsConfig View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters Synopsis Sets configuration entries. Description This function creates or changes configuration values. These can be used to provide dynamic configuration information outside the PowerShell variable system. Syntax Set-DbatoolsConfig -FullName [-Value ] [-Description ] [-Validation ] [-Handler ] [-Hidden] [-Default] [-Initialize] [-DisableValidation] [-DisableHandler] [-EnableException] [-SimpleExport] [-ModuleExport] [-PassThru] [-AllowDelete] [ ] Set-DbatoolsConfig -FullName [-Description ] [-Validation ] [-Handler ] [-Hidden] [-Default] [-Initialize] [-DisableValidation] [-DisableHandler] [-EnableException] -PersistedValue [-PersistedType ] [-SimpleExport] [-ModuleExport] [-PassThru] [-AllowDelete] [ ] Set-DbatoolsConfig -Name [-Module ] [-Value ] [-Description ] [-Validation ] [-Handler ] [-Hidden] [-Default] [-Initialize] [-DisableValidation] [-DisableHandler] [-EnableException] [-SimpleExport] [-ModuleExport] [-PassThru] [-AllowDelete] [ ] &nbsp; Examples &nbsp; Example Example 1: Simple: Updates the configuration entry for Path.DbatoolsData to E:\\temp\\dbatools PS C:\\> Set-DbatoolsConfig -FullName Path.DbatoolsData -Value E:\\temp\\dbatools Required Parameters -FullName | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Name | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -PersistedValue | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -Default | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Description | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DisableHandler | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DisableValidation | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Handler | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Hidden | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Initialize | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Module | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ModuleExport | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PassThru | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PersistedType | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Register | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SimpleExport | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Validation | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Value | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | &nbsp;"
  },
  {
    "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",
    "category": "Utilities",
    "tags": [],
    "verb": "Set",
    "popular": true,
    "url": "/Set-DbatoolsInsecureConnection",
    "popularityRank": 11,
    "synopsis": "Reverts SQL Server connection security defaults to disable encryption and trust all certificates",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbatoolsInsecureConnection View Source Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Reverts SQL Server connection security defaults to disable encryption and trust all certificates 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. The 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. This is particularly useful when working with development servers, self-signed certificates, or legacy environments where the new security defaults cause connection failures. You can read more here: https://dbatools.io/newdefaults Syntax Set-DbatoolsInsecureConnection [-SessionOnly] [[-Scope] {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [-Register] [ ] &nbsp; Examples &nbsp; Example 1: Sets the default connection settings to trust all server certificates and not require encrypted connections PS C:\\> Set-DbatoolsInsecureConnection Example 2: Sets the default connection settings to trust all server certificates and not require encrypted connections PS C:\\> Set-DbatoolsInsecureConnection -SessionOnly Sets the default connection settings to trust all server certificates and not require encrypted connections. Does not persist across sessions so the default will return if you close and reopen PowerShell. Optional Parameters -SessionOnly Applies the insecure connection settings only to the current PowerShell session instead of persisting them permanently. Use this when testing connection settings or when you need insecure connections temporarily without changing your permanent dbatools configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Scope Specifies where to store the persistent connection settings when SessionOnly is not used. Defaults to UserDefault. UserDefault applies to the current user only, while SystemDefault applies to all users on the machine. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UserDefault | -Register This parameter is deprecated and will be removed in a future release. The function now automatically handles registration of settings when SessionOnly is not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs None This command configures dbatools connection security settings but does not output any objects to the pipeline. The internal configuration values are applied silently to enable insecure connections (disabled encryption, trusted certificates). &nbsp;"
  },
  {
    "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.",
    "category": "Utilities",
    "tags": [],
    "verb": "Set",
    "popular": false,
    "url": "/Set-DbatoolsPath",
    "popularityRank": 585,
    "synopsis": "Configures or updates a path under a name.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Set-DbatoolsPath View Source Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Configures or updates a path under a name. Description Configures or updates a path under a name. The path can be persisted using the \"-Register\" command. Paths setup like this can be retrieved using Get-DbatoolsPath. Syntax Set-DbatoolsPath -Name -Path [ ] Set-DbatoolsPath -Name -Path -Register [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [ ] &nbsp; Examples &nbsp; Example 1: Configures C:\\temp as the current temp path PS C:\\> Set-DbatoolsPath -Name 'temp' -Path 'C:\\temp' Configures C:\\temp as the current temp path. (does not override $Env:TEMP !) Required Parameters -Name Specifies the alias name to associate with the path for easy retrieval. Use descriptive names like 'backups', 'scripts', or 'logs' to organize commonly used directory paths. The name can be referenced later with Get-DbatoolsPath to quickly access the stored path. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Path Specifies the directory path to store under the given name. Can be any valid file system path including network shares and mapped drives. Use this to centralize path management for backup locations, script directories, or output folders. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Register Persists the path configuration across PowerShell sessions and module reloads. Without this switch, the path mapping only exists for the current session. Essential when setting up permanent path aliases for team environments or automated scripts. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | False | Optional Parameters -Scope Determines where the persistent configuration is stored when using -Register. UserDefault stores the setting for the current user only, while other scopes affect system-wide or module-level settings. Choose the appropriate scope based on whether the path should be available to all users or just the current user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UserDefault | Outputs None This command configures internal dbatools path settings but does not output any objects to the pipeline. Use Get-DbatoolsPath to retrieve the configured path values. &nbsp;"
  },
  {
    "name": "Show-DbaDbList",
    "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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "filesystem"
    ],
    "verb": "Show",
    "popular": false,
    "url": "/Show-DbaDbList",
    "popularityRank": 284,
    "synopsis": "Displays available databases in an interactive selection window",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Show-DbaDbList View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Displays available databases in an interactive selection window 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. The 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. Clicking OK returns the selected database name, while Cancel returns null, allowing your scripts to handle user cancellation gracefully. Syntax Show-DbaDbList [-SqlInstance] [[-SqlCredential] ] [[-Title] ] [[-Header] ] [[-DefaultDb] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Shows a GUI list of databases using Windows Authentication to connect to the SQL Server PS C:\\> Show-DbaDbList -SqlInstance sqlserver2014a Shows a GUI list of databases using Windows Authentication to connect to the SQL Server. Returns a string of the selected database. Example 2: Shows a GUI list of databases using SQL credentials to connect to the SQL Server PS C:\\> Show-DbaDbList -SqlInstance sqlserver2014a -SqlCredential $cred Shows a GUI list of databases using SQL credentials to connect to the SQL Server. Returns a string of the selected database. Example 3: Shows a GUI list of databases using Windows Authentication to connect to the SQL Server PS C:\\> Show-DbaDbList -SqlInstance sqlserver2014a -DefaultDb master Shows 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. Required Parameters -SqlInstance The target SQL Server instance or instances.. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Title Sets the title text that appears in the window's title bar. Defaults to \"Select Database\". Use this to customize the dialog title for specific maintenance scripts or to indicate the purpose of the database selection. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Select Database | -Header Specifies the instruction text displayed above the database tree view. Defaults to \"Select the database:\". Customize this to provide context-specific instructions like \"Choose database to backup:\" or \"Select database for maintenance:\". | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Select the database: | -DefaultDb Pre-selects a specific database when the selection dialog opens. Use this when you have a preferred or most commonly selected database to reduce clicks for end users. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String Returns the name of the selected database when the user selects a database and clicks OK. For example: \"master\", \"msdb\", \"model\", \"tempdb\", or any user-created database name. Returns $null if the user cancels the dialog, closes the window without selecting a database, or if the OK button is not explicitly clicked. &nbsp;"
  },
  {
    "name": "Show-DbaInstanceFileSystem",
    "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's 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.",
    "category": "Server Management",
    "tags": [
      "storage",
      "filesystem",
      "os"
    ],
    "verb": "Show",
    "popular": false,
    "url": "/Show-DbaInstanceFileSystem",
    "popularityRank": 329,
    "synopsis": "Displays a GUI tree view for browsing remote SQL Server file systems and returns the selected directory path",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Show-DbaInstanceFileSystem View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Displays a GUI tree view for browsing remote SQL Server file systems and returns the selected directory 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's 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. Show-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. Syntax Show-DbaInstanceFileSystem [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Shows a list of databases using Windows Authentication to connect to the SQL Server PS C:\\> Show-DbaInstanceFileSystem -SqlInstance sql2017 Shows a list of databases using Windows Authentication to connect to the SQL Server. Returns a string of the selected path. Example 2: Shows a list of databases using SQL credentials to connect to the SQL Server PS C:\\> Show-DbaInstanceFileSystem -SqlInstance sql2017 -SqlCredential $cred Shows a list of databases using SQL credentials to connect to the SQL Server. Returns a string of the selected path. Required Parameters -SqlInstance The target SQL Server instance or instances. Defaults to localhost. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.String Returns the full directory path with trailing backslash when the user selects a folder and clicks OK. For example: \"C:\\\", \"D:\\Backup\\\", or \"C:\\Program Files\\Microsoft SQL Server\\\". Returns $null if the user cancels the dialog or closes the window without selecting a path. &nbsp;"
  },
  {
    "name": "Start-DbaAgentJob",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "job",
      "agent"
    ],
    "verb": "Start",
    "popular": false,
    "url": "/Start-DbaAgentJob",
    "popularityRank": 116,
    "synopsis": "Starts SQL Server Agent jobs and optionally waits for completion",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Start-DbaAgentJob View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Starts SQL Server Agent jobs and optionally waits for completion 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. Syntax Start-DbaAgentJob [-SqlCredential ] [-Job ] [-StepName ] [-ExcludeJob ] [-AllJobs] [-Wait] [-Parallel] [-WaitPeriod ] [-SleepPeriod ] [-EnableException] [-WhatIf] [-Confirm] [ ] Start-DbaAgentJob -SqlInstance [-SqlCredential ] [-Job ] [-StepName ] [-ExcludeJob ] [-AllJobs] [-Wait] [-Parallel] [-WaitPeriod ] [-SleepPeriod ] [-EnableException] [-WhatIf] [-Confirm] [ ] Start-DbaAgentJob [-SqlCredential ] [-Job ] [-StepName ] [-ExcludeJob ] -InputObject [-AllJobs] [-Wait] [-Parallel] [-WaitPeriod ] [-SleepPeriod ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Starts all running SQL Agent Jobs on the local SQL Server instance PS C:\\> Start-DbaAgentJob -SqlInstance localhost Example 2: Starts the cdc.DBWithCDC_capture SQL Agent Job on sql2016 PS C:\\> Get-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture | Start-DbaAgentJob Example 3: Starts the cdc.DBWithCDC_capture SQL Agent Job on sql2016 PS C:\\> Start-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture Example 4: Restarts all failed jobs on all servers in the $servers collection PS C:\\> $servers | Find-DbaAgentJob -IsFailed | Start-DbaAgentJob Example 5: Start all the jobs PS C:\\> Start-DbaAgentJob -SqlInstance sql2016 -AllJobs Example 6: This is a serialized approach to submitting jobs and waiting for each job to continue the next PS C:\\> Start-DbaAgentJob -SqlInstance sql2016 -Job @('Job1', 'Job2', 'Job3') -Wait This is a serialized approach to submitting jobs and waiting for each job to continue the next. Starts Job1, waits for completion of Job1 Starts Job2, waits for completion of Job2 Starts Job3, Waits for completion of Job3 Example 7: This is a parallel approach to submitting all jobs and waiting for them all to complete PS C:\\> Start-DbaAgentJob -SqlInstance sql2016 -Job @('Job1', 'Job2', 'Job3') -Wait -Parallel This is a parallel approach to submitting all jobs and waiting for them all to complete. Starts Job1, starts Job2, starts Job3 and waits for completion of Job1, Job2, and Job3. Example 8: Starts the JobWith5Steps SQL Agent Job at step Step4 PS C:\\> Start-DbaAgentJob -SqlInstance sql2016 -Job JobWith5Steps -StepName Step4 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts SQL Agent job objects from the pipeline, typically from Get-DbaAgentJob or other dbatools functions. Use this when chaining dbatools commands together to start jobs that meet specific criteria, such as failed jobs or jobs with certain schedules. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies the names of specific SQL Agent jobs to start. Accepts job names as strings and supports multiple job names in an array. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StepName Specifies the job step name where job execution should begin instead of starting from the first step. Use this to resume a failed job at a specific step or to test individual job steps without running the entire job sequence. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJob Specifies job names to exclude from starting when using -AllJobs or when no specific jobs are specified. Use this to start all jobs except certain ones, such as excluding maintenance jobs during business hours or problematic jobs that need special handling. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllJobs Starts all SQL Agent jobs that are currently in an idle state on the target instance. Use this switch when you need to start all available jobs, typically after server maintenance or during bulk job execution scenarios. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Wait Waits for each job to complete execution before returning results or proceeding to the next job. Use this when you need to ensure job completion before continuing your script, or when jobs have dependencies that require sequential execution. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Parallel Starts all specified jobs simultaneously and waits for all to complete, rather than starting and waiting for each job sequentially. Use this when jobs can run concurrently without conflicts to reduce total execution time. Requires the -Wait parameter to function. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WaitPeriod Sets the polling interval in seconds for checking job status when using the -Wait parameter. Defaults to 3 seconds. Adjust 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 3 | -SleepPeriod Sets the initial wait time in milliseconds after starting a job before checking its status. Defaults to 300 milliseconds. Increase this value if you experience issues with jobs not showing as started immediately, which can occur on heavily loaded servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 300 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.Job Returns 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 (without -Wait). Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the SQL Agent job CurrentRunStatus: The current execution status of the job (Idle, Executing, etc.) LastRunDate: DateTime of the most recent job execution LastRunOutcome: Outcome of the last run (Succeeded, Failed, Cancelled, etc.) IsEnabled: Boolean indicating if the job is enabled HasSchedule: Boolean indicating if the job has schedules OwnerLoginName: Login that owns the job Additional properties available (from SMO Agent.Job object): JobSteps: Collection of job steps defined in this job Schedules: Collection of schedules assigned to this job Notifications: Notification settings for the job Category: The job category name CategoryID: The job category ID CreatedDate: DateTime when the job was created Description: Job description text Note: 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 returning results. &nbsp;"
  },
  {
    "name": "Start-DbaDbEncryption",
    "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't 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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Start",
    "popular": false,
    "url": "/Start-DbaDbEncryption",
    "popularityRank": 317,
    "synopsis": "Implements Transparent Data Encryption (TDE) on user databases with automated key infrastructure and backup management",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Start-DbaDbEncryption View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Implements Transparent Data Encryption (TDE) on user databases with automated key infrastructure and backup management 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. The 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't miss critical backup steps that could leave your encrypted databases unrecoverable. Most 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. Syntax Start-DbaDbEncryption [[-SqlInstance] ] [[-SqlCredential] ] [[-EncryptorName] ] [[-EncryptorType] ] [[-Database] ] [[-ExcludeDatabase] ] [-BackupPath] [-MasterKeySecurePassword] [[-CertificateSubject] ] [[-CertificateStartDate] ] [[-CertificateExpirationDate] ] [-CertificateActiveForServiceBrokerDialog] [-BackupSecurePassword] [[-InputObject] ] [-AllUserDatabases] [-Force] [-Parallel] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Prompts for two passwords (the username doesn&#39;t matter, this is just an easy &amp; secure way to get a secure... PS C:\\> $masterkeypass = (Get-Credential justneedpassword).Password PS C:\\> $certbackuppass = (Get-Credential justneedpassword).Password PS C:\\> $params = @{ >> SqlInstance = \"sql01\" >> AllUserDatabases = $true >> MasterKeySecurePassword = $masterkeypass >> BackupSecurePassword = $certbackuppass >> BackupPath = \"C:\\temp\" >> EnableException = $true >> } PS C:\\> Start-DbaDbEncryption @params Prompts for two passwords (the username doesn't matter, this is just an easy & secure way to get a secure password) Then 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 Example 2: Encrypts all user databases on sql01 and sql02 using parallel processing for improved performance PS C:\\> $masterkeypass = (Get-Credential justneedpassword).Password PS C:\\> $certbackuppass = (Get-Credential justneedpassword).Password PS C:\\> $splatEncryption = @{ >> SqlInstance = \"sql01\", \"sql02\" >> AllUserDatabases = $true >> MasterKeySecurePassword = $masterkeypass >> BackupSecurePassword = $certbackuppass >> BackupPath = \"\\\\backup\\tde\" >> Parallel = $true >> } PS C:\\> Start-DbaDbEncryption @splatEncryption Encrypts all user databases on sql01 and sql02 using parallel processing for improved performance. Master keys and certificates are created sequentially per instance, then database encryption operations run in parallel. Required Parameters -BackupPath Directory path where master key and certificate backup files will be stored, accessible by the SQL Server service account. Critical for disaster recovery as these backups are required to restore TDE-encrypted databases. Ensure this path has appropriate security permissions and is included in your backup strategy. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -MasterKeySecurePassword Secure password used to create and protect the service master key in the master database if one doesn't exist. Required for all TDE operations because the function cannot determine if master key creation is needed until runtime. This password protects the root of the encryption hierarchy and is critical for disaster recovery. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -BackupSecurePassword Secure password used to encrypt backup files for master keys and certificates created during TDE setup. Essential for disaster recovery as these backups are required to restore encrypted databases on different servers. Must be stored securely as losing this password makes the encrypted data unrecoverable. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EncryptorName Specifies the name of the certificate or asymmetric key in the master database that will encrypt the database encryption keys. If 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. For asymmetric keys, the key must reside on an extensible key management provider to encrypt database encryption keys. | Property | Value | | --- | --- | | Alias | Certificate,CertificateName | | Required | False | | Pipeline | false | | Default Value | | -EncryptorType Determines whether to use a certificate or asymmetric key for TDE encryption. Defaults to Certificate. Certificate is the most common choice for standard TDE implementations. Use AsymmetricKey when integrating with extensible key management providers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Certificate | | Accepted Values | AsymmetricKey,Certificate | -Database Specifies which user databases to encrypt with Transparent Data Encryption (TDE). Use this when you need to encrypt specific databases instead of all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to exclude from TDE encryption. Useful when you want to encrypt most databases but need to skip specific ones due to compatibility or business requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CertificateSubject Sets the subject field for TDE certificates created during the encryption process. Use this to standardize certificate naming for compliance or organizational requirements. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CertificateStartDate Specifies when TDE certificates become valid. Defaults to the current date and time. Useful for planned encryption rollouts where certificates need to activate at a specific time. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-Date) | -CertificateExpirationDate Sets when TDE certificates will expire. Defaults to 5 years from the current date. Plan certificate renewals well before expiration to avoid service disruptions during database operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-Date).AddYears(5) | -CertificateActiveForServiceBrokerDialog Enables the TDE certificate for Service Broker dialog security in addition to database encryption. Use this when your databases utilize Service Broker and need certificate-based dialog security. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts database objects from Get-DbaDatabase for TDE encryption via pipeline. Allows filtering and processing specific databases before encryption, useful for complex selection criteria. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -AllUserDatabases Encrypts all user databases on the instance, excluding system databases (master, model, tempdb, msdb). Use this for compliance initiatives when you need to encrypt every user database quickly. System databases are automatically excluded as they cannot be encrypted with TDE. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Creates a new certificate with the specified EncryptorName if it doesn't exist in the master database. Requires EncryptorName to be specified. Use this when you need to establish new TDE infrastructure with specific naming conventions. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Parallel Enables parallel processing of databases using runspace pools with 1-10 concurrent threads. Use this when enabling encryption on multiple databases to improve performance. Shared resources (master keys and certificates) are created sequentially before parallel processing begins. Without this switch, databases are processed sequentially. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject When 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. Properties (when -Parallel is specified): ComputerName: The computer name of the SQL Server instance where encryption was applied InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: Name of the database that was encrypted EncryptionEnabled: Boolean indicating if encryption was successfully enabled on the database Status: String indicating operation result - either \"Success\" or \"Failed\" Error: Error message if Status is \"Failed\", otherwise null Note: Sequential processing (default, without -Parallel) does not output to the pipeline. Use -Parallel to receive result objects for each encrypted database. &nbsp;"
  },
  {
    "name": "Start-DbaEndpoint",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "endpoint"
    ],
    "verb": "Start",
    "popular": false,
    "url": "/Start-DbaEndpoint",
    "popularityRank": 597,
    "synopsis": "Starts stopped SQL Server endpoints for Database Mirroring, Service Broker, and other network services.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Start-DbaEndpoint View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Starts stopped SQL Server endpoints for Database Mirroring, Service Broker, and other network services. 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. Syntax Start-DbaEndpoint [[-SqlInstance] ] [[-SqlCredential] ] [[-Endpoint] ] [-AllEndpoints] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Starts all endpoints on the sqlserver2014 instance PS C:\\> Start-DbaEndpoint -SqlInstance sqlserver2012 -AllEndpoints Example 2: Logs into sqlserver2012 using alternative credentials and starts the endpoint1 and endpoint2 endpoints PS C:\\> Start-DbaEndpoint -SqlInstance sqlserver2012 -Endpoint endpoint1,endpoint2 -SqlCredential sqladmin Example 3: Starts the endpoints returned from the Get-Endpoint function PS C:\\> Get-Endpoint -SqlInstance sqlserver2012 -Endpoint endpoint1 | Start-DbaEndpoint Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Endpoint Specifies the names of specific endpoints to start on the target SQL Server instance. Use this when you only need to start particular endpoints like Database Mirroring or Service Broker endpoints rather than all endpoints on the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllEndpoints Starts all endpoints on the target SQL Server instance regardless of their current state or type. This is required when using the SqlInstance parameter and you want to start all endpoints rather than specific ones. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts endpoint objects from the pipeline, typically from Get-DbaEndpoint cmdlet output. Use this to start endpoints that have already been retrieved and filtered by other dbatools commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Endpoint Returns the Endpoint object(s) that were successfully started. Properties: Name: The endpoint name EndpointState: The state of the endpoint (Started, Stopped, Disabled) EndpointType: The type of endpoint (DatabaseMirroring, ServiceBroker, Tsql, SoapEndpoint, etc.) ProtocolType: The communication protocol used (TCP, NamedPipes, SharedMemory) Owner: The owner of the endpoint IsAdminEndpoint: Boolean indicating if this is an administrative endpoint IsSystemObject: Boolean indicating if this is a system-created endpoint ID: Unique identifier for the endpoint Parent: References the parent Server object &nbsp;"
  },
  {
    "name": "Start-DbaMigration",
    "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's 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.\nAll SSIS catalog folders, projects, and environments. Use -Exclude SsisCatalog 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's default data and log directories. You can override this by specifying -ReuseSourceFolderStructure. Filestreams and filegroups are also migrated. Safety is emphasized.",
    "category": "Utilities",
    "tags": [
      "migration"
    ],
    "verb": "Start",
    "popular": true,
    "url": "/Start-DbaMigration",
    "popularityRank": 6,
    "synopsis": "Migrates entire SQL Server instances including all databases, logins, server configuration, and server objects from source to destination servers.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Start-DbaMigration View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Migrates entire SQL Server instances including all databases, logins, server configuration, and server objects from source to destination servers. 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's less flexible than using individual migration functions but handles the complexity of orchestrating a full migration workflow. The function migrates: All user databases to exclude support databases such as ReportServerTempDB (Use -IncludeSupportDbs for this). Use -Exclude Databases to skip. All logins. Use -Exclude Logins to skip. All database mail objects. Use -Exclude DatabaseMail All credentials. Use -Exclude Credentials to skip. All objects within the Job Server (SQL Agent). Use -Exclude AgentServer to skip. All linked servers. Use -Exclude LinkedServers to skip. All groups and servers within Central Management Server. Use -Exclude CentralManagementServer to skip. All SQL Server configuration objects (everything in sp_configure). Use -Exclude SpConfigure to skip. All user objects in system databases. Use -Exclude SysDbUserObjects to skip. All system triggers. Use -Exclude SystemTriggers to skip. All system backup devices. Use -Exclude BackupDevices to skip. All Audits. Use -Exclude Audits to skip. All Endpoints. Use -Exclude Endpoints to skip. All Extended Events. Use -Exclude ExtendedEvents to skip. All Policy Management objects. Use -Exclude PolicyManagement to skip. All Resource Governor objects. Use -Exclude ResourceGovernor to skip. All Server Audit Specifications. Use -Exclude ServerAuditSpecifications to skip. All Custom Errors (User Defined Messages). Use -Exclude CustomErrors to skip. All Server Roles. Use -Exclude ServerRoles to skip. All Data Collector collection sets. Does not configure the server. Use -Exclude DataCollector to skip. All startup procedures. Use -Exclude StartupProcedures to skip. All custom Extended Stored Procedures. Use -Exclude ExtendedStoredProcedures to skip. All SSIS catalog folders, projects, and environments. Use -Exclude SsisCatalog to skip. This 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. By default, databases will be migrated to the destination SQL Server's default data and log directories. You can override this by specifying -ReuseSourceFolderStructure. Filestreams and filegroups are also migrated. Safety is emphasized. Syntax Start-DbaMigration [[-Source] ] [[-Destination] ] [[-Credential] ] [-DetachAttach] [-Reattach] [-BackupRestore] [[-SharedPath] ] [-WithReplace] [-NoRecovery] [-SetSourceReadOnly] [-SetSourceOffline] [-ReuseSourceFolderStructure] [-IncludeSupportDbs] [[-SourceSqlCredential] ] [[-DestinationSqlCredential] ] [[-Exclude] ] [-DisableJobsOnDestination] [-DisableJobsOnSource] [-ExcludeSaRename] [-UseLastBackup] [-KeepCDC] [-KeepReplication] [-Continue] [-ExcludePassword] [-Force] [[-AzureCredential] ] [[-MasterKeyPassword] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: All databases, logins, job objects and sp_configure options will be migrated from sqlserver\\instance to... PS C:\\> Start-DbaMigration -Source sqlserver\\instance -Destination sqlcluster -DetachAttach All 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 be updated. User passwords, SIDs, database roles and server roles will be migrated along with the login. Example 2: Utilizes splatting technique to set all the needed parameters PS C:\\> $params = @{ >> Source = \"sqlcluster\" >> Destination = \"sql2016\" >> SourceSqlCredential = $scred >> DestinationSqlCredential = $cred >> SharedPath = \"\\\\fileserver\\share\\sqlbackups\\Migration\" >> BackupRestore = $true >> ReuseSourceFolderStructure = $true >> Force = $true >> } >> PS C:\\> Start-DbaMigration @params -Verbose Utilizes 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, credentials, SQL Agent, Central Management Server, and SQL Server global configuration. Example 3: Migrates databases using detach/copy/attach PS C:\\> Start-DbaMigration -Verbose -Source sqlcluster -Destination sql2016 -DetachAttach -Reattach -SetSourceReadonly Migrates databases using detach/copy/attach. Reattach at source and set source databases read-only. Also migrates everything else. Example 4: Migrates databases using backup/restore method PS C:\\> Start-DbaMigration -Verbose -Source sqlcluster -Destination sql2016 -BackupRestore -SharedPath \"\\\\fileserver\\backups\" -SetSourceOffline Migrates databases using backup/restore method. Sets source databases offline before migration to prevent any connections during the process. Example 5: Utilizes the PSDefaultParameterValues system variable, and sets the Source and Destination parameters for any... PS C:\\> $PSDefaultParameters = @{ >> \"dbatools:Source\" = \"sqlcluster\" >> \"dbatools:Destination\" = \"sql2016\" >> } >> PS C:\\> Start-DbaMigration -Verbose -Exclude Databases, Logins Utilizes 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 passing them in constantly. The execution of the function will migrate everything but logins and databases. Optional Parameters -Source Specifies the source SQL Server instance to migrate from. Accepts server name, server\\instance, or connection string formats. This is the instance where all databases, logins, and server objects currently exist. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Destination Specifies one or more destination SQL Server instances to migrate to. Accepts server name, server\\instance, or connection string formats. When specifying multiple destinations, all objects will be migrated to each destination server. Multiple destinations require -Reattach when using -DetachAttach method. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential) Only used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DetachAttach Uses detach, copy, and attach method to migrate databases. Temporarily makes databases unavailable during the migration process. Files are copied using BITS over administrative shares and databases are reattached if destination attachment fails. This method is faster than backup/restore but requires downtime and breaks mirroring/replication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Reattach Reattaches all databases to the source server after a detach/attach migration completes. Use this when you want to keep the source databases online after migration, such as for testing or gradual cutover scenarios. Required when using -DetachAttach with multiple destination servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BackupRestore Uses backup and restore method to migrate databases instead of detach/attach. Creates copy-only backups to preserve existing backup chains. Requires either -SharedPath for new backups or -UseLastBackup to restore from existing backup files. This method is safer for production environments as it doesn't detach databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Both source and destination SQL Server service accounts require read/write permissions to this location. Only used with -BackupRestore method when not using -UseLastBackup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -WithReplace Forces restore operations to overwrite existing databases with the same name on the destination. Use this when you need to replace existing databases or when destination databases have different file paths than source. Only applies to backup/restore method. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoRecovery Restores databases in NORECOVERY mode, leaving them in a restoring state for additional log backups. Use this when you plan to apply differential or transaction log backups after the initial restore. Only applies to backup/restore method and prevents normal database access until recovered. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SetSourceReadOnly Sets migrated databases to read-only mode on the source server before migration begins. This prevents data changes during migration and helps ensure data consistency. When combined with -Reattach, databases remain read-only after being reattached to the source. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SetSourceOffline Sets migrated databases offline on the source server before migration begins. This prevents any connections to the source databases during migration, ensuring complete isolation. When combined with -Reattach, databases are brought back online after being reattached to the source. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ReuseSourceFolderStructure Preserves the original file paths from the source server when restoring databases on the destination. By default, databases are restored to the destination's default data and log directories. Use this when you need to maintain specific drive letters or folder structures on the destination server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IncludeSupportDbs Includes system support databases in the migration: ReportServer, ReportServerTempDB, SSISDB, and distribution databases. By default, these databases are excluded to prevent conflicts with existing services. Use this when migrating servers with SQL Server Reporting Services, Integration Services, or replication configured. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SourceSqlCredential Specifies credentials to connect to the source SQL Server instance. Use when the current Windows account lacks sufficient permissions. Accepts PowerShell credential objects created with Get-Credential for SQL Authentication or alternative Windows accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Specifies credentials to connect to the destination SQL Server instance(s). Use when the current Windows account lacks sufficient permissions. Accepts PowerShell credential objects created with Get-Credential for SQL Authentication or alternative Windows accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Exclude Specifies which migration components to skip during the migration process. Use this to exclude specific object types when you only need partial migrations or when certain objects should remain on the source. Valid values: Databases, Logins, AgentServer, Credentials, LinkedServers, SpConfigure, CentralManagementServer, DatabaseMail, SysDbUserObjects, SystemTriggers, BackupDevices, Audits, Endpoints, ExtendedEvents, PolicyManagement, ResourceGovernor, ServerAuditSpecifications, CustomErrors, ServerRoles, DataCollector, StartupProcedures, ExtendedStoredProcedures, AgentServerProperties, MasterCertificates, SsisCatalog. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Databases,Logins,AgentServer,Credentials,LinkedServers,SpConfigure,CentralManagementServer,DatabaseMail,SysDbUserObjects,SystemTriggers,BackupDevices,Audits,Endpoints,ExtendedEvents,PolicyManagement,ResourceGovernor,ServerAuditSpecifications,CustomErrors,ServerRoles,DataCollector,StartupProcedures,ExtendedStoredProcedures,AgentServerProperties,MasterCertificates,SsisCatalog | -DisableJobsOnDestination Disables all migrated SQL Agent jobs on the destination server after migration completes. Use this to prevent jobs from running automatically on the destination until you're ready to activate them. Helpful for staged migrations or when you need to update job schedules before activation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisableJobsOnSource Disables all SQL Agent jobs on the source server during the migration process. Use this to prevent jobs from running and potentially interfering with database migrations. Jobs remain disabled on the source after migration completes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludeSaRename Prevents renaming the sa account on the destination to match the source server's sa account name. By default, the destination sa account is renamed to match the source for consistency. Use this when you want to maintain the destination server's original sa account name. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UseLastBackup Uses existing backup files instead of creating new backups during database migration. The function will locate the most recent full, differential, and log backups for each database. Backup files must be accessible to all destination servers, typically on a network share. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepCDC Preserves Change Data Capture (CDC) configuration and data during database migration. By default, CDC information is not migrated to avoid potential conflicts with existing CDC configurations. Use this when you need to maintain CDC functionality on the destination server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepReplication Preserves replication configuration and metadata during database migration. By default, replication settings are not migrated to prevent conflicts with existing replication topologies. Use this when migrating databases that participate in replication and you want to maintain those settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Continue Attempts to apply additional transaction log backups to databases already in RESTORING or STANDBY states. Use this to bring destination databases up-to-date when they were previously restored with NORECOVERY. Only works with -UseLastBackup and requires databases to already exist in a restoring state. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -ExcludePassword Copies credentials, linked servers, and other objects without the actual password values. Use this in security-conscious environments where password decryption is restricted or when passwords should be manually reset after migration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Overwrites existing objects on the destination server without prompting for confirmation. For databases: drops existing databases with matching names before restoring. For logins: drops and recreates existing logins instead of skipping them. For DetachAttach method: breaks database mirroring and removes databases from Availability Groups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -AzureCredential Specifies the name of a SQL Server credential for accessing Azure Storage when SharedPath points to an Azure Storage account. The credential must already exist on both source and destination servers with proper access to the Azure Storage container. Only needed when using Azure Storage URLs for the SharedPath parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MasterKeyPassword Specifies the password for creating or opening database master keys during certificate migration. Required when migrating databases with encrypted objects or certificates that need master key protection. Must be provided as a SecureString object for security. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Object When 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 migration method selected: When using -BackupRestore method: Returns database migration status objects showing which databases were successfully restored on destination servers. When using -DetachAttach method: Returns database reattachment status objects showing which databases were successfully attached on destination servers. When -Exclude Databases is specified, most server-level migration operations do not return pipeline output. The exception is SSIS catalog migration, which returns MigrationObject status objects from Copy-DbaSsisCatalog when the source instance has an SSISDB catalog. All 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 migration steps. &nbsp;"
  },
  {
    "name": "Start-DbaPfDataCollectorSet",
    "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.",
    "category": "Utilities",
    "tags": [
      "perfmon"
    ],
    "verb": "Start",
    "popular": false,
    "url": "/Start-DbaPfDataCollectorSet",
    "popularityRank": 603,
    "synopsis": "Starts Windows Performance Monitor Data Collector Sets on local or remote computers.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Start-DbaPfDataCollectorSet View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Starts Windows Performance Monitor Data Collector Sets on local or remote computers. 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. Syntax Start-DbaPfDataCollectorSet [[-ComputerName] ] [[-Credential] ] [[-CollectorSet] ] [[-InputObject] ] [-NoWait] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Attempts to start all ready Collectors on localhost PS C:\\> Start-DbaPfDataCollectorSet Example 2: Attempts to start all ready Collectors on localhost PS C:\\> Start-DbaPfDataCollectorSet -ComputerName sql2017 Example 3: Starts the &#39;System Correlation&#39; Collector on sql2017 and sql2016 using alternative credentials PS C:\\> Start-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet 'System Correlation' Example 4: Starts the &#39;System Correlation&#39; Collector PS C:\\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Start-DbaPfDataCollectorSet Optional Parameters -ComputerName Specifies the target computer(s) where Performance Monitor Data Collector Sets will be started. Defaults to localhost. Use this when you need to start collector sets on remote SQL Server machines or when managing multiple servers from a central location. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to $ComputerName using alternative credentials. To use: $cred = Get-Credential, then pass $cred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CollectorSet Specifies the name(s) of specific Performance Monitor Data Collector Sets to start. When omitted, all ready collector sets will be started. Use this when you only need to start particular collector sets like 'System Performance' or custom sets created for SQL Server monitoring. | Property | Value | | --- | --- | | Alias | DataCollectorSet | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Performance Monitor Data Collector Set objects from Get-DbaPfDataCollectorSet via the pipeline. Objects must contain DataCollectorSetObject property. Use this when you want to filter collector sets with Get-DbaPfDataCollectorSet first, then start only the matching sets through the pipeline. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -NoWait When specified, starts the collector set and returns results immediately without waiting for the startup process to complete. Use this when starting multiple collector sets in scripts where you don't need to confirm each one fully initialized before proceeding. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one Performance Monitor Data Collector Set object for each collector set that was successfully started. Properties: ComputerName: The name of the computer where the Data Collector Set is located State: The current state of the Data Collector Set (Running, Stopped, etc.) Name: The name of the Data Collector Set DataCollectorSetObject: The underlying Windows Performance Monitor Data Collector Set COM object Returns 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. &nbsp;"
  },
  {
    "name": "Start-DbaService",
    "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't 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).",
    "category": "Server Management",
    "tags": [
      "service",
      "sqlserver",
      "instance",
      "connect"
    ],
    "verb": "Start",
    "popular": false,
    "url": "/Start-DbaService",
    "popularityRank": 205,
    "synopsis": "Starts SQL Server related services across multiple computers while respecting service dependencies.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Start-DbaService View Source Kirill Kravtsov (@nvarscar) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Starts SQL Server related services across multiple computers while respecting service dependencies. 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't have to manually determine which services depend on others. Commonly used after maintenance windows, server reboots, or when troubleshooting stopped services across an environment. Requires Local Admin rights on destination computer(s). Syntax Start-DbaService [[-ComputerName] ] [-InstanceName ] [-SqlInstance ] [-Type ] [-Timeout ] [-Credential ] [-EnableException] [-WhatIf] [-Confirm] [ ] Start-DbaService [-InstanceName ] [-Type ] -InputObject [-Timeout ] [-Credential ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Starts the SQL Server related services on computer sqlserver2014a PS C:\\> Start-DbaService -ComputerName sqlserver2014a Example 2: Gets the SQL Server related services on computers sql1, sql2 and sql3 and starts them PS C:\\> 'sql1','sql2','sql3'| Get-DbaService | Start-DbaService Example 3: Starts the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2 PS C:\\> Start-DbaService -ComputerName sql1,sql2 -Instance MSSQLSERVER Example 4: Starts the SQL Server related services of type &quot;SSRS&quot; (Reporting Services) on computers in the variable... PS C:\\> Start-DbaService -ComputerName $MyServers -Type SSRS Starts the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers. Required Parameters -InputObject Accepts service objects from Get-DbaService through the pipeline for targeted service operations. Use this when you need fine-grained control over which specific services to start, such as when Get-DbaService has filtered to stopped services only. | Property | Value | | --- | --- | | Alias | ServiceCollection | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -ComputerName Specifies the computer names where SQL Server services should be started. Accepts multiple computer names for bulk operations. Use this when you need to start services across multiple servers simultaneously, such as after a maintenance window or environment-wide restart. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -InstanceName Filters services to only those belonging to specific named instances. Does not affect default instance (MSSQLSERVER) services. Use this when you have multiple instances on the same server and only want to start services for specific named instances like SQL2019 or REPORTING. | Property | Value | | --- | --- | | Alias | Instance | | Required | False | | Pipeline | false | | Default Value | | -SqlInstance Use a combination of computername and instancename to get the SQL Server related services for specific instances on specific computers. Parameters ComputerName and InstanceName will be ignored if SqlInstance is used. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Filters to specific SQL Server service types rather than starting all services. Valid types: Agent, Browser, Engine, FullText, SSAS, SSIS, SSRS, PolyBase, Launchpad. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Agent,Browser,Engine,FullText,SSAS,SSIS,SSRS,PolyBase,Launchpad | -Timeout Sets the maximum time in seconds to wait for each service to start before moving to the next service. Defaults to 60 seconds. Increase this value for slow-starting services or when starting services on heavily loaded servers. Set to 0 to wait indefinitely. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 60 | -Credential Credential object used to connect to the computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs System.ServiceProcess.ServiceController Returns one ServiceController object per service that was successfully started. Each object represents a SQL Server related service on the target computer(s). Default display properties (from ServiceController): Name: The service name (e.g., MSSQLSERVER, SQLSERVERAGENT, MSSQLServerOlapService) DisplayName: The friendly display name of the service Status: The current status of the service (Running, Stopped, StartPending, StopPending, etc.) StartType: How the service starts (Boot, System, Automatic, Manual, Disabled) Additional properties available from ServiceController: ServiceName: The name of the service ServiceType: The type of service CanPauseAndContinue: Boolean indicating if the service can be paused and resumed CanShutdown: Boolean indicating if the service should be notified of system shutdown CanStop: Boolean indicating if the service can be stopped ServiceHandle: The service's Windows handle DependentServices: Collection of services that depend on this service ServicesDependedOn: Collection of services that this service depends on RequiredServices: Collection of services required for this service to run Returns nothing if no services are found matching the specified parameters, or if the -WhatIf parameter is used. &nbsp;"
  },
  {
    "name": "Start-DbaTrace",
    "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.",
    "category": "Performance",
    "tags": [
      "trace"
    ],
    "verb": "Start",
    "popular": false,
    "url": "/Start-DbaTrace",
    "popularityRank": 360,
    "synopsis": "Starts existing SQL Server traces that are currently stopped",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Start-DbaTrace View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Starts existing SQL Server traces that are currently stopped 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. Syntax Start-DbaTrace [[-SqlInstance] ] [[-SqlCredential] ] [[-Id] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Starts all traces on sql2008 PS C:\\> Start-DbaTrace -SqlInstance sql2008 Example 2: Starts all trace with ID 1 on sql2008 PS C:\\> Start-DbaTrace -SqlInstance sql2008 -Id 1 Example 3: Starts selected traces on sql2008 PS C:\\> Get-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Start-DbaTrace Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Id Specifies the numeric IDs of specific traces to start. When omitted, all stopped traces on the instance will be started. Use this when you need to start only particular traces rather than all available stopped traces. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts trace objects from the pipeline, typically from Get-DbaTrace. This allows you to filter traces first, then start only the selected ones. Use this parameter when piping trace objects or when you have trace objects from a previous Get-DbaTrace command. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object for each trace that was started or would be started (if -WhatIf is specified). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Id: The trace ID number Status: Numeric trace status value (0=stopped, 1=running, 2=closed) IsRunning: Boolean indicating if the trace is currently running Path: The file path where the trace output is stored MaxSize: Maximum size of the trace file in megabytes (0=unlimited) StopTime: DateTime when the trace is scheduled to stop, or null if running indefinitely MaxFiles: Maximum number of rollover files (0=unlimited) IsRowset: Boolean indicating if trace output is written as rowset IsRollover: Boolean indicating if rollover file creation is enabled IsShutdown: Boolean indicating if trace will stop on server shutdown IsDefault: Boolean indicating if this is the default system trace BufferCount: Number of in-memory buffers allocated for the trace BufferSize: Size of each buffer in kilobytes FilePosition: Current file position for trace output ReaderSpid: Server process ID reading the trace (SPID) StartTime: DateTime when the trace was started LastEventTime: DateTime of the most recent trace event EventCount: Number of events captured by the trace DroppedEventCount: Number of events dropped due to buffer limitations Additional properties available but excluded from default view: RemotePath: UNC path to the trace file for remote access (null if Path is empty) Parent: Reference to the Microsoft.SqlServer.Management.Smo.Server object SqlCredential: The credentials used to connect to the instance Use Select-Object * to access all properties. &nbsp;"
  },
  {
    "name": "Start-DbaXESession",
    "description": "Activates Extended Events sessions that have been created but are not currently running. Extended Events sessions are SQL Server's 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't accidentally interfere with SQL Server's 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.",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Start",
    "popular": false,
    "url": "/Start-DbaXESession",
    "popularityRank": 547,
    "synopsis": "Starts Extended Events sessions on SQL Server instances for monitoring and troubleshooting.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Start-DbaXESession View Source Doug Meyers Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Starts Extended Events sessions on SQL Server instances for monitoring and troubleshooting. Description Activates Extended Events sessions that have been created but are not currently running. Extended Events sessions are SQL Server's lightweight monitoring framework used for troubleshooting performance issues, security auditing, and capturing specific database activity patterns. The 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't accidentally interfere with SQL Server's internal monitoring. For 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. Syntax Start-DbaXESession [-SqlInstance] [-SqlCredential ] -Session [-StartAt ] [-StopAt ] [-EnableException] [-WhatIf] [-Confirm] [ ] Start-DbaXESession [-SqlInstance] [-SqlCredential ] [-StartAt ] [-StopAt ] -AllSessions [-EnableException] [-WhatIf] [-Confirm] [ ] Start-DbaXESession [-StartAt ] [-StopAt ] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Starts all Extended Event Session on the sqlserver2014 instance PS C:\\> Start-DbaXESession -SqlInstance sqlserver2012 -AllSessions Example 2: Starts the xesession1 and xesession2 Extended Event sessions PS C:\\> Start-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2 Example 3: Starts the xesession1 and xesession2 Extended Event sessions and stops them in 30 minutes PS C:\\> Start-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2 -StopAt (Get-Date).AddMinutes(30) Example 4: Starts the AlwaysOn_health Extended Event sessions in 1 minute PS C:\\> Start-DbaXESession -SqlInstance sqlserver2012 -Session AlwaysOn_health -StartAt (Get-Date).AddMinutes(1) Starts the AlwaysOn_health Extended Event sessions in 1 minute. The command will return immediately. Example 5: Starts the sessions returned from the Get-DbaXESession function PS C:\\> Get-DbaXESession -SqlInstance sqlserver2012 -Session xesession1 | Start-DbaXESession Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Session Specifies the names of specific Extended Events sessions to start. Accepts multiple session names as an array. Use this when you need to start only certain sessions rather than all user-created sessions on the instance. | Property | Value | | --- | --- | | Alias | Sessions | | Required | True | | Pipeline | false | | Default Value | | -AllSessions Starts all user-created Extended Events sessions on the instance while excluding system sessions (AlwaysOn_health, system_health, telemetry_xevents). Use this when you want to activate all custom monitoring sessions without interfering with SQL Server's built-in diagnostics. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | False | -InputObject Accepts Extended Events session objects from Get-DbaXESession for pipeline operations. Use this when you need to filter sessions with Get-DbaXESession first, then start only the matching sessions. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StartAt Schedules the Extended Events sessions to start at a specific date and time using a temporary SQL Agent job. The command returns immediately while the job handles starting sessions at the scheduled time, useful for capturing activity during specific time windows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -StopAt Schedules the Extended Events sessions to stop at a specific date and time using a temporary SQL Agent job. Use this with StartAt or on already running sessions to create time-bounded monitoring windows for troubleshooting specific issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.XEvent.Session Returns one Session object for each Extended Events session that was started or would be started (if -WhatIf is specified). Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the Extended Events session Status: Current session status - either \"Running\" or \"Stopped\" StartTime: DateTime when the session was started (null if stopped) AutoStart: Boolean indicating if the session starts automatically when SQL Server starts State: SMO object state (Existing, Creating, Pending, etc.) Targets: Collection of target objects configured for this session TargetFile: Array of resolved file paths for all event_file targets (includes UNC paths for network access) Events: Collection of Extended Events configured in this session MaxMemory: Maximum memory allocation for the session in KB MaxEventSize: Maximum event size the session will capture in KB Additional properties added as NoteProperties: Session: The session name (alias for Name property) RemoteTargetFile: Array of UNC paths for all target files (for remote file access) Parent: Reference to the parent Microsoft.SqlServer.Management.Smo.Server object Store: Reference to the Microsoft.SqlServer.Management.XEvent.XEStore object When -StartAt is specified, jobs are created but the session objects are returned immediately without waiting for scheduled execution. &nbsp;"
  },
  {
    "name": "Stop-DbaAgentJob",
    "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.",
    "category": "Agent & Jobs",
    "tags": [
      "job",
      "agent"
    ],
    "verb": "Stop",
    "popular": false,
    "url": "/Stop-DbaAgentJob",
    "popularityRank": 358,
    "synopsis": "Stops running SQL Server Agent jobs by calling their Stop() method.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Stop-DbaAgentJob View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Stops running SQL Server Agent jobs by calling their Stop() method. Description Stops currently executing SQL Server Agent jobs and returns the job objects for verification after the stop attempt. Perfect for halting runaway jobs during maintenance windows, stopping jobs that are causing blocking or performance issues, or clearing job queues before scheduled operations. The function automatically skips jobs that are already idle and can optionally wait until jobs have completely finished stopping before returning results. Works with individual job names, exclusion filters, or accepts piped job objects from Get-DbaAgentJob and other dbatools commands. Syntax Stop-DbaAgentJob [-SqlCredential ] [-Job ] [-ExcludeJob ] [-Wait] [-EnableException] [-WhatIf] [-Confirm] [ ] Stop-DbaAgentJob -SqlInstance [-SqlCredential ] [-Job ] [-ExcludeJob ] [-Wait] [-EnableException] [-WhatIf] [-Confirm] [ ] Stop-DbaAgentJob [-SqlCredential ] [-Job ] [-ExcludeJob ] -InputObject [-Wait] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Stops all running SQL Agent Jobs on the local SQL Server instance PS C:\\> Stop-DbaAgentJob -SqlInstance localhost Example 2: Stops the cdc.DBWithCDC_capture SQL Agent Job on sql2016 PS C:\\> Get-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture | Stop-DbaAgentJob Example 3: Stops the cdc.DBWithCDC_capture SQL Agent Job on sql2016 PS C:\\> Stop-DbaAgentJob -SqlInstance sql2016 -Job cdc.DBWithCDC_capture Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts SQL Agent job objects from pipeline operations, typically from Get-DbaAgentJob or other dbatools commands. This allows you to filter jobs using complex criteria upstream and then pipe the results directly to Stop-DbaAgentJob for processing. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies which SQL Agent jobs to stop by name. Accepts exact job names from the target instance. Use this when you need to stop specific jobs instead of all running jobs. If unspecified, all currently running jobs will be processed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJob Specifies SQL Agent job names to exclude from the stop operation. Accepts exact job names from the target instance. Use this when you want to stop most jobs but preserve critical ones like backup jobs, monitoring jobs, or maintenance routines during troubleshooting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Wait Waits for each job to completely finish stopping before returning results. Without this switch, the function returns immediately after sending the stop command. Use this when you need to ensure jobs have fully terminated before proceeding with subsequent operations like maintenance or troubleshooting steps. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Agent.Job Returns 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). Default display properties (via SMO Agent.Job): Name: The name of the SQL Server Agent job Enabled: Boolean indicating if the job is enabled CurrentRunStatus: The current execution status of the job (Idle, Executing, etc.) LastRunOutcome: The outcome of the last job execution (Succeeded, Failed, Retry, Canceled, etc.) LastRunDate: DateTime of the most recent job execution NextRunDate: DateTime of the next scheduled job execution OwnerLoginName: The login name of the job owner All SMO Job object properties are accessible using Select-Object *. See Microsoft SQL Server Management Objects (SMO) documentation for the complete property list. Note: 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 CurrentRunStatus may still show Executing. &nbsp;"
  },
  {
    "name": "Stop-DbaDbEncryption",
    "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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Stop",
    "popular": false,
    "url": "/Stop-DbaDbEncryption",
    "popularityRank": 593,
    "synopsis": "Disables Transparent Data Encryption (TDE) on all user databases across a SQL Server instance",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Stop-DbaDbEncryption View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Disables Transparent Data Encryption (TDE) on all user databases across a SQL Server instance 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. This 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. Each 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. Syntax Stop-DbaDbEncryption [-SqlInstance] [[-SqlCredential] ] [-Parallel] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Removes this does that PS C:\\> Stop-DbaDbEncryption -SqlInstance sql01 Example 2: Disables TDE on all user databases on sql01 without prompting for confirmation PS C:\\> Stop-DbaDbEncryption -SqlInstance sql01 -Confirm:$false Example 3: Disables TDE on all user databases across multiple instances using parallel processing for improved... PS C:\\> Stop-DbaDbEncryption -SqlInstance sql01, sql02 -Parallel -Confirm:$false Disables TDE on all user databases across multiple instances using parallel processing for improved performance Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Parallel Enables parallel processing of databases using runspace pools with 1-10 concurrent threads. Use this when disabling encryption on multiple databases to improve performance. Without this switch, databases are processed sequentially. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database processed, with output varying based on encryption status and processing mode. Default properties (sequential mode without -Parallel): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) DatabaseName: The name of the database EncryptionEnabled: Boolean indicating whether encryption is enabled after the operation When -Parallel is specified, additional properties are included: Status: The operation result (Success, NotEncrypted, or Failed) Error: Error message if the operation failed; null on success &nbsp;"
  },
  {
    "name": "Stop-DbaEndpoint",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "endpoint"
    ],
    "verb": "Stop",
    "popular": false,
    "url": "/Stop-DbaEndpoint",
    "popularityRank": 668,
    "synopsis": "Stops SQL Server communication endpoints like Service Broker, Database Mirroring, or custom TCP endpoints.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Stop-DbaEndpoint View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Stops SQL Server communication endpoints like Service Broker, Database Mirroring, or custom TCP endpoints. 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. Syntax Stop-DbaEndpoint [[-SqlInstance] ] [[-SqlCredential] ] [[-Endpoint] ] [-AllEndpoints] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Stops all endpoints on the sqlserver2014 instance PS C:\\> Stop-DbaEndpoint -SqlInstance sql2017a -AllEndpoints Example 2: Stops the endpoint1 and endpoint2 endpoints PS C:\\> Stop-DbaEndpoint -SqlInstance sql2017a -Endpoint endpoint1,endpoint2 Example 3: Stops the endpoints returned from the Get-Endpoint command PS C:\\> Get-Endpoint -SqlInstance sql2017a -Endpoint endpoint1 | Stop-DbaEndpoint Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Endpoint Specifies the names of specific endpoints to stop. Accepts multiple endpoint names as an array. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AllEndpoints Stops all endpoints on the specified SQL Server instance. Required when using SqlInstance parameter if Endpoint is not specified. Use this during full maintenance windows or when you need to completely disable all endpoint communication for troubleshooting network connectivity issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts endpoint objects from Get-DbaEndpoint for pipeline operations. Allows filtering and processing endpoints before stopping them. Use this for complex scenarios where you need to filter endpoints based on their properties before stopping them. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Endpoint Returns the endpoint object(s) after they have been successfully stopped. One object is returned per endpoint that was stopped. Properties include: Name: The name of the endpoint EndpointType: Type of endpoint (ServiceBroker, DatabaseMirroring, TSQL_DEFAULT_TCP, TSQL_DEFAULT_HTTP, or custom application) ProtocolType: The protocol used by the endpoint State: Current state of the endpoint (Stopped, Started, or Disabled) Parent: Reference to the parent server or database object Protocol: Detailed protocol configuration object Payload: Endpoint payload and payload type configuration All properties from the base SMO Endpoint object are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Stop-DbaExternalProcess",
    "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's waiting for it.\n\nhttps://web.archive.org/web/20201027122300/http://vickyharp.com/2013/12/killing-sessions-with-external-wait-types/",
    "category": "Utilities",
    "tags": [
      "diagnostic",
      "process"
    ],
    "verb": "Stop",
    "popular": false,
    "url": "/Stop-DbaExternalProcess",
    "popularityRank": 655,
    "synopsis": "Terminates operating system processes spawned by SQL Server instances",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Stop-DbaExternalProcess View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Terminates operating system processes spawned by SQL Server instances 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. The 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. This 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's waiting for it. https://web.archive.org/web/20201027122300/http://vickyharp.com/2013/12/killing-sessions-with-external-wait-types/ Syntax Stop-DbaExternalProcess [-ComputerName] [[-Credential] ] [[-ProcessId] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Kills all OS processes created by SQL Server on SQL01 PS C:\\> Get-DbaExternalProcess -ComputerName SQL01 | Stop-DbaExternalProcess Example 2: Kills all cmd.exe processes created by SQL Server on SQL01 PS C:\\> Get-DbaExternalProcess -ComputerName SQL01 | Where-Object Name -eq \"cmd.exe\" | Stop-DbaExternalProcess Required Parameters -ComputerName Specifies the Windows server hosting the SQL Server instance where external processes need to be terminated. Use this when troubleshooting hung sessions with external wait types on remote SQL Server hosts. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -Credential Allows you to login to $ComputerName using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -ProcessId Specifies the Windows process ID of the external process spawned by SQL Server that needs to be terminated. Typically obtained from Get-DbaExternalProcess output when identifying processes causing EXTERNAL_SCRIPT_NETWORK_IO or WAITFOR_RESULTS wait types. | Property | Value | | --- | --- | | Alias | pid | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per successfully stopped external process with the following properties: ComputerName: The name of the computer where the process was terminated ProcessId: The Windows process ID that was stopped (integer) Name: The process name/executable name of the terminated process Status: The status of the operation; always \"Stopped\" when successful &nbsp;"
  },
  {
    "name": "Stop-DbaPfDataCollectorSet",
    "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't needed.",
    "category": "Utilities",
    "tags": [
      "perfmon"
    ],
    "verb": "Stop",
    "popular": false,
    "url": "/Stop-DbaPfDataCollectorSet",
    "popularityRank": 694,
    "synopsis": "Stops Windows Performance Monitor Data Collector Sets used for SQL Server performance monitoring.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Stop-DbaPfDataCollectorSet View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Stops Windows Performance Monitor Data Collector Sets used for SQL Server performance monitoring. 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't needed. Syntax Stop-DbaPfDataCollectorSet [[-ComputerName] ] [[-Credential] ] [[-CollectorSet] ] [[-InputObject] ] [-NoWait] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Attempts to stop all ready Collectors on localhost PS C:\\> Stop-DbaPfDataCollectorSet Example 2: Attempts to stop all ready Collectors on localhost PS C:\\> Stop-DbaPfDataCollectorSet -ComputerName sql2017 Example 3: Stops the &#39;System Correlation&#39; Collector on sql2017 and sql2016 using alternative credentials PS C:\\> Stop-DbaPfDataCollectorSet -ComputerName sql2017, sql2016 -Credential ad\\sqldba -CollectorSet 'System Correlation' Example 4: Stops the &#39;System Correlation&#39; Collector PS C:\\> Get-DbaPfDataCollectorSet -CollectorSet 'System Correlation' | Stop-DbaPfDataCollectorSet Optional Parameters -ComputerName Specifies the target computer where Performance Monitor Data Collector Sets are running. Accepts multiple computer names for bulk operations. Use this when stopping collectors on remote SQL Server instances or when managing multiple servers from a central location. Defaults to localhost when not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to $ComputerName using alternative credentials. To use: $cred = Get-Credential, then pass $cred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -CollectorSet Specifies the exact name of the Data Collector Set to stop. Supports multiple collector names for stopping several sets simultaneously. Use this when you need to stop specific performance monitoring sets without affecting other running collectors on the system. Common SQL Server collector sets include 'SQL Server Data Collector Set' and custom monitoring configurations. | Property | Value | | --- | --- | | Alias | DataCollectorSet | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts Data Collector Set objects from Get-DbaPfDataCollectorSet via pipeline input. Use this approach when you need to filter or examine collector properties before stopping them, or when building complex monitoring workflows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -NoWait Returns control immediately after initiating the stop command without waiting for the collector to fully terminate. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Objects from Get-DbaPfDataCollectorSet Returns 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 information showing it is no longer running. Properties returned match those from Get-DbaPfDataCollectorSet, including: ComputerName: The computer where the Data Collector Set is configured Name: The name of the Data Collector Set that was stopped State: The current state (should be \"Stopped\" after successful termination) Enabled: Boolean indicating if the collector set is enabled DataCollectorSetObject: Reference to the underlying Windows COM object Note: 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. &nbsp;"
  },
  {
    "name": "Stop-DbaProcess",
    "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.",
    "category": "Utilities",
    "tags": [
      "diagnostic",
      "process"
    ],
    "verb": "Stop",
    "popular": false,
    "url": "/Stop-DbaProcess",
    "popularityRank": 248,
    "synopsis": "Terminates SQL Server processes (SPIDs) to resolve blocking, kill runaway queries, or clean up connections.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Stop-DbaProcess View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Terminates SQL Server processes (SPIDs) to resolve blocking, kill runaway queries, or clean up connections. 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. The 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. Syntax Stop-DbaProcess [-SqlCredential ] [-Spid ] [-ExcludeSpid ] [-Database ] [-Login ] [-Hostname ] [-Program ] [-EnableException] [-WhatIf] [-Confirm] [ ] Stop-DbaProcess -SqlInstance [-SqlCredential ] [-Spid ] [-ExcludeSpid ] [-Database ] [-Login ] [-Hostname ] [-Program ] [-EnableException] [-WhatIf] [-Confirm] [ ] Stop-DbaProcess [-SqlCredential ] [-Spid ] [-ExcludeSpid ] [-Database ] [-Login ] [-Hostname ] [-Program ] -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Finds all processes for base\\ctrlb and sa on sqlserver2014a, then kills them PS C:\\> Stop-DbaProcess -SqlInstance sqlserver2014a -Login base\\ctrlb, sa Finds all processes for base\\ctrlb and sa on sqlserver2014a, then kills them. Uses Windows Authentication to login to sqlserver2014a. Example 2: Finds processes for spid 56 and 57, then kills them PS C:\\> Stop-DbaProcess -SqlInstance sqlserver2014a -SqlCredential $credential -Spid 56, 77 Finds processes for spid 56 and 57, then kills them. Uses alternative (SQL or Windows) credentials to login to sqlserver2014a. Example 3: Finds processes that were created in Microsoft SQL Server Management Studio, then kills them PS C:\\> Stop-DbaProcess -SqlInstance sqlserver2014a -Program 'Microsoft SQL Server Management Studio' Example 4: Finds processes that were initiated (computers/clients) workstationx and server 1000, then kills them PS C:\\> Stop-DbaProcess -SqlInstance sqlserver2014a -Hostname workstationx, server100 Example 5: Shows what would happen if the command were executed PS C:\\> Stop-DbaProcess -SqlInstance sqlserver2014 -Database tempdb -WhatIf Example 6: Finds processes that were created with dbatools, then kills them PS C:\\> Get-DbaProcess -SqlInstance sql2016 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -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 verification of which processes will be killed. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 multiple SPIDs to kill several problem sessions at once. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 processes by login, hostname, or database. This exclusion is applied last, overriding all other matching filters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. This will disconnect all users currently connected to the targeted databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 issues. Supports multiple logins and accepts both Windows (DOMAIN\\user) and SQL logins. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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 all sessions from a specific machine. Accepts multiple hostnames including both short names and FQDNs. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Common program names include 'Microsoft SQL Server Management Studio' and various .NET application names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per successfully killed process, confirming the termination action with session details. Properties: SqlInstance: The name of the SQL Server instance where the process was terminated Spid: The session ID (SPID) of the killed process Login: The login name associated with the killed process Host: The hostname or computer name where the client process originated Database: The name of the database the killed session was connected to Program: The application or program name that initiated the killed session Status: Always set to \"Killed\" to confirm successful process termination Note: Processes matching filter criteria but matching ExcludeSpid, or the current session, or processes that fail to kill will not generate output objects. &nbsp;"
  },
  {
    "name": "Stop-DbaService",
    "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).",
    "category": "Server Management",
    "tags": [
      "service",
      "stop"
    ],
    "verb": "Stop",
    "popular": false,
    "url": "/Stop-DbaService",
    "popularityRank": 236,
    "synopsis": "Stops SQL Server-related Windows services with proper dependency handling.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Stop-DbaService View Source Kirill Kravtsov (@nvarscar) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Stops SQL Server-related Windows services with proper dependency handling. 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. Particularly 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. Supports 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. Requires Local Admin rights on destination computer(s). Syntax Stop-DbaService [[-ComputerName] ] [-InstanceName ] [-SqlInstance ] [-Type ] [-Timeout ] [-Credential ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] Stop-DbaService [-InstanceName ] [-Type ] -InputObject [-Timeout ] [-Credential ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Stops the SQL Server related services on computer sqlserver2014a PS C:\\> Stop-DbaService -ComputerName sqlserver2014a Example 2: Gets the SQL Server related services on computers sql1, sql2 and sql3 and stops them PS C:\\> 'sql1','sql2','sql3'| Get-DbaService | Stop-DbaService Example 3: Stops the SQL Server services related to the default instance MSSQLSERVER on computers sql1 and sql2 PS C:\\> Stop-DbaService -ComputerName sql1,sql2 -Instance MSSQLSERVER Example 4: Stops the SQL Server related services of type &quot;SSRS&quot; (Reporting Services) on computers in the variable... PS C:\\> Stop-DbaService -ComputerName $MyServers -Type SSRS Stops the SQL Server related services of type \"SSRS\" (Reporting Services) on computers in the variable MyServers. Example 5: Stops SQL Server database engine services on sql1 forcing dependent SQL Server Agent services to stop as well PS C:\\> Stop-DbaService -ComputerName sql1 -Type Engine -Force Required Parameters -InputObject Accepts service objects directly from Get-DbaService, allowing for advanced filtering and pipeline operations. Use this approach when you need complex service filtering that goes beyond the built-in ComputerName, InstanceName, and Type parameters. | Property | Value | | --- | --- | | Alias | ServiceCollection | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -ComputerName Specifies the target computer(s) containing SQL Server services to stop. Accepts multiple computer names for bulk service management. Use this when you need to stop SQL Server services across multiple servers during maintenance windows or troubleshooting scenarios. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -InstanceName Targets services belonging to specific SQL Server named instances. Filters results to match only the specified instance names. Essential in multi-instance environments where you need to stop services for particular instances while leaving others running. | Property | Value | | --- | --- | | Alias | Instance | | Required | False | | Pipeline | false | | Default Value | | -SqlInstance Use a combination of computername and instancename to get the SQL Server related services for specific instances on specific computers. Parameters ComputerName and InstanceName will be ignored if SqlInstance is used. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Filters which SQL Server service types to stop. Valid options: Agent, Browser, Engine, FullText, SSAS, SSIS, SSRS, PolyBase, Launchpad. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Agent,Browser,Engine,FullText,SSAS,SSIS,SSRS,PolyBase,Launchpad | -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. Increase this value for services that take longer to shut down gracefully, particularly in environments with large databases or heavy workloads. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 60 | -Credential Credential object used to connect to the computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Automatically stops dependent services when stopping SQL Server Database Engine services. Prevents dependency conflicts that would otherwise block the stop operation. Required when stopping Engine services that have dependent SQL Agent services running, as SQL Agent must be stopped first to avoid service dependency errors. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Wmi.Service Returns one service object per service that was stopped, with the following default display properties: ComputerName: The name of the computer hosting the SQL Server service ServiceName: The Windows service name (e.g., MSSQLSERVER, SQLSERVERAGENT, SSRS) InstanceName: The SQL Server instance name associated with the service ServiceType: The type of SQL Server service (Engine, Agent, SSRS, SSAS, SSIS, PolyBase, Launchpad, Browser, FullText) State: The current state of the service (Running, Stopped, etc.) Status: The result of the stop operation (Successful, Failed) Message: Detailed status message describing the operation result (success or failure reason) *Additional properties available via Select-Object :** ServiceAccount: The Windows account running the service StartMode: The startup type (Automatic, Manual, Disabled) Properties: Collection of additional service properties Parent: Reference to the parent computer object When -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 output with their own status information. If no services match the specified parameters, no output is generated. &nbsp;"
  },
  {
    "name": "Stop-DbaTrace",
    "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.",
    "category": "Performance",
    "tags": [
      "trace"
    ],
    "verb": "Stop",
    "popular": false,
    "url": "/Stop-DbaTrace",
    "popularityRank": 672,
    "synopsis": "Stops running SQL Server traces using sp_trace_setstatus",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Stop-DbaTrace View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Stops running SQL Server traces using sp_trace_setstatus 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. Syntax Stop-DbaTrace [[-SqlInstance] ] [[-SqlCredential] ] [[-Id] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Stops all traces on sql2008 PS C:\\> Stop-DbaTrace -SqlInstance sql2008 Example 2: Stops all trace with ID 1 on sql2008 PS C:\\> Stop-DbaTrace -SqlInstance sql2008 -Id 1 Example 3: Stops selected traces on sql2008 PS C:\\> Get-DbaTrace -SqlInstance sql2008 | Out-GridView -PassThru | Stop-DbaTrace Optional Parameters -SqlInstance The target SQL Server instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Id Specifies the trace IDs to stop. Accepts one or more trace ID numbers as integers. Use this when you need to stop specific traces instead of all running traces on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts trace objects from the pipeline, typically from Get-DbaTrace output. This enables selective stopping of traces by piping Get-DbaTrace results through filtering commands like Out-GridView or Where-Object. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per trace that was stopped, with the following default display properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Id: The unique identifier of the trace IsRunning: Boolean indicating if the trace is currently running (false after successful stop) *Additional properties available via Select-Object :** Status: Current status of the trace Path: File path where trace events are logged MaxSize: Maximum size of the trace file in MB StopTime: DateTime when the trace will stop MaxFiles: Maximum number of trace files for rollover IsRowset: Boolean indicating if trace data is in rowset format IsRollover: Boolean indicating if trace file rollover is enabled IsShutdown: Boolean indicating if trace stops on shutdown IsDefault: Boolean indicating if this is the default trace BufferCount: Number of buffers in memory BufferSize: Size of each buffer in KB FilePosition: Current position in the trace file ReaderSpid: SPID of the trace reader process StartTime: DateTime when the trace started LastEventTime: DateTime of the last event logged EventCount: Total number of events logged DroppedEventCount: Number of events dropped due to buffer overflow Parent: Reference to the parent SQL Server object &nbsp;"
  },
  {
    "name": "Stop-DbaXESession",
    "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.",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Stop",
    "popular": false,
    "url": "/Stop-DbaXESession",
    "popularityRank": 659,
    "synopsis": "Stops running Extended Events sessions on SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Stop-DbaXESession View Source Doug Meyers Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Stops running Extended Events sessions on SQL Server instances 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. Syntax Stop-DbaXESession [-SqlInstance] [-SqlCredential ] -Session [-EnableException] [-WhatIf] [-Confirm] [ ] Stop-DbaXESession [-SqlInstance] [-SqlCredential ] -AllSessions [-EnableException] [-WhatIf] [-Confirm] [ ] Stop-DbaXESession -InputObject [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Stops all Extended Event Session on the sqlserver2014 instance PS C:\\> Stop-DbaXESession -SqlInstance sqlserver2012 -AllSessions Example 2: Stops the xesession1 and xesession2 Extended Event sessions PS C:\\> Stop-DbaXESession -SqlInstance sqlserver2012 -Session xesession1,xesession2 Example 3: Stops the sessions returned from the Get-DbaXESession function PS C:\\> Get-DbaXESession -SqlInstance sqlserver2012 -Session xesession1 | Stop-DbaXESession Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Session Specifies the names of specific Extended Events sessions to stop by name. Accepts session names as strings or arrays for multiple sessions. Use 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. | Property | Value | | --- | --- | | Alias | Sessions | | Required | True | | Pipeline | false | | Default Value | | -AllSessions Stops all user-created Extended Events sessions while preserving critical system sessions (AlwaysOn_health, system_health, telemetry_xevents). Use this when performing maintenance, reducing resource usage, or cleaning up after troubleshooting activities without disrupting essential SQL Server monitoring. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | False | -InputObject Accepts Extended Events session objects from Get-DbaXESession through the pipeline for stopping sessions. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.XEvent.Session Returns one Extended Events session object for each session that was stopped. The session objects reflect the stopped state after the command completes. Default display properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Name: The name of the Extended Events session State: The current state of the session (Created, Started, Stopped, or Altered) IsRunning: Boolean indicating if the session is currently running (false after stopping) StartTime: DateTime when the session was started (null if not currently running) DefinitionFileLocation: Path to the XML definition file for the session MaxMemory: Maximum memory in MB allocated to the session EventRetentionMode: How events are retained (AllowSingleEventLoss, AllowMultipleEventLoss, NoEventLoss, or DropOnFullBuffer) *Additional properties available on the SMO Session object (via Select-Object ):** Urn: The Uniform Resource Name for the session object Properties: Collection of session property objects TargetCount: Number of targets associated with the session EventCount: Number of events collected by the session MaxDispatchLatency: Maximum latency in seconds for event dispatch SuspendedEventCount: Number of currently suspended events &nbsp;"
  },
  {
    "name": "Suspend-DbaAgDbDataMovement",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Suspend",
    "popular": false,
    "url": "/Suspend-DbaAgDbDataMovement",
    "popularityRank": 394,
    "synopsis": "Suspends data synchronization for availability group databases to halt replication between replicas.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Suspend-DbaAgDbDataMovement View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Suspends data synchronization for availability group databases to halt replication between replicas. 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. Syntax Suspend-DbaAgDbDataMovement [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Database] ] [[-InputObject] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Suspends data movement on db1 and db2 to ag1 on sql2017a PS C:\\> Suspend-DbaAgDbDataMovement -SqlInstance sql2017a -AvailabilityGroup ag1 -Database db1, db2 Suspends data movement on db1 and db2 to ag1 on sql2017a. Prompts for confirmation. Example 2: Suspends data movement on the selected availability group databases PS C:\\> Get-DbaAgDatabase -SqlInstance sql2017a, sql2019 | Out-GridView -Passthru | Suspend-DbaAgDbDataMovement -Confirm:$false Suspends data movement on the selected availability group databases. Does not prompt for confirmation. Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies the availability group containing the databases to suspend. Required when using SqlInstance parameter. Use this to target databases within a specific AG when multiple availability groups exist on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which availability group databases to suspend data movement for. Accepts multiple database names. Use this when you need to halt synchronization for specific databases while leaving other AG databases running normally. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group database objects piped from Get-DbaAgDatabase or other dbatools AG commands. Use this for pipeline operations when you want to filter and select specific AG databases before suspending data movement. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.AvailabilityDatabase Returns one AvailabilityDatabase object for each database where data movement was suspended. When suspending data movement for multiple databases, one object is returned per database. Default display properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) AvailabilityGroup: Name of the availability group LocalReplicaRole: Role of this replica (Primary or Secondary) Name: Database name SynchronizationState: Current synchronization state (NotSynchronizing, Synchronizing, Synchronized, Reverting, Initializing) IsFailoverReady: Boolean indicating if the database is ready for failover IsJoined: Boolean indicating if the database has joined the availability group IsSuspended: Boolean indicating if data movement is suspended (true after suspension completes) *Additional properties available on the SMO AvailabilityDatabase object (via Select-Object ):** DatabaseGuid: Unique identifier for the database EstimatedDataLoss: Estimated data loss in seconds EstimatedRecoveryTime: Estimated recovery time in seconds FileStreamSendRate: Rate of FILESTREAM data being sent (bytes/sec) GroupDatabaseId: Unique identifier for the database within the AG LastCommitTime: Timestamp of last committed transaction LogSendQueue: Size of log send queue in KB RedoRate: Rate of redo operations (bytes/sec) &nbsp;"
  },
  {
    "name": "Sync-DbaAvailabilityGroup",
    "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't filter based on which objects are actually used by the availability group databases. Use the exclusion parameters to limit scope when needed.",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Sync",
    "popular": true,
    "url": "/Sync-DbaAvailabilityGroup",
    "popularityRank": 26,
    "synopsis": "Synchronizes server-level objects from primary to secondary replicas in availability groups",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Sync-DbaAvailabilityGroup View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Synchronizes server-level objects from primary to secondary replicas in availability groups 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. This 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: SpConfigure CustomErrors Credentials DatabaseMail LinkedServers Logins LoginPermissions SystemTriggers DatabaseOwner AgentCategory AgentOperator AgentAlert AgentProxy AgentSchedule AgentJob Any 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. The command copies ALL objects of each enabled type - it doesn't filter based on which objects are actually used by the availability group databases. Use the exclusion parameters to limit scope when needed. Syntax Sync-DbaAvailabilityGroup [[-Primary] ] [[-PrimarySqlCredential] ] [[-Secondary] ] [[-SecondarySqlCredential] ] [[-Credential] ] [[-AvailabilityGroup] ] [[-Exclude] ] [[-Login] ] [[-ExcludeLogin] ] [[-Job] ] [[-ExcludeJob] ] [-DisableJobOnDestination] [[-InputObject] ] [-ExcludePassword] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Syncs the following on all replicas found in the db3 AG: SpConfigure, CustomErrors, Credentials... PS C:\\> Sync-DbaAvailabilityGroup -Primary sql2016a -AvailabilityGroup db3 Syncs the following on all replicas found in the db3 AG: SpConfigure, CustomErrors, Credentials, DatabaseMail, LinkedServers Logins, LoginPermissions, SystemTriggers, DatabaseOwner, AgentCategory, AgentOperator, AgentAlert, AgentProxy, AgentSchedule, AgentJob Example 2: Syncs the following on all replicas found in all AGs on the specified instance: SpConfigure, CustomErrors... PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2016a | Sync-DbaAvailabilityGroup -ExcludeType LoginPermissions, LinkedServers -ExcludeLogin login1, login2 -Job job1, job2 Syncs the following on all replicas found in all AGs on the specified instance: SpConfigure, CustomErrors, Credentials, DatabaseMail, Logins, SystemTriggers, DatabaseOwner, AgentCategory, AgentOperator AgentAlert, AgentProxy, AgentSchedule, AgentJob. Copies all logins except for login1 and login2 and only syncs job1 and job2 Example 3: Shows what would happen if the command were to run but doesn&#39;t actually perform the action PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2016a | Sync-DbaAvailabilityGroup -WhatIf Optional Parameters -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. Required when not using InputObject parameter. Server version must be SQL Server 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PrimarySqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Secondary The secondary replica SQL Server instances where server-level objects will be copied to. Can specify multiple instances. If not specified, the function will automatically discover all secondary replicas in the availability group. Server version must be SQL Server 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecondarySqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential) Only used when passwords are being exported, as it requires access to the Windows OS via PowerShell remoting to decrypt the passwords. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup The name of the specific availability group to synchronize server objects for. When specified, the function will identify all replicas in this AG and sync objects from primary to all secondaries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Exclude Excludes specific object types from being synchronized to avoid conflicts or reduce sync time. Useful when you need to manually manage certain objects or when some object types cause issues in your environment. Valid values: SpConfigure, CustomErrors, Credentials, DatabaseMail, LinkedServers, Logins, LoginPermissions, SystemTriggers, DatabaseOwner, AgentCategory, AgentOperator, AgentAlert, AgentProxy, AgentSchedule, AgentJob | Property | Value | | --- | --- | | Alias | ExcludeType | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. Use this when you only need to sync specific service accounts or application logins rather than all logins on the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeLogin Specifies login accounts to skip during synchronization. Accepts an array of login names. Commonly used to exclude system accounts, sa, or logins that should remain unique per replica for monitoring or maintenance purposes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies which SQL Agent jobs to synchronize to secondary replicas. Accepts an array of job names. Use this when you only need to sync critical jobs like backup jobs or maintenance tasks rather than all jobs on the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJob Specifies SQL Agent jobs to skip during synchronization. Accepts an array of job names. Commonly used to exclude replica-specific jobs like log shipping, local backups, or jobs that should only run on the primary replica. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DisableJobOnDestination Disables all synchronized jobs on secondary replicas after copying them from the primary. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -InputObject Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline processing. Use this to sync multiple availability groups at once or to process specific AGs returned by filtering commands. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -ExcludePassword Copies credentials, linked servers, and other objects without the actual password values. Use this in security-conscious environments where password decryption is restricted or when passwords should be manually reset after migration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Force Drops and recreates existing objects on secondary replicas instead of skipping them. Use this when you need to update objects that already exist on secondaries or when objects have configuration differences that need to be synchronized. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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 primary to secondary replicas. The underlying sync commands (Copy-DbaSpConfigure, Copy-DbaLogin, Copy-DbaCustomError, Copy-DbaCredential, Copy-DbaDbMail, Copy-DbaLinkedServer, Copy-DbaInstanceTrigger, Copy-DbaAgentJobCategory, Copy-DbaAgentOperator, Copy-DbaAgentAlert, Copy-DbaAgentProxy, Copy-DbaAgentSchedule, Copy-DbaAgentJob, and Sync-DbaLoginPermission) may produce output when called directly with the underlying Copy-Dba and Sync-Dba* commands. &nbsp;"
  },
  {
    "name": "Sync-DbaLoginPassword",
    "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's 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.",
    "category": "Security",
    "tags": [
      "migration",
      "login",
      "password"
    ],
    "verb": "Sync",
    "popular": false,
    "url": "/Sync-DbaLoginPassword",
    "popularityRank": 0,
    "synopsis": "Synchronizes SQL Server login passwords between instances using hashed password values.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Sync-DbaLoginPassword View Source Shawn Melton (@wsmelton), http://www.wsmelton.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Synchronizes SQL Server login passwords between instances using hashed password values. 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's sp_help_revlogin by extracting and applying hashed password values. This is particularly useful for: Maintaining consistent passwords across Availability Group replicas Migrating logins between instances when users cannot provide their passwords Disaster recovery scenarios where password synchronization is critical Keeping development/test environments synchronized with production passwords The 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. Syntax Sync-DbaLoginPassword [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-InputObject] ] [[-Login] ] [[-ExcludeLogin] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Syncs all SQL Server authentication login passwords from sql2016 to sql2016ag1 and sql2016ag2 PS C:\\> Sync-DbaLoginPassword -Source sql2016 -Destination sql2016ag1, sql2016ag2 Syncs all SQL Server authentication login passwords from sql2016 to sql2016ag1 and sql2016ag2. Windows authentication logins are automatically skipped. Example 2: Syncs passwords only for the app_user and reports_user logins from sql2016 to sql2016ag1 PS C:\\> Sync-DbaLoginPassword -Source sql2016 -Destination sql2016ag1 -Login app_user, reports_user Example 3: Syncs all SQL Server login passwords except for sa and admin accounts from sql2016 to sql2016ag1 PS C:\\> Sync-DbaLoginPassword -Source sql2016 -Destination sql2016ag1 -ExcludeLogin sa, admin Example 4: Syncs all SQL Server login passwords using SQL Authentication credentials for both source and destination... PS C:\\> $splatSync = @{ >> Source = \"sql2016\" >> Destination = \"sql2016ag1\", \"sql2016ag2\" >> SourceSqlCredential = $sourceCred >> DestinationSqlCredential = $destCred >> EnableException = $true >> } PS C:\\> Sync-DbaLoginPassword @splatSync Syncs all SQL Server login passwords using SQL Authentication credentials for both source and destination connections. Throws exceptions on errors for easier scripting and automation. Example 5: Gets all SQL Server authentication logins from sql2016 and syncs their passwords to sql2016ag1 using pipeline... PS C:\\> Get-DbaLogin -SqlInstance sql2016 | Where-Object LoginType -eq \"SqlLogin\" | Sync-DbaLoginPassword -Destination sql2016ag1 Gets all SQL Server authentication logins from sql2016 and syncs their passwords to sql2016ag1 using pipeline input. Required Parameters -Source Specifies the source SQL Server instance to read login passwords from. The login password hashes will be extracted from this instance. You must have sysadmin access and the server version must be SQL Server 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -Destination Specifies the destination SQL Server instance(s) where login passwords will be updated. Accepts multiple instances to sync passwords to several servers simultaneously. The 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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Specifies alternative credentials to connect to the source SQL Server instance. Use this when your current Windows credentials don't have sysadmin access to the source server. Accepts PowerShell credentials created with Get-Credential. Supports Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Specifies alternative credentials to connect to the destination SQL Server instance(s). Use this when your current Windows credentials don't have sysadmin access to the destination server(s). Accepts PowerShell credentials created with Get-Credential. Supports Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Specifies login objects from the pipeline to sync passwords for. Accepts login objects from Get-DbaLogin. When using InputObject, only SQL Server authentication logins will be processed - Windows authentication logins are automatically filtered out. This parameter enables pipeline scenarios where you can filter logins first and then sync their passwords. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -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. Accepts multiple login names as an array. Only SQL Server authentication logins will be processed - Windows logins are automatically skipped. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeLogin Specifies login names to exclude from the password sync process. Use this to skip specific accounts that shouldn't have their passwords synced. Commonly used to exclude service accounts, application accounts, or logins with environment-specific passwords that should remain different between servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per login password synchronized, whether successful or failed. Properties: SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Login: The name of the login whose password was synced Status: The result of the operation - either \"Success\" or \"Failed\" Notes: Additional details about the operation; null for successful syncs, error message for failures &nbsp;"
  },
  {
    "name": "Sync-DbaLoginPermission",
    "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.",
    "category": "Security",
    "tags": [
      "migration",
      "login"
    ],
    "verb": "Sync",
    "popular": true,
    "url": "/Sync-DbaLoginPermission",
    "popularityRank": 38,
    "synopsis": "Synchronizes login permissions and role memberships between SQL Server instances.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Sync-DbaLoginPermission View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Synchronizes login permissions and role memberships between SQL Server instances. 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. The 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. If 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. Syntax Sync-DbaLoginPermission [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Login] ] [[-ExcludeLogin] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Syncs only SQL Server login permissions, roles, etc PS C:\\> Sync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster Syncs only SQL Server login permissions, roles, etc. Does not add or drop logins or users. To copy logins and their permissions, use Copy-SqlLogin. Example 2: Copies all login permissions except for realcajun using SQL Authentication to connect to each server PS C:\\> Sync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster -Exclude realcajun -SourceSqlCredential $scred -DestinationSqlCredential $dcred Copies 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. Example 3: Copies permissions ONLY for logins netnerds and realcajun PS C:\\> Sync-DbaLoginPermission -Source sqlserver2014a -Destination sqlcluster -Login realcajun, netnerds Required Parameters -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. You must have sysadmin access and the server version must be SQL Server 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Destination Specifies the destination SQL Server instance(s) where login permissions will be applied. Accepts multiple instances to sync permissions to several servers simultaneously. The 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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Specifies alternative credentials to connect to the source SQL Server instance. Use this when your current Windows credentials don't have access to the source server. Accepts PowerShell credentials created with Get-Credential. Supports Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Specifies alternative credentials to connect to the destination SQL Server instance(s). Use this when your current Windows credentials don't have access to the destination server(s). Accepts PowerShell credentials created with Get-Credential. Supports Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Accepts 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). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeLogin Specifies login names to exclude from the permission sync process. Use this to skip specific accounts that shouldn't have their permissions synced. Commonly used to exclude service accounts, shared accounts, or logins with environment-specific permissions that should remain different between servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject with TypeName MigrationObject Returns one object per login per destination server showing the result of the permission sync operation. Objects are output immediately as each login's permissions are synced, not collected at the end. Properties: SourceServer: The name of the source SQL Server instance DestinationServer: The name of the destination SQL Server instance Name: The login name that was synced Type: The operation type (always \"Login Permissions\") Status: Result of the sync operation (Successful or Failed) Notes: Error message details if Status is Failed, null if Successful DateTime: DbaDateTime object representing when the sync was attempted &nbsp;"
  },
  {
    "name": "Test-DbaAgentJobOwner",
    "description": "This function audits SQL Agent job ownership by comparing each job's current owner against a target login, typically 'sa' 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 'sa' account (or renamed sysadmin), but you can specify any valid login for your organization's security standards. Returns only jobs that don't 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",
    "category": "Agent & Jobs",
    "tags": [
      "agent",
      "job",
      "owner"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaAgentJobOwner",
    "popularityRank": 428,
    "synopsis": "Identifies SQL Agent jobs with incorrect ownership for security compliance auditing",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaAgentJobOwner View Source Michael Fal (@Mike_Fal), mikefal.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies SQL Agent jobs with incorrect ownership for security compliance auditing Description This function audits SQL Agent job ownership by comparing each job's current owner against a target login, typically 'sa' 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 'sa' account (or renamed sysadmin), but you can specify any valid login for your organization's security standards. Returns only jobs that don't match the expected ownership, making it easy to identify compliance violations that need remediation. Best practice reference: https://www.itprotoday.com/sql-server-tip-assign-ownership-jobs-sysadmin-account Syntax Test-DbaAgentJobOwner [-SqlInstance] [[-SqlCredential] ] [[-Job] ] [[-ExcludeJob] ] [[-Login] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all SQL Agent Jobs where the owner does not match &#39;sa&#39; PS C:\\> Test-DbaAgentJobOwner -SqlInstance localhost Example 2: Returns SQL Agent Jobs except for the syspolicy_purge_history job PS C:\\> Test-DbaAgentJobOwner -SqlInstance localhost -ExcludeJob 'syspolicy_purge_history' Example 3: Returns all SQL Agent Jobs where the owner does not match DOMAIN\\account PS C:\\> Test-DbaAgentJobOwner -SqlInstance localhost -Login DOMAIN\\account Returns all SQL Agent Jobs where the owner does not match DOMAIN\\account. Note that Login must be a valid security principal that exists on the target server. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Job Specifies specific SQL Agent jobs to check for ownership compliance. When provided, only these named jobs are evaluated against the target owner. Use this to focus on critical jobs or when troubleshooting specific ownership issues. If omitted, all jobs on the instance are processed. | Property | Value | | --- | --- | | Alias | Jobs | | Required | False | | Pipeline | false | | Default Value | | -ExcludeJob Excludes specific SQL Agent jobs from the ownership compliance check. Useful for skipping system jobs or jobs that legitimately require different owners. Commonly used to exclude jobs like 'syspolicy_purge_history' or maintenance jobs that run under service accounts by design. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Defaults to 'sa' (or the renamed sysadmin account). Common alternatives include service accounts or dedicated job owner logins required by your organization's security policies. | Property | Value | | --- | --- | | Alias | TargetLogin | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 returned regardless of ownership status. Properties: Server: The name of the SQL Server instance Job: The name of the SQL Agent job JobType: Type of job (Remote for remote jobs, LocalJob, or other job type values) CurrentOwner: The login name that currently owns this job TargetOwner: The expected login name that should own this job (default 'sa' or specified via -Login parameter) OwnerMatch: Boolean indicating if the current owner matches the target owner &nbsp;"
  },
  {
    "name": "Test-DbaAgPolicyState",
    "description": "Evaluates the health of SQL Server Availability Groups by checking them against\nMicrosoft's predefined Always On policies from the Policy-Based Management framework.\n\nReturns one object per policy evaluated, including whether the policy check passed\n(IsHealthy), the policy name, category, facet, issue description, and details.\n\nBased on the Microsoft documentation at:\nhttps://learn.microsoft.com/en-us/sql/database-engine/availability-groups/windows/always-on-policies-for-operational-issues-always-on-availability",
    "category": "Advanced Features",
    "tags": [
      "availabilitygroup",
      "ha",
      "ag",
      "test",
      "policy"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaAgPolicyState",
    "popularityRank": 0,
    "synopsis": "Tests Availability Group health against Microsoft's Always On predefined policies.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaAgPolicyState View Source the dbatools team + Claude Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests Availability Group health against Microsoft's Always On predefined policies. Description Evaluates the health of SQL Server Availability Groups by checking them against Microsoft's predefined Always On policies from the Policy-Based Management framework. Returns one object per policy evaluated, including whether the policy check passed (IsHealthy), the policy name, category, facet, issue description, and details. Based on the Microsoft documentation at: https://learn.microsoft.com/en-us/sql/database-engine/availability-groups/windows/always-on-policies-for-operational-issues-always-on-availability Syntax Test-DbaAgPolicyState [[-SqlInstance] ] [[-SqlCredential] ] [[-AvailabilityGroup] ] [[-Secondary] ] [[-SecondarySqlCredential] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Evaluates all predefined Always On policies for the availability group TestAG on sql2019 PS C:\\> Test-DbaAgPolicyState -SqlInstance sql2019 -AvailabilityGroup TestAG Example 2: Evaluates all predefined Always On policies for all availability groups on sql2019 PS C:\\> Test-DbaAgPolicyState -SqlInstance sql2019 Example 3: Evaluates all predefined Always On policies for all availability groups on sql2019 using pipeline input PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql2019 | Test-DbaAgPolicyState Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies which availability groups to evaluate. If not specified, all availability groups are evaluated. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Secondary Specifies secondary replica endpoints when they use non-standard ports or custom connection strings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecondarySqlCredential Specifies credentials for connecting to secondary replica instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group objects from Get-DbaAvailabilityGroup via pipeline input. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per policy evaluated. Properties: ComputerName: The computer name of the SQL Server instance (string) InstanceName: The SQL Server instance name (string) SqlInstance: The full SQL Server instance name (string) AvailabilityGroup: Name of the availability group (string) Replica: Name of the availability replica for replica-level policies, $null for server/AG-level policies (string) Database: Name of the availability database for database-level policies, $null for server/AG/replica-level policies (string) PolicyName: The name of the Always On policy being evaluated (string) Category: The severity of the policy - Critical or Warning (string) Facet: The object type the policy applies to (string) IsHealthy: Boolean indicating whether the policy check passed (bool) Issue: Description of the issue when the policy is not healthy, $null when healthy (string) Details: Additional detail about the current state (string) &nbsp;"
  },
  {
    "name": "Test-DbaAgSpn",
    "description": "Checks whether the required SPNs are properly registered in Active Directory for each Availability Group listener's 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",
    "category": "Advanced Features",
    "tags": [
      "ag",
      "ha"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaAgSpn",
    "popularityRank": 466,
    "synopsis": "Validates Service Principal Name registration for Availability Group listeners in Active Directory",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaAgSpn View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates Service Principal Name registration for Availability Group listeners in Active Directory Description Checks whether the required SPNs are properly registered in Active Directory for each Availability Group listener's 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. Use 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. https://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 Syntax Test-DbaAgSpn [[-SqlInstance] ] [[-SqlCredential] ] [[-Credential] ] [[-AvailabilityGroup] ] [[-Listener] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Tests the SPNs for the SharePoint availability group listeners on sql01 PS C:\\> Get-DbaAvailabilityGroup -SqlInstance sql01 -AvailabilityGroup SharePoint | Test-DbaAgSpn Example 2: Tests the spag01 SPN for the SharePoint availability group listener on sql01 PS C:\\> Test-DbaAgSpn -SqlInstance sql01 -AvailabilityGroup SharePoint -Listener spag01 Example 3: Tests the SPNs for all availability group listeners on sql01 and sets them if they are not set PS C:\\> Test-DbaAgSpn -SqlInstance sql01 | Set-DbaSpn Optional Parameters -SqlInstance The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Alternative credential for connecting to Active Directory. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. If not specified, all availability groups will be tested. Accepts multiple AG names for bulk validation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Listener Specifies which AG listeners to validate SPNs for by listener name. Use this when troubleshooting specific listener connectivity issues. If not specified, all listeners within the specified availability groups will be tested. Accepts multiple listener names. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts availability group objects from Get-DbaAvailabilityGroup for pipeline processing. Use this to chain commands when working with specific AG objects. This allows for filtering AGs before SPN validation without needing to specify instance and AG names separately. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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., MSSQLSvc/listener.domain.com:1433). The function queries Active Directory to verify SPN registration and reports the validation status. Properties: ComputerName: The fully qualified network name of the computer hosting the SQL Server instance SqlInstance: The SQL Server instance name InstanceName: The instance name (defaults to MSSQLSERVER for default instance) SqlProduct: The SQL Server product version string including edition and platform information InstanceServiceAccount: The service account running SQL Server (may be modified if virtual or managed service account is detected) RequiredSPN: The Service Principal Name that should be registered in Active Directory IsSet: Boolean indicating whether the required SPN is currently registered in Active Directory (true if found, false if missing) Cluster: Boolean indicating whether SQL Server is running in a clustered configuration TcpEnabled: Boolean indicating whether TCP protocol is enabled (always true for AG listeners) Port: The TCP port number the listener uses DynamicPort: Boolean indicating whether dynamic port allocation is enabled (always false for AG listeners) Warning: Reserved for warning messages; contains \"None\" unless a warning condition is detected Error: Contains \"SPN missing\" if the SPN is not found in Active Directory, or \"None\" if the SPN is properly registered Note: The Credential and DomainName properties are excluded from the default display but remain accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Test-DbaAvailabilityGroup",
    "description": "Verifies that all replicas in an Availability Group are connected and communicating properly by checking ConnectionState across all replicas from the primary's 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't have to troubleshoot failed Add-DbaAgDatabase operations later.",
    "category": "Advanced Features",
    "tags": [
      "availabilitygroup",
      "ha",
      "ag",
      "test"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaAvailabilityGroup",
    "popularityRank": 76,
    "synopsis": "Validates Availability Group replica connectivity and database prerequisites for AG operations",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaAvailabilityGroup View Source Andreas Jordan (@JordanOrdix), ordix.de Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates Availability Group replica connectivity and database prerequisites for AG operations Description Verifies that all replicas in an Availability Group are connected and communicating properly by checking ConnectionState across all replicas from the primary's perspective. This helps you identify connectivity issues that could impact failover capabilities or data synchronization. When 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. This prevents common AG setup failures by catching configuration issues early, so you don't have to troubleshoot failed Add-DbaAgDatabase operations later. Syntax Test-DbaAvailabilityGroup [-SqlInstance] [-SqlCredential ] -AvailabilityGroup [-Secondary ] [-SecondarySqlCredential ] [-AddDatabase ] [-SeedingMode ] [-SharedPath ] [-UseLastBackup] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Test Availability Group TestAG1 with SQL2016 as the primary replica PS C:\\> Test-DbaAvailabilityGroup -SqlInstance SQL2016 -AvailabilityGroup TestAG1 Example 2: Test if database AdventureWorks can be added to the Availability Group TestAG1 with automatic seeding PS C:\\> Test-DbaAvailabilityGroup -SqlInstance SQL2016 -AvailabilityGroup TestAG1 -AddDatabase AdventureWorks -SeedingMode Automatic Required Parameters -SqlInstance The primary replica of the Availability Group. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -AvailabilityGroup Specifies the Availability Group name to validate for replica connectivity and database prerequisites. Use this to target a specific AG when testing health status or preparing to add databases. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Secondary Specifies secondary replica endpoints when they use non-standard ports or custom connection strings. The function auto-discovers secondary replicas from the AG configuration, but use this when replicas listen on custom ports or require specific connection parameters. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SecondarySqlCredential Specifies credentials for connecting to secondary replica instances during validation. Use this when secondary replicas require different authentication than the primary replica, such as in cross-domain scenarios or when using SQL authentication on secondaries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AddDatabase Specifies database names to validate for Availability Group addition prerequisites. Triggers comprehensive validation including recovery model, database status, backup history, and seeding compatibility checks. Use this to prevent Add-DbaAgDatabase failures by catching configuration issues early. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SeedingMode Specifies the database seeding method for validation when using AddDatabase parameter. Use 'Automatic' for SQL Server 2016+ environments or 'Manual' when you need to control backup/restore operations. This determines the prerequisite validation logic performed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | Automatic,Manual | -SharedPath Specifies the network path accessible by all replicas for backup and restore operations during manual seeding validation. Required when AddDatabase uses manual seeding and databases need to be restored on secondary replicas. Must be accessible by all SQL Server service accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -UseLastBackup Validates that the most recent database backup chain can be used for AG database addition. Enables 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Without the -AddDatabase parameter, returns one object per Availability Group tested with the following properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) AvailabilityGroup: The name of the Availability Group being tested With the -AddDatabase parameter, returns one object per database being added with the following properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) AvailabilityGroupName: The name of the Availability Group DatabaseName: The name of the database being added to the AG AvailabilityGroupSMO: The Microsoft.SqlServer.Management.Smo.AvailabilityGroup object for the AG DatabaseSMO: The Microsoft.SqlServer.Management.Smo.Database object for the database PrimaryServerSMO: The Microsoft.SqlServer.Management.Smo.Server object for the primary replica ReplicaServerSMO: A hashtable mapping secondary replica names to their Microsoft.SqlServer.Management.Smo.Server objects RestoreNeeded: A hashtable mapping replica names to boolean values indicating if database restore is needed on that replica Backups: An array of backup history objects from Get-DbaDbBackupHistory (when -UseLastBackup is specified) &nbsp;"
  },
  {
    "name": "Test-DbaBackupEncrypted",
    "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.",
    "category": "Security",
    "tags": [
      "backups",
      "encryption"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaBackupEncrypted",
    "popularityRank": 456,
    "synopsis": "Analyzes backup files to determine encryption status and retrieve encryption details",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaBackupEncrypted View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Analyzes backup files to determine encryption status and retrieve encryption details 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. Syntax Test-DbaBackupEncrypted [[-SqlInstance] ] [[-SqlCredential] ] [-FilePath] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Test to see if /tmp/northwind.bak is encrypted PS C:\\> Test-DbaBackupEncrypted -SqlInstance sql01 -Path /tmp/northwind.bak Example 2: Test to see if all of the backups in \\\\nas\\sql\\backups are encrypted PS C:\\> Get-ChildItem \\\\nas\\sql\\backups | Test-DbaBackupEncrypted -SqlInstance sql01 Required Parameters -FilePath Specifies the file path(s) to the backup files (.bak, .trn, .dif) that need to be analyzed for encryption status. Accepts multiple paths and supports pipeline input from Get-ChildItem or other file discovery commands. Use this to verify encryption compliance across backup files or troubleshoot restore failures caused by missing encryption certificates. | Property | Value | | --- | --- | | Alias | FullName,Path | | Required | True | | Pipeline | true (ByPropertyName) | | Default Value | | Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per backup file analyzed, containing encryption status and certificate information. Properties: ComputerName (string) - The computer name of the SQL Server instance used for analysis InstanceName (string) - The SQL Server instance name used for analysis SqlInstance (string) - The full SQL Server instance name (computer\\instance) FilePath (string) - The file path of the backup file that was analyzed BackupName (string) - The logical name of the backup set from RESTORE HEADERONLY output Encrypted (boolean) - Boolean indicating if the backup contains encryption from backup encryption or Transparent Data Encryption (TDE) KeyAlgorithm (string) - The encryption key algorithm (e.g., \"AES128\", \"AES192\", \"AES256\", null if not encrypted via backup encryption) EncryptorThumbprint (string) - The SHA-1 thumbprint of the backup encryption certificate (null if not encrypted via backup encryption) EncryptorType (string) - The type of backup encryptor (e.g., \"Certificate\", \"Asymmetric Key\", null if no backup encryption) TDEThumbprint (string) - The TDE thumbprint in hexadecimal format from FILELISTONLY (null if database was not encrypted with TDE) Compressed (boolean) - Boolean indicating if the backup was created with compression enabled &nbsp;"
  },
  {
    "name": "Test-DbaBackupInformation",
    "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't 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",
    "category": "Backup & Restore",
    "tags": [
      "backup",
      "restore",
      "disasterrecovery"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaBackupInformation",
    "popularityRank": 194,
    "synopsis": "Validates backup history objects to ensure successful database restoration",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaBackupInformation View Source Stuart Moore (@napalmgram), stuart-moore.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates backup history objects to ensure successful database restoration 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. This 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. Use 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. Tests performed include: Checking unbroken LSN chain for transaction log backups Verifying target database doesn't exist unless WithReplace is specified Ensuring backup files exist and are accessible by SQL Server service account Validating no file conflicts with existing databases Creating required target directories for database files Confirming backup files can be read from the specified locations Syntax Test-DbaBackupInformation [-BackupHistory] [[-SqlInstance] ] [[-SqlCredential] ] [-WithReplace] [-Continue] [-VerifyOnly] [-OutputScriptOnly] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Pass in a BackupHistory object to be tested against MyInstance PS C:\\> $BackupHistory | Test-DbaBackupInformation -SqlInstance MyInstance PS C:\\> $PassedDbs = $BackupHistory | Where-Object {$_.IsVerified -eq $True} PS C:\\> $FailedDbs = $BackupHistory | Where-Object {$_.IsVerified -ne $True} Pass in a BackupHistory object to be tested against MyInstance. Those records that pass are marked as verified. We can then use the IsVerified property to divide the failures and successes Required Parameters -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 database name, backup type, LSN values, and file paths. Pass the output from Format-DbaBackupInformation to validate the entire restore sequence before attempting restoration. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlInstance The Sql Server instance that wil be performing the restore | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this when performing disaster recovery or refresh scenarios where you need to replace the current database with backup data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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 already exist in RESTORING state. Use this when performing point-in-time recovery scenarios where you're applying additional log backups after an initial restore. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Use this when you only need to verify that backup files are valid and accessible without testing restore feasibility to the target instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -OutputScriptOnly Prevents automatic creation of missing target directories during validation. Missing paths generate warnings instead of being created automatically. Use this for testing restore scenarios without making changes to the file system, or when you need to verify permissions before allowing directory creation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before running the cmdlet. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs The same backup history object type provided as input, with an additional IsVerified property Returns one validated backup history object per input backup, with all original properties preserved and an added IsVerified property. Properties: 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 accessibility, database conflicts, and path availability). Set to $False or left unchanged for backups with validation errors. All 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 verification status for filtering restoration candidates. &nbsp;"
  },
  {
    "name": "Test-DbaBuild",
    "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.",
    "category": "Utilities",
    "tags": [
      "sqlbuild",
      "version",
      "utility"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaBuild",
    "popularityRank": 83,
    "synopsis": "Tests SQL Server build versions against patching compliance requirements",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaBuild View Source Simone Bizzotto (@niphold) , Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests SQL Server build versions against patching compliance requirements 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. Syntax Test-DbaBuild [[-Build] ] [[-MinimumBuild] ] [[-MaxBehind] ] [[-MaxTimeBehind] ] [-Latest] [[-SqlInstance] ] [[-SqlCredential] ] [-Update] [-Quiet] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns information about a build identified by &quot;12.0.5540&quot; (which is SQL 2014 with SP2 and CU4), which is... PS C:\\> Test-DbaBuild -Build \"12.0.5540\" -MinimumBuild \"12.0.5557\" Returns 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 build is \"12.0.5557\" (which is SQL 2014 with SP2 and CU8). Example 2: Returns information about a build identified by &quot;12.0.5540&quot;, making sure it is AT MOST 1 Service Pack &quot;behind&quot; PS C:\\> Test-DbaBuild -Build \"12.0.5540\" -MaxBehind \"1SP\" Returns information about a build identified by \"12.0.5540\", making sure it is AT MOST 1 Service Pack \"behind\". For that version, that identifies an SP2, means accepting as the lowest compliance version as \"12.0.4110\", that identifies 2014 with SP1. Output column CUTarget is not relevant (empty). SPTarget and BuildTarget are filled in the result. Example 3: Returns information about a build identified by &quot;12.0.5540&quot;, making sure it is AT MOST 1 Service Pack... PS C:\\> Test-DbaBuild -Build \"12.0.5540\" -MaxBehind \"1SP 1CU\" Returns 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, that 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 will be \"12.0.4511\", which is 2014 with SP1 and CU12. Example 4: Returns information about a build identified by &quot;12.0.5540&quot;, making sure it is the latest CU release PS C:\\> Test-DbaBuild -Build \"12.0.5540\" -MaxBehind \"0CU\" Returns information about a build identified by \"12.0.5540\", making sure it is the latest CU release. Output columns CUTarget, SPTarget and BuildTarget are relevant. If the latest build is a service pack (not a CU), CUTarget will be empty. Example 5: Returns information about a build identified by &quot;12.0.5540&quot;, making sure it is the latest build available PS C:\\> Test-DbaBuild -Build \"12.0.5540\" -Latest Returns information about a build identified by \"12.0.5540\", making sure it is the latest build available. Output columns CUTarget and SPTarget are not relevant (empty), only the BuildTarget is. Example 6: Same as before, but tries to fetch the most up to date index online PS C:\\> Test-DbaBuild -Build \"12.00.4502\" -MinimumBuild \"12.0.4511\" -Update Same as before, but tries to fetch the most up to date index online. When the online version is newer, the local one gets overwritten. Example 7: Returns information builds identified by these versions strings PS C:\\> Test-DbaBuild -Build \"12.0.4502\",\"10.50.4260\" -MinimumBuild \"12.0.4511\" Example 8: Integrate with other cmdlets to have builds checked for all your registered servers on sqlserver2014a PS C:\\> Get-DbaRegServer -SqlInstance sqlserver2014a | Test-DbaBuild -MinimumBuild \"12.0.4511\" Example 9: Returns information about SQL Server 2022 CU10 (16.0.4095), checking whether it was released within the last... PS C:\\> Test-DbaBuild -Build \"16.0.4095\" -MaxTimeBehind \"6Mo\" Returns information about SQL Server 2022 CU10 (16.0.4095), checking whether it was released within the last 6 months. Requires ReleaseDate data in the build reference index. Example 10: Checks all instances in $servers to ensure they are running a build released within the last 180 days PS C:\\> Test-DbaBuild -SqlInstance $servers -MaxTimeBehind \"180D\" -Update Checks all instances in $servers to ensure they are running a build released within the last 180 days. Updates the build reference index before performing the check. Optional Parameters -Build Specifies one or more SQL Server build version numbers to test for compliance instead of connecting to live instances. Use this when you want to check specific build versions like \"12.0.5540\" without querying actual servers. Accepts version strings in the format major.minor.build or major.minor.build.revision. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MinimumBuild Sets the baseline build version that defines compliance requirements for your environment. Any SQL Server instance running a build version below this threshold will be flagged as non-compliant. Commonly used to enforce minimum security patch levels across your SQL Server estate. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaxBehind Defines compliance based on how many service packs or cumulative updates behind the latest release is acceptable. Use format like \"1SP\", \"2CU\", or \"1SP 1CU\" to specify maximum allowed gaps from current releases. This approach automatically adjusts compliance targets as new patches are released, unlike fixed MinimumBuild values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaxTimeBehind Defines compliance based on how much time has elapsed since the current build was released. Use format like \"6Mo\" for months or \"180D\" for days to specify the maximum acceptable build age. Requires ReleaseDate data in the build reference index. Builds without release date information will be reported as non-compliant with a warning. This approach aligns with organizational patch policies measured in time (e.g., \"all instances must run a build released within the last 6 months\"). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Latest Requires SQL Server instances to be running the most current build available for their version. Use this for environments with strict currency requirements where any outdated build is considered non-compliant. Automatically determines the latest available build for each SQL Server major version. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SqlInstance Target any number of instances, in order to return their compliance state. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Update Downloads the latest SQL Server build reference data from online sources before performing compliance checks. Use this periodically to ensure your compliance testing includes recently released patches and cumulative updates. The updated reference data is cached locally for subsequent function calls. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Quiet Returns only boolean compliance results ($true/$false) instead of detailed build information objects. Designed for use in automated scripts where you only need to know pass/fail status. Useful for integration with monitoring systems or compliance dashboards. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Boolean (when -Quiet parameter is specified) Returns only the compliance result: $true if the build is compliant, $false if non-compliant. Designed for automated scripts and monitoring system integration. PSCustomObject (default) Returns one build compliance object per build version tested. The object includes build information and compliance status with the following properties: Always included: Build: The SQL Server build version being tested MatchType: How the build was matched - \"Exact\" for recognized builds or \"Approximate\" for unrecognized versions Compliant: Boolean indicating if the build meets the specified compliance requirement ($true or $false) When -MinimumBuild is specified: MinimumBuild: The baseline build version that was used for comparison SPTarget, CUTarget, BuildTarget: Hidden (not shown by default) When -MaxBehind or -Latest is specified: MaxBehind: The maximum allowed gap specification (e.g., \"1SP\", \"2CU\", \"1SP 1CU\") or empty for -Latest SPTarget: Target Service Pack level required for compliance (null when -Latest or -MaxBehind uses only CU specification) CUTarget: Target Cumulative Update level required for compliance (null when -Latest or -MaxBehind uses only SP specification) BuildTarget: The target build version that represents the compliance threshold MinimumBuild: Hidden (not shown by default) When -MaxTimeBehind is specified: MaxTimeBehind: The maximum time window specification (e.g., \"6Mo\", \"180D\") BuildTarget: The oldest build version released within the time window (represents minimum acceptable version) MinimumBuild: Hidden (not shown by default) MaxBehind: Hidden (not shown by default) SPTarget: Hidden (not shown by default) CUTarget: Hidden (not shown by default) When -SqlInstance is specified (instead of -Build): SqlInstance: The source SQL Server instance where the build was discovered When -SqlInstance is not specified (using -Build): SqlInstance: Hidden (not shown by default) All properties can be accessed using Select-Object * regardless of the default display. &nbsp;"
  },
  {
    "name": "Test-DbaCmConnection",
    "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.",
    "category": "Utilities",
    "tags": [
      "computermanagement",
      "cim"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaCmConnection",
    "popularityRank": 314,
    "synopsis": "Tests remote computer management connectivity using multiple protocols and caches optimal connection methods",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaCmConnection View Source Friedrich Weinmann (@FredWeinmann) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests remote computer management connectivity using multiple protocols and caches optimal connection methods Description Tests remote computer connectivity across four different management protocols to determine the most reliable connection method for SQL Server administration tasks. This function evaluates connectivity for: CIM over WinRM (Windows Remote Management) CIM over DCOM (Distributed Component Object Model) WMI (Windows Management Instrumentation) PowerShell Remoting Results 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. This function bypasses global configuration settings that might restrict certain protocols, allowing you to test all available connection types regardless of your dbatools configuration. Syntax Test-DbaCmConnection [[-ComputerName] ] [[-Credential] ] [[-Type] {None | CimRM | CimDCOM | Wmi | PowerShellRemoting}] [-Force] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Performs a full-spectrum connection test against the computer sql2014 PS C:\\> Test-DbaCmConnection -ComputerName sql2014 Performs 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. Example 2: This test will run a connectivity test of CIM over DCOM and CIM over WinRM against the computer sql2014 using... PS C:\\> Test-DbaCmConnection -ComputerName sql2014 -Credential $null -Type CimDCOM, CimRM This test will run a connectivity test of CIM over DCOM and CIM over WinRM against the computer sql2014 using Windows Authentication. The results will be reported and registered. Future calls from Get-DbaCmObject will recognize the results and optimize the query. Optional Parameters -ComputerName Specifies the target computers to test management connectivity against. Accepts computer names, IP addresses, or FQDN formats. Use this to validate which remote management protocols work before running other dbatools commands that require computer management access. Defaults to the local computer if not specified. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $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 'Cache.Management.Disable.BadCredentialList' configuration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies which remote management protocols to test for connectivity. Tests all four protocols by default. Use this to focus testing on specific protocols when troubleshooting connectivity issues or when you know certain protocols are blocked in your environment. Available options: CimRM (CIM over WinRM), CimDCOM (CIM over DCOM), Wmi (legacy WMI), PowerShellRemoting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @(\"CimRM\", \"CimDCOM\", \"Wmi\", \"PowerShellRemoting\") | -Force Forces testing even when credentials are cached as previously failed. Removes bad credential cache entries and retests connectivity. Use this when credentials have been updated or when network connectivity issues have been resolved since the last test. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Connection.ConnectionManager Returns one connection manager object containing the results of connectivity testing across all requested management protocols. Default properties displayed: ComputerName: The target computer name being tested (lowercase format) CimRM: Result of CIM over WinRM connectivity test (\"Success\" or \"Error\") CimDCOM: Result of CIM over DCOM connectivity test (\"Success\" or \"Error\") Wmi: Result of WMI connectivity test (\"Success\" or \"Error\") PowerShellRemoting: Result of PowerShell Remoting connectivity test (\"Success\" or \"Error\") Additional properties available (from ConnectionManager object): LastCimRM: DateTime of the most recent CIM over WinRM connectivity test LastCimDCOM: DateTime of the most recent CIM over DCOM connectivity test LastWmi: DateTime of the most recent WMI connectivity test LastPowerShellRemoting: DateTime of the most recent PowerShell Remoting test KnownBadCredentials: Collection of credentials that have failed in previous tests DisableBadCredentialCache: Boolean indicating if bad credential caching is disabled The returned object is automatically cached by dbatools for optimization of future connections using Get-DbaCmObject and Invoke-DbaCmMethod. &nbsp;"
  },
  {
    "name": "Test-DbaComputerCertificateExpiration",
    "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's 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's 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.",
    "category": "Security",
    "tags": [
      "certificate",
      "security"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaComputerCertificateExpiration",
    "popularityRank": 271,
    "synopsis": "Identifies SSL/TLS certificates that are expired or expiring soon on SQL Server computers",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaComputerCertificateExpiration View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies SSL/TLS certificates that are expired or expiring soon on SQL Server computers 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. By default, it examines certificates that are candidates for SQL Server's 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's expiration date against a configurable threshold (30 days by default) and returns detailed information about any certificates requiring attention. This is essential for maintaining secure SQL Server connections and preventing unexpected service disruptions caused by expired certificates. Syntax Test-DbaComputerCertificateExpiration [[-ComputerName] ] [[-Credential] ] [[-Store] ] [[-Folder] ] [[-Type] ] [[-Path] ] [[-Thumbprint] ] [[-Threshold] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Gets computer certificates on localhost that are candidates for using with SQL Server&#39;s network encryption... PS C:\\> Test-DbaComputerCertificateExpiration Gets computer certificates on localhost that are candidates for using with SQL Server's network encryption then checks to see if they'll be expiring within 30 days Example 2: Gets computer certificates on sql2016 that are candidates for using with SQL Server&#39;s network encryption then... PS C:\\> Test-DbaComputerCertificateExpiration -ComputerName sql2016 -Threshold 90 Gets computer certificates on sql2016 that are candidates for using with SQL Server's network encryption then checks to see if they'll be expiring within 90 days Example 3: Gets computer certificates on sql2016 that match thumbprints 8123472E32AB412ED4288888B83811DB8F504DED or... PS C:\\> Test-DbaComputerCertificateExpiration -ComputerName sql2016 -Thumbprint 8123472E32AB412ED4288888B83811DB8F504DED, 04BFF8B3679BB01A986E097868D8D494D70A46D6 Gets computer certificates on sql2016 that match thumbprints 8123472E32AB412ED4288888B83811DB8F504DED or 04BFF8B3679BB01A986E097868D8D494D70A46D6 then checks to see if they'll be expiring within 30 days Optional Parameters -ComputerName The target SQL Server instance or instances. Defaults to localhost. If target is a cluster, you must specify the distinct nodes. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Allows you to login to $ComputerName using alternative credentials. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Store Specifies the certificate store to scan for certificates. Defaults to LocalMachine which contains system-wide certificates. Use this when you need to check certificates in different stores like CurrentUser for user-specific certificates. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | LocalMachine | -Folder Specifies the certificate folder within the store to examine. Defaults to My (Personal) where SSL certificates are typically stored. Common folders include My for personal certificates, Root for trusted root authorities, and CA for intermediate certificate authorities. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | My | -Type Determines which certificates to examine based on their intended use. Defaults to Service which finds certificates suitable for SQL Server. Service finds certificates that meet SQL Server's requirements but may also be used by other services like IIS. SQL Server returns only certificates currently configured for use by SQL Server instances. All examines every certificate in the specified store regardless of suitability. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Service | | Accepted Values | All,Service,SQL Server | -Path Specifies the file system path to a specific certificate file to examine instead of scanning certificate stores. Use this when you have certificate files (.cer, .crt, .pfx) on disk that you want to check for expiration. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Thumbprint Filters results to certificates matching the specified thumbprint values. Accepts multiple thumbprints as an array. Use this when you need to check specific certificates you've identified through other means or are monitoring for compliance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Threshold Sets the number of days before expiration to trigger a warning. Defaults to 30 days. Adjust this based on your certificate renewal process - use 90 days if you need longer lead times for procurement and testing. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 30 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Certificate objects with added properties Returns 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 meet the expiration criteria, nothing is returned. Displayed properties (via Select-DefaultView): ComputerName: The name of the computer where the certificate is stored Store: The certificate store location (LocalMachine, CurrentUser, etc.) Folder: The certificate folder within the store (My, Root, CA, etc.) Name: The friendly name of the certificate DnsNameList: Array of DNS names associated with the certificate (Subject Alternative Names) Thumbprint: The SHA-1 hash of the certificate used for identification NotBefore: DateTime when the certificate becomes valid (validity start date) NotAfter: DateTime when the certificate expires (validity end date) Subject: The certificate subject Distinguished Name (DN) Issuer: The certificate issuer Distinguished Name (DN) Algorithm: The signature algorithm used by the certificate (e.g., sha256RSA) ExpiredOrExpiring: Boolean value indicating the certificate is expired or expiring (always $true for returned objects) 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\") All standard X.509 certificate properties are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Test-DbaConnection",
    "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.",
    "category": "Utilities",
    "tags": [
      "connection"
    ],
    "verb": "Test",
    "popular": true,
    "url": "/Test-DbaConnection",
    "popularityRank": 29,
    "synopsis": "Validates SQL Server connectivity and gathers comprehensive connection diagnostics",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaConnection View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates SQL Server connectivity and gathers comprehensive connection diagnostics 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. Syntax Test-DbaConnection [[-SqlInstance] ] [[-Credential] ] [[-SqlCredential] ] [-SkipPSRemoting] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: ComputerName : SQL2016 InstanceName : MSSQLSERVER SqlInstance : sql2016 SqlVersion : 13.0.4001... PS C:\\> Test-DbaConnection SQL2016 ComputerName : SQL2016 InstanceName : MSSQLSERVER SqlInstance : sql2016 SqlVersion : 13.0.4001 ConnectingAsUser : BASE\\ctrlb ConnectSuccess : True AuthType : Windows Authentication AuthScheme : KERBEROS TcpPort : 1433 IPAddress : 10.2.1.5 NetBiosName : sql2016.base.local IsPingable : True PSRemotingAccessible : True DomainName : base.local LocalWindows : 10.0.15063.0 LocalPowerShell : 5.1.15063.502 LocalCLR : 4.0.30319.42000 LocalSMOVersion : 13.0.0.0 LocalDomainUser : True LocalRunAsAdmin : False LocalEdition : Desktop Test connection to SQL2016 and outputs information collected Example 2: ComputerName : SQL2017 InstanceName : MSSQLSERVER SqlInstance : sql2017 SqlVersion : 14.0.3356... PS C:\\> $winCred = Get-Credential sql2017\\Administrator PS C:\\> $sqlCred = Get-Credential sa PS C:\\> Test-DbaConnection SQL2017 -SqlCredential $sqlCred -Credential $winCred ComputerName : SQL2017 InstanceName : MSSQLSERVER SqlInstance : sql2017 SqlVersion : 14.0.3356 ConnectingAsUser : sa ConnectSuccess : True AuthType : SQL Authentication AuthScheme : SQL TcpPort : 50164 IPAddress : 10.10.10.15 NetBiosName : sql2017.company.local IsPingable : True PSRemotingAccessible : True DomainName : company.local LocalWindows : 10.0.15063.0 LocalPowerShell : 5.1.19041.610 LocalCLR : 4.0.30319.42000 LocalSMOVersion : 15.100.0.0 LocalDomainUser : True LocalRunAsAdmin : False LocalEdition : Desktop Test connection to SQL2017 instance and collecting information on SQL Server using the sa login, local Administrator account is used to collect port information Optional Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -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. Use this when your current Windows account lacks administrative privileges on the target server or when testing across domain boundaries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SkipPSRemoting Skips the PowerShell remoting connectivity test during the connection assessment. Use this when PSRemoting is disabled or blocked by firewall rules but you still want to test SQL connectivity and gather other diagnostic information. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance with comprehensive connection and environment diagnostics. Properties: ComputerName: The resolved computer name of the SQL Server instance InstanceName: The SQL Server instance name (MSSQLSERVER for default instance) SqlInstance: The full SMO instance name (computer\\instance format) SqlVersion: The SQL Server version number (e.g., 13.0.4001 for SQL Server 2016) ConnectingAsUser: The login name used to establish the SQL connection ConnectSuccess: Boolean indicating whether the SQL Server connection was successful AuthType: The type of authentication used (Windows Authentication or SQL Authentication) AuthScheme: The authentication scheme (KERBEROS, NTLM, SQL, etc.) or error if retrieval failed TcpPort: The TCP port number used by the SQL Server instance; contains error details if port detection failed IPAddress: The IP address of the target server NetBiosName: The fully qualified domain name (FQDN) of the server IsPingable: Boolean indicating whether the server responds to ICMP ping requests PSRemotingAccessible: Boolean indicating PSRemoting connectivity status; contains error details if test failed or skipped DomainName: The Active Directory domain name LocalWindows: The Windows OS version on the local machine where the command runs LocalPowerShell: The PowerShell version on the local machine LocalCLR: The CLR (Common Language Runtime) version on the local machine LocalSMOVersion: The SQL Server Management Objects (SMO) version on the local machine LocalDomainUser: Boolean indicating whether the local session is running as a domain user LocalRunAsAdmin: Boolean indicating whether the local session is running with administrator privileges LocalEdition: The PowerShell edition (Desktop or Core) &nbsp;"
  },
  {
    "name": "Test-DbaConnectionAuthScheme",
    "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.",
    "category": "Utilities",
    "tags": [
      "spn",
      "kerberos"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaConnectionAuthScheme",
    "popularityRank": 397,
    "synopsis": "Tests and reports authentication scheme and transport protocol details for SQL Server connections",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaConnectionAuthScheme View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests and reports authentication scheme and transport protocol details for SQL Server connections 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). This 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. When 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. Common scenarios include diagnosing SPN configuration problems, security auditing of connection protocols, and verifying that domain authentication is working as expected in your environment. Syntax Test-DbaConnectionAuthScheme [-SqlInstance] [[-SqlCredential] ] [-Kerberos] [-Ntlm] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns ConnectName, ServerName, Transport and AuthScheme for sqlserver2014a and sql2016 PS C:\\> Test-DbaConnectionAuthScheme -SqlInstance sqlserver2014a, sql2016 Example 2: Returns $true or $false depending on if the connection is Kerberos or not PS C:\\> Test-DbaConnectionAuthScheme -SqlInstance sqlserver2014a -Kerberos Example 3: Returns the results of &quot;SELECT from sys.dm_exec_connections WHERE session_id = @@SPID&quot; PS C:\\> Test-DbaConnectionAuthScheme -SqlInstance sqlserver2014a | Select-Object Required Parameters -SqlInstance The target SQL Server instance or instances. Server(s) must be SQL Server 2005 or higher. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | Credential,Cred | | Required | False | | Pipeline | false | | Default Value | | -Kerberos Returns $true if the connection uses Kerberos authentication, $false otherwise. Use this switch when you need to verify that domain authentication is working properly and not falling back to NTLM. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Ntlm Returns $true if the connection uses NTLM authentication, $false otherwise. Use this switch to confirm when connections are using NTLM instead of the preferred Kerberos authentication method. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Default output (no -Kerberos or -Ntlm switch): Returns one object per instance queried showing the current connection details from sys.dm_exec_connections. Default display properties: ComputerName: The computer name from SERVERPROPERTY InstanceName: The instance name from SERVERPROPERTY SqlInstance: The server name from SERVERPROPERTY Transport: Network transport type (TCP, Named Pipes, Shared Memory, etc.) AuthScheme: Authentication scheme used (Kerberos or NTLM) *Additional properties available (via Select-Object ): SessionId: Current session ID MostRecentSessionId: Most recent session ID ConnectTime: DateTime when the connection was established ProtocolType: Type of protocol used ProtocolVersion: Version of the protocol EndpointId: Endpoint identifier EncryptOption: Encryption option setting NodeAffinity: Node affinity setting NumReads: Number of read operations NumWrites: Number of write operations LastRead: DateTime of last read operation LastWrite: DateTime of last write operation PacketSize: Network packet size in bytes ClientNetworkAddress: Client network address ClientTcpPort: Client TCP port number ServerNetworkAddress: Server network address ServerTcpPort: Server TCP port number ConnectionId: Connection identifier ParentConnectionId: Parent connection identifier MostRecentSqlHandle: Most recent SQL handle With -Kerberos or -Ntlm switch: Returns a filtered object with these properties:** ComputerName: The computer name InstanceName: The instance name SqlInstance: The server instance name Result: Boolean indicating if the connection uses the specified authentication scheme ($true if using Kerberos or NTLM as specified, $false otherwise) &nbsp;"
  },
  {
    "name": "Test-DbaDbCollation",
    "description": "Compares each database's collation against the SQL Server instance's 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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "collation"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDbCollation",
    "popularityRank": 416,
    "synopsis": "Identifies databases with collations that differ from the SQL Server instance default collation",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaDbCollation View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies databases with collations that differ from the SQL Server instance default collation Description Compares each database's collation against the SQL Server instance's 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. Syntax Test-DbaDbCollation [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns server name, database name and true/false if the collations match for all databases on sqlserver2014a PS C:\\> Test-DbaDbCollation -SqlInstance sqlserver2014a Example 2: Returns information for the db1 and db2 databases on sqlserver2014a PS C:\\> Test-DbaDbCollation -SqlInstance sqlserver2014a -Database db1, db2 Example 3: Returns information for database and server collations for all databases except db1 on sqlserver2014a and... PS C:\\> Test-DbaDbCollation -SqlInstance sqlserver2014a, sql2016 -Exclude db1 Returns information for database and server collations for all databases except db1 on sqlserver2014a and sql2016. Example 4: Returns db/server collation information for every database on every server listed in the Central Management... PS C:\\> Get-DbaRegServer -SqlInstance sql2016 | Test-DbaDbCollation Returns db/server collation information for every database on every server listed in the Central Management Server on sql2016. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for collation mismatches against the server's default collation. Accepts wildcards for pattern matching. Use this when you need to focus collation testing on specific databases rather than scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to skip during collation testing. Useful for excluding system databases or databases you know have intentional collation differences. Common scenarios include skipping databases with different language requirements or legacy databases scheduled for decommission. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database on the specified instance(s) that matches the filter criteria. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database being tested ServerCollation: The default collation of the SQL Server instance DatabaseCollation: The collation setting of the database IsEqual: Boolean indicating if the database collation matches the server's default collation ($true if match, $false if different) &nbsp;"
  },
  {
    "name": "Test-DbaDbCompatibility",
    "description": "Compares each database's compatibility level against the SQL Server instance's 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.",
    "category": "Database Operations",
    "tags": [
      "database",
      "compatibility"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDbCompatibility",
    "popularityRank": 420,
    "synopsis": "Identifies databases running at lower compatibility levels than the SQL Server instance supports",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaDbCompatibility View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies databases running at lower compatibility levels than the SQL Server instance supports Description Compares each database's compatibility level against the SQL Server instance's 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. Syntax Test-DbaDbCompatibility [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns server name, database name and true/false if the compatibility level match for all databases on... PS C:\\> Test-DbaDbCompatibility -SqlInstance sqlserver2014a Returns server name, database name and true/false if the compatibility level match for all databases on sqlserver2014a. Example 2: Returns detailed information for database and server compatibility level for the db1 and db2 databases on... PS C:\\> Test-DbaDbCompatibility -SqlInstance sqlserver2014a -Database db1, db2 Returns detailed information for database and server compatibility level for the db1 and db2 databases on sqlserver2014a. Example 3: Returns detailed information for database and server compatibility level for all databases except db1 on... PS C:\\> Test-DbaDbCompatibility -SqlInstance sqlserver2014a, sql2016 -Exclude db1 Returns detailed information for database and server compatibility level for all databases except db1 on sqlserver2014a and sql2016. Example 4: Returns db/server compatibility information for every database on every server listed in the Central... PS C:\\> Get-DbaRegServer -SqlInstance sql2014 | Test-DbaDbCompatibility Returns db/server compatibility information for every database on every server listed in the Central Management Server on sql2016. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to test for compatibility level mismatches. Accepts database names, wildcards, or arrays. Use this when you need to check specific databases instead of testing all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to skip during compatibility level testing. Accepts database names, wildcards, or arrays. Use this to exclude system databases, maintenance databases, or any databases you don't want included in the results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ServerLevel: The SQL Server instance's compatibility level (CompatibilityLevel enum value like Version140, Version150, etc.) Database: The name of the database being evaluated DatabaseCompatibility: The database's current compatibility level (CompatibilityLevel enum value) IsEqual: Boolean indicating whether the database compatibility level matches the server's maximum compatibility level &nbsp;"
  },
  {
    "name": "Test-DbaDbCompression",
    "description": "Performs comprehensive compression analysis on user tables and indexes to help DBAs identify storage optimization opportunities. Uses SQL Server's 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: 'PAGE', 'ROW', 'NO_GAIN' or '?' 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's 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.",
    "category": "Utilities",
    "tags": [
      "compression",
      "table"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDbCompression",
    "popularityRank": 323,
    "synopsis": "Analyzes user tables and indexes to recommend optimal compression settings for storage space reduction.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaDbCompression View Source Jason Squires (@js_0505), jstexasdba@gmail.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Analyzes user tables and indexes to recommend optimal compression settings for storage space reduction. Description Performs comprehensive compression analysis on user tables and indexes to help DBAs identify storage optimization opportunities. Uses SQL Server's sp_estimate_data_compression_savings system procedure combined with workload pattern analysis to recommend the most effective compression type for each object. This 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. The analysis examines operational statistics from sys.dm_db_index_operational_stats to determine usage patterns: Percent_Update shows the percentage of update operations relative to total operations. Lower update percentages indicate better candidates for page compression. Percent_Scan shows the percentage of scan operations relative to total operations. Higher scan percentages indicate better candidates for page compression. Compression_Type_Recommendation provides specific guidance: 'PAGE', 'ROW', 'NO_GAIN' or '?' when the algorithm cannot determine the best option. The 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. Test-DbaDbCompression script derived from GitHub and the Tiger Team's repository: (https://github.com/Microsoft/tigertoolbox/tree/master/Evaluate-Compression-Gains) Be 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. Syntax Test-DbaDbCompression [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Schema] ] [[-Table] ] [[-ResultSize] ] [[-Rank] ] [[-FilterBy] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns results of all potential compression options for all databases for the default instance on the local... PS C:\\> Test-DbaDbCompression -SqlInstance localhost Returns 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 Example 2: Returns results of all potential compression options for all databases on the instance ServerA PS C:\\> Test-DbaDbCompression -SqlInstance ServerA Example 3: Returns results of all potential compression options for a single database DBName with the recommendation of... PS C:\\> Test-DbaDbCompression -SqlInstance ServerA -Database DBName | Out-GridView Returns 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 Example 4: Returns results of all potential compression options for all databases except MyDatabase on instance ServerA... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Test-DbaDbCompression -SqlInstance ServerA -ExcludeDatabase MyDatabase -SqlCredential $cred Returns results of all potential compression options for all databases except MyDatabase on instance ServerA using SQL credentials to authentication to ServerA. Returns the recommendation of either Page, Row or NO_GAIN Example 5: Returns results of all potential compression options for the Table Test.MyTable in instance ServerA on... PS C:\\> Test-DbaDbCompression -SqlInstance ServerA -Schema Test -Table MyTable Returns results of all potential compression options for the Table Test.MyTable in instance ServerA on ServerA and ServerB. Returns the recommendation of either Page, Row or NO_GAIN. Returns a result for each partition of any Heap, Clustered or NonClustered index. Example 6: Returns results of all potential compression options for all databases on ServerA and ServerB PS C:\\> Test-DbaDbCompression -SqlInstance ServerA, ServerB -ResultSize 10 Returns results of all potential compression options for all databases on ServerA and ServerB. Returns the recommendation of either Page, Row or NO_GAIN. Returns results for the top 10 partitions by TotalPages used per database. Example 7: Returns results of all potential compression options for all databases on ServerA containing a schema Test... PS C:\\> ServerA | Test-DbaDbCompression -Schema Test -ResultSize 10 -Rank UsedPages -FilterBy Table Returns results of all potential compression options for all databases on ServerA containing a schema Test Returns results for the top 10 Tables by Used Pages per database. Results are split by Table, Index and Partition so more than 10 results may be returned. Example 8: Returns results of all potential compression options for a single database DBName on Server1 or Server2... PS C:\\> $servers = 'Server1','Server2' PS C:\\> $servers | Test-DbaDbCompression -Database DBName | Out-GridView Returns results of all potential compression options for a single database DBName on Server1 or Server2 Returns the recommendation of either Page, Row or NO_GAIN in a nicely formatted GridView Example 9: Returns results of all potential compression options for objects in Database MyDb on instance ServerA using... PS C:\\> $cred = Get-Credential sqladmin PS C:\\> Test-DbaDbCompression -SqlInstance ServerA -Database MyDB -SqlCredential $cred -Schema Test -Table Test1, Test2 Returns results of all potential compression options for objects in Database MyDb on instance ServerA using SQL credentials to authentication to ServerA. Returns the recommendation of either Page, Row or NO_GAIN for tables with Schema Test and name in Test1 or Test2 Example 10: This produces a full analysis of all your servers listed and is pushed to a csv for you to analyze PS C:\\> $servers = 'Server1','Server2' PS C:\\> foreach ($svr in $servers) { >> Test-DbaDbCompression -SqlInstance $svr | Export-Csv -Path C:\\temp\\CompressionAnalysisPAC.csv -Append >> } Required Parameters -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. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to analyze for compression opportunities. Accepts multiple database names and supports wildcards. Use this to focus analysis on specific databases rather than scanning all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during compression analysis. Helpful when you want to analyze most databases but exclude specific ones. Commonly used to skip databases that are already compressed, read-only, or contain sensitive data requiring separate analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Filters analysis to specific database schemas only. Accepts multiple schema names for targeted analysis. Use this when you need compression recommendations for tables in specific schemas like 'dbo', 'sales', or custom application schemas. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Filters analysis to specific table names only. Accepts multiple table names for focused compression analysis. Use this when investigating compression opportunities for known large tables or when validating compression recommendations for specific objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ResultSize Limits the number of objects analyzed per database to control analysis scope and execution time. No limit applied when unspecified. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Rank Determines how objects are prioritized when ResultSize limits are applied. Options are TotalPages (default), UsedPages, or TotalRows. TotalPages focuses on allocated storage, UsedPages targets actual data consumption, and TotalRows prioritizes by record count for different optimization strategies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | TotalPages | | Accepted Values | TotalPages,UsedPages,TotalRows | -FilterBy Sets the granularity level for ResultSize filtering. Options are Partition (default), Index, or Table level filtering. Partition level provides most detailed analysis per partition, Index level groups by index, and Table level gives broader table-focused results. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | Partition | | Accepted Values | Partition,Index,Table | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per table/index/partition analyzed (depending on -FilterBy parameter), providing compression analysis recommendations and estimated space savings. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: Name of the database analyzed Schema: Name of the schema containing the table TableName: Name of the table being analyzed IndexName: Name of the index; null for heap analysis or when FilterBy is 'Table' Partition: Partition number; 0 when FilterBy is 'Table' or 'Index', otherwise partition number IndexID: Index ID number; 0 when FilterBy is 'Table', internal SQL Server index ID for other FilterBy values IndexType: Type of index structure (Heap, ClusteredIndex, NonClusteredIndex, etc.) PercentScan: Percentage of operations that are scans (0-100); higher values indicate PAGE compression suitability PercentUpdate: Percentage of operations that are updates (0-100); higher values indicate ROW compression suitability RowEstimatePercentOriginal: Estimated size with ROW compression as percentage of original size PageEstimatePercentOriginal: Estimated size with PAGE compression as percentage of original size CompressionTypeRecommendation: Recommended compression type (ROW, PAGE, NO_GAIN, or ? when undetermined) SizeCurrent: Current size in bytes; dbasize object (displays as B, KB, MB, GB, or TB) SizeRequested: Estimated size after applying recommended compression type PercentCompression: Percentage of space savings with recommended compression (0-100 range) Granularity and filtering controlled by parameters: When -FilterBy is 'Partition' (default): One object per partition per index When -FilterBy is 'Index': One object per index grouped across partitions When -FilterBy is 'Table': One object per table grouped across all indexes and partitions When -ResultSize is specified: Only top N objects by -Rank (TotalPages, UsedPages, or TotalRows) are returned per database &nbsp;"
  },
  {
    "name": "Test-DbaDbDataGeneratorConfig",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "datageneration"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDbDataGeneratorConfig",
    "popularityRank": 590,
    "synopsis": "Validates JSON configuration files used for generating realistic test data in SQL Server databases",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaDbDataGeneratorConfig View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates JSON configuration files used for generating realistic test data in SQL Server databases 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. This 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. Syntax Test-DbaDbDataGeneratorConfig [-FilePath] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Test the configuration file PS C:\\> Test-DbaDbDataGeneratorConfig -FilePath C:\\temp\\_datamasking\\db1.json Required Parameters -FilePath Specifies the path to the JSON configuration file created by New-DbaDbDataGeneratorConfig that needs validation. Use this to verify your data generation configuration before running Invoke-DbaDbDataGenerator to avoid runtime errors. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns validation error objects for any configuration issues found. If the configuration file is valid with no errors, no output is returned. Each error object contains the following properties: Table (string): Name of the table in the configuration where the error was found Column (string): Name of the column in the table where the error was found Value (string): The problematic value or comma-separated list of property names causing the error Error (string): Description of the validation error encountered Common validation errors include: Missing required column properties (CharacterString, ColumnType, Composite, ForeignKey, Identity, MaskingType, MaxValue, MinValue, Name, Nullable, SubType) Additional properties in columns that are not in the required properties list Invalid column data types (unsupported by SQL Server or the Bogus data generation library) Invalid masking types (not available in the Bogus randomization library) Invalid masking subtypes (not available for the specified masking type) The validation errors help identify configuration issues before attempting to generate test data with Invoke-DbaDbDataGenerator, preventing runtime failures. &nbsp;"
  },
  {
    "name": "Test-DbaDbDataMaskingConfig",
    "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'll execute successfully without runtime errors.",
    "category": "Data Operations",
    "tags": [
      "masking",
      "datamasking"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDbDataMaskingConfig",
    "popularityRank": 472,
    "synopsis": "Validates data masking configuration JSON files for structural and logical errors",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaDbDataMaskingConfig View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates data masking configuration JSON files for structural and logical errors Description Validates data masking configuration JSON files by checking column properties, data types, masking types, and action configurations against dbatools requirements. Returns detailed error information for any tables and columns that fail validation, helping you identify configuration issues before running data masking operations. Checks include required/allowed column properties, supported SQL Server data types, valid masking and subtype combinations, date range validations, and action property requirements. Essential for troubleshooting complex masking configurations and ensuring they'll execute successfully without runtime errors. Syntax Test-DbaDbDataMaskingConfig [-FilePath] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Test the configuration file PS C:\\> Test-DbaDbDataMaskingConfig -FilePath C:\\temp\\_datamasking\\db1.json Required Parameters -FilePath Specifies the full path to the data masking configuration JSON file to validate. Use this to verify your masking configuration before running New-DbaDbDataMaskingConfig or Invoke-DbaDbDataMasking to catch errors early. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns validation error objects for any configuration issues found. If the configuration file is valid with no errors, no output is returned. Each error object contains the following properties: Table (string): Name of the table in the configuration where the error was found Column (string): Name of the column in the table where the error was found Value (string): The problematic value or comma-separated list of property names causing the error Error (string): Description of the validation error encountered Common validation errors include: Missing required column properties (Action, CharacterString, ColumnType, Composite, Deterministic, Format, MaskingType, MaxValue, MinValue, Name, Nullable, KeepNull, SubType) Invalid column data types (unsupported by SQL Server or dbatools) Invalid masking types or subtypes (not available in dbatools randomization library) Unsupported action categories, types, or subcategories Invalid date range values or missing required min/max values for 'Between' subtype Missing required action properties (Category, Type, Value for datetime actions; Category, Type, Value for number actions) Action category incompatibility with column data type Additional properties in columns that are not in the allowed properties list &nbsp;"
  },
  {
    "name": "Test-DbaDbLogShipStatus",
    "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're 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'll see \"All OK\" in the status output.\nProblem databases will show detailed messages about which operations are behind schedule or failing entirely.",
    "category": "Utilities",
    "tags": [
      "logshipping"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDbLogShipStatus",
    "popularityRank": 234,
    "synopsis": "Retrieves log shipping status and health information from the monitoring instance",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaDbLogShipStatus View Source Sander Stad (@sqlstad), sqlstad.nl Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Retrieves log shipping status and health information from the monitoring instance Description Queries the log shipping monitoring system to check the health of your log shipping configuration across primary and secondary instances. This function connects to your log shipping monitoring instance and examines backup, copy, and restore operations to identify any issues or delays. Make sure you're connecting to the monitoring instance of your log shipping infrastructure, as this is where SQL Server stores the consolidated monitoring data. The function analyzes timing thresholds for each operation and reports specific problems like missed backups, copy delays, or restore failures. When everything is functioning normally, you'll see \"All OK\" in the status output. Problem databases will show detailed messages about which operations are behind schedule or failing entirely. Syntax Test-DbaDbLogShipStatus [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-Simple] [-Primary] [-Secondary] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Retrieves the log ship information from sql1 and displays all the information present including the status PS C:\\> Test-DbaDbLogShipStatus -SqlInstance sql1 Example 2: Retrieves the log ship information for just the database AdventureWorks PS C:\\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Database AdventureWorks2014 Example 3: Retrieves the log ship information and only returns the information for the databases on the primary instance PS C:\\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Primary Example 4: Retrieves the log ship information and only returns the information for the databases on the secondary... PS C:\\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Secondary Retrieves the log ship information and only returns the information for the databases on the secondary instance. Example 5: Retrieves the log ship information and only returns the columns SQL Instance, Database, Instance Type and... PS C:\\> Test-DbaDbLogShipStatus -SqlInstance sql1 -Simple Retrieves the log ship information and only returns the columns SQL Instance, Database, Instance Type and Status Required Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2000 or greater. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which log shipped databases to check by exact name. Accepts multiple database names as a comma-separated list. Use this when you want to focus on specific databases instead of checking all log shipped databases on the monitoring instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific log shipped databases from the status check by exact name. Accepts multiple database names as a comma-separated list. Use this when you want to check most databases but skip certain ones, such as test or development log shipping configurations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Simple Returns only essential columns: SqlInstance, Database, InstanceType, and Status instead of all detailed timing information. Use this for quick health overviews when you don't need the full backup/copy/restore timing details. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Primary Returns only status information for databases acting as primary instances in log shipping configurations. Use this when you want to focus specifically on backup operations and primary-side health monitoring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Secondary Returns only status information for databases acting as secondary instances in log shipping configurations. Use this when you want to focus specifically on copy and restore operations and secondary-side health monitoring. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per log-shipped database configured on the monitoring instance. Output structure varies based on the -Simple parameter. Default output (without -Simple) includes all properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the log-shipped database InstanceType: The role of the instance - either \"Primary Instance\" (backup/copy operations) or \"Secondary Instance\" (restore operations) TimeSinceLastBackup: DateTime of the most recent backup operation (or \"N/A\" if never executed) LastBackupFile: The name of the file involved in the last backup operation BackupThreshold: The configured threshold in minutes for maximum acceptable time between backups IsBackupAlertEnabled: Boolean indicating whether alerting is enabled for backup operation failures TimeSinceLastCopy: DateTime of the most recent copy operation (or \"N/A\" if never executed); only relevant on secondary instances LastCopiedFile: The name of the file involved in the last copy operation TimeSinceLastRestore: DateTime of the most recent restore operation (or \"N/A\" if never executed); only relevant on secondary instances LastRestoredFile: The name of the file involved in the last restore operation LastRestoredLatency: The delay in seconds between the backup and restore operations (latency between primary and secondary) RestoreThreshold: The configured threshold in minutes for maximum acceptable time between restore operations IsRestoreAlertEnabled: Boolean indicating whether alerting is enabled for restore operation failures 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\") When -Simple is specified: Only four properties are returned: SqlInstance, Database, InstanceType, and Status This provides a quick health overview without detailed timing information When -Primary is specified: Only databases acting as primary instances are returned; backup-related properties are populated Copy and restore properties may be empty or N/A since those operations occur on secondaries When -Secondary is specified: Only databases acting as secondary instances are returned; copy and restore properties are populated Backup properties may be empty or N/A since backup operations occur on primaries &nbsp;"
  },
  {
    "name": "Test-DbaDbOwner",
    "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 'sa' (or the renamed sysadmin account if 'sa' 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 'sa' 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",
    "category": "Database Operations",
    "tags": [
      "database",
      "owner",
      "dbowner"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDbOwner",
    "popularityRank": 250,
    "synopsis": "Identifies databases with incorrect ownership for security compliance and best practice enforcement.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaDbOwner View Source Michael Fal (@Mike_Fal), mikefal.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies databases with incorrect ownership for security compliance and best practice enforcement. 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 'sa' (or the renamed sysadmin account if 'sa' was changed), but you can specify any valid login. This 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. The function automatically detects if the 'sa' 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. Best Practice reference: http://weblogs.sqlteam.com/dang/archive/2008/01/13/Database-Owner-Troubles.aspx Syntax Test-DbaDbOwner [[-SqlInstance] ] [-SqlCredential ] [-Database ] [-ExcludeDatabase ] [-TargetLogin ] [-InputObject ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns all databases where the owner does not match &#39;sa&#39; PS C:\\> Test-DbaDbOwner -SqlInstance localhost Example 2: Returns all databases where the owner does not match &#39;DOMAIN\\account&#39; PS C:\\> Test-DbaDbOwner -SqlInstance localhost -TargetLogin 'DOMAIN\\account' Example 3: Gets only accessible databases and checks where the owner does not match &#39;sa&#39; PS C:\\> Get-DbaDatabase -SqlInstance localhost -OnlyAccessible | Test-DbaDbOwner Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to check for ownership compliance. Accepts wildcards for pattern matching. Use this when you need to audit ownership for specific databases rather than all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during the ownership compliance check. Accepts wildcards for pattern matching. Useful for excluding system databases or databases with intentionally different ownership from standard policy. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TargetLogin Specifies the expected database owner login for compliance checking. Defaults to 'sa' or the renamed sysadmin account if 'sa' was changed. Use this to enforce organizational standards where databases should be owned by a service account or specific login rather than individual users. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase for ownership verification. Use this to check ownership on a pre-filtered set of databases or when chaining with other database operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database that does not match the target owner. Each object contains the following properties: Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Database: The name of the database being checked DBState: The current database state (Online, Offline, Restoring, etc.) CurrentOwner: The login name of the current database owner TargetOwner: The login name of the expected database owner (the compliance target) OwnerMatch: Boolean indicating whether the current owner matches the target owner (False for all returned objects, since only non-matching databases are returned) &nbsp;"
  },
  {
    "name": "Test-DbaDbQueryStore",
    "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",
    "category": "Database Operations",
    "tags": [
      "database",
      "querystore"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDbQueryStore",
    "popularityRank": 359,
    "synopsis": "Compares Query Store settings against best practices.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaDbQueryStore View Source Jess Pomfret (@jpomfret), jesspomfret.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Compares Query Store settings against best practices. Description Evaluates Query Store against a set of rules to match best practices. The rules are: ActualState = ReadWrite (This means Query Store is enabled and collecting data.) DataFlushIntervalInSeconds = 900 (Recommended to leave this at the default of 900 seconds (15 mins).) MaxPlansPerQuery = 200 (Number of distinct plans per query. 200 is a good starting point for most environments.) MaxStorageSizeInMB = 2048 (How much disk space Query Store will use. 2GB is a good starting point.) QueryCaptureMode = Auto (With auto, queries that are insignificant from a resource utilization perspective, or executed infrequently, are not captured.) SizeBasedCleanupMode = Auto (With auto, as Query Store gets close to out of space it will automatically purge older data.) StaleQueryThresholdInDays = 30 (Determines how much historic data to keep. 30 days is a good value here.) StatisticsCollectionIntervalInMinutes = 30 (Time window that runtime stats will be aggregated. Use 30 unless you have space concerns, then leave at the default (60).) WaitStatsCaptureMode = ON (Adds valuable data when troubleshooting.) Trace Flag 7745 enabled Trace Flag 7752 enabled Syntax Test-DbaDbQueryStore [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Checks that Query Store is enabled and meets best practices for all user databases on the localhost machine PS C:\\> Test-DbaDbQueryStore -SqlInstance localhost Example 2: Checks that Query Store is enabled and meets best practices for the AdventureWorks2017 database on the... PS C:\\> Test-DbaDbQueryStore -SqlInstance localhost -Database AdventureWorks2017 Checks that Query Store is enabled and meets best practices for the AdventureWorks2017 database on the localhost machine. Example 3: Checks that Query Store is enabled and meets best practices for all user databases except AdventureWorks2017... PS C:\\> Test-DbaDbQueryStore -SqlInstance localhost -ExcludeDatabase AdventureWorks2017 Checks that Query Store is enabled and meets best practices for all user databases except AdventureWorks2017 on the localhost machine. Example 4: Checks that Query Store is enabled and meets best practices for all databases that are piped on the localhost... PS C:\\> $databases = Get-DbaDatabase -SqlInstance localhost PS C:\\> $databases | Test-DbaDbQueryStore Checks that Query Store is enabled and meets best practices for all databases that are piped on the localhost machine. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to test for Query Store best practices. Accepts wildcards for pattern matching. Use this when you need to evaluate Query Store settings for specific databases instead of all user databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Excludes specific databases from Query Store evaluation. System databases (master, model, tempdb) are automatically excluded. Use this when you want to test most databases but skip certain ones like development or temporary databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects piped from Get-DbaDatabase, server objects, or instance parameters for testing. Use this when you want to test Query Store settings on a pre-filtered set of databases or work within a pipeline workflow. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per Query Store configuration property per database, plus one object per enabled trace flag per instance (on non-Azure servers only). Query Store Configuration Properties (returned for each evaluated database): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database being evaluated Name: The configuration property name (e.g., ActualState, MaxStorageSizeInMB, StaleQueryThresholdInDays) Value: The current value of the configuration property RecommendedValue: The recommended value for this property based on best practices IsBestPractice: Boolean indicating if the current value matches the recommended value (true = best practice compliant) Justification: Explanation of why the recommended value is best practice Trace Flag Status (returned only on SQL Server instances that are not Azure SQL Database): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name Name: The trace flag name (e.g., \"Trace Flag 7745 Enabled\", \"Trace Flag 7752 Enabled\") Value: The status of the trace flag (Enabled or Disabled) RecommendedValue: The trace flag number (7745 or 7752) IsBestPractice: Boolean indicating if the trace flag is enabled as recommended Justification: Explanation of why the trace flag should be enabled Output 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). &nbsp;"
  },
  {
    "name": "Test-DbaDbRecoveryModel",
    "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's post (http://www.sqlskills.com/blogs/paul/new-script-is-that-database-really-in-the-full-recovery-mode/)",
    "category": "Backup & Restore",
    "tags": [
      "disasterrecovery",
      "backup"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDbRecoveryModel",
    "popularityRank": 438,
    "synopsis": "Validates whether databases are truly operating in their configured recovery model",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaDbRecoveryModel View Source Claudio Silva (@ClaudioESSilva) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates whether databases are truly operating in their configured 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. For 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. This 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. Inspired by Paul Randal's post (http://www.sqlskills.com/blogs/paul/new-script-is-that-database-really-in-the-full-recovery-mode/) Syntax Test-DbaDbRecoveryModel [-SqlInstance] [[-Database] ] [[-ExcludeDatabase] ] [[-SqlCredential] ] [[-RecoveryModel] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Shows all databases where the configured recovery model is FULL and indicates whether or not they are really... PS C:\\> Test-DbaDbRecoveryModel -SqlInstance sql2005 Shows all databases where the configured recovery model is FULL and indicates whether or not they are really in FULL recovery model. Example 2: Only shows the databases that are functionally in &#39;simple&#39; mode PS C:\\> Test-DbaDbRecoveryModel -SqlInstance . | Where-Object {$_.ActualRecoveryModel -ne \"FULL\"} Example 3: Shows all databases where the configured recovery model is BULK_LOGGED and sort them by server name descending PS C:\\> Test-DbaDbRecoveryModel -SqlInstance sql2008 -RecoveryModel Bulk_Logged | Sort-Object Server -Descending Example 4: Shows all of the properties for the databases that have Full Recovery Model PS C:\\> Test-DbaDbRecoveryModel -SqlInstance localhost | Select-Object -Property * Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Database Specifies which databases to test for recovery model validation. Accepts multiple database names and supports wildcards. When specified, only these databases will be evaluated instead of all databases on the instance. Useful when you need to verify recovery model behavior for specific databases or troubleshoot particular applications. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to skip during recovery model validation. Accepts multiple database names and supports wildcards. Use this to exclude system databases, test databases, or databases you know are properly configured when testing large instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -RecoveryModel Specifies which recovery model to validate against configured settings. Valid values are Full, Simple, or Bulk_Logged. Defaults to Full recovery model, which also checks if databases have established a log backup chain for true point-in-time recovery. Use Simple or Bulk_Logged when auditing databases that should be configured for those specific recovery models. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | | Accepted Values | 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. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database evaluated, providing recovery model configuration and current operational status comparison. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The name of the database being validated ConfiguredRecoveryModel: The recovery model configured on the database (FULL, SIMPLE, or BULK_LOGGED) ActualRecoveryModel: The actual operational recovery model (may differ from configured; FULL databases without a log backup chain report as SIMPLE) For 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 models report their configured value as the actual value. &nbsp;"
  },
  {
    "name": "Test-DbaDiskAlignment",
    "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's 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.",
    "category": "Utilities",
    "tags": [
      "storage",
      "disk",
      "os"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDiskAlignment",
    "popularityRank": 287,
    "synopsis": "Tests disk partition alignment to identify I/O performance issues that can impact SQL Server.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaDiskAlignment View Source Constantine Kokkinos (@mobileck), constantinekokkinos.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests disk partition alignment to identify I/O performance issues that can impact SQL Server. 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. The function connects to Windows computers via CIM and examines each disk partition's 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. Returns detailed alignment analysis including partition size, offset calculations, and recommendations. This helps identify storage configuration issues before they impact database performance. Please refer to your storage vendor best practices before following any advice below. By 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. While 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 ) Caveats: 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. 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. 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. Syntax Test-DbaDiskAlignment [-ComputerName] [[-Credential] ] [[-SqlCredential] ] [-NoSqlCheck] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Tests the disk alignment of a single server named sqlserver2014a PS C:\\> Test-DbaDiskAlignment -ComputerName sqlserver2014a Example 2: Tests the disk alignment of multiple servers PS C:\\> Test-DbaDiskAlignment -ComputerName sqlserver2014a, sqlserver2014b, sqlserver2014c Required Parameters -ComputerName Specifies the Windows computer(s) to test for disk partition alignment issues. Accepts multiple server names for batch processing. Use this to identify storage configuration problems that could impact SQL Server I/O performance across your environment. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Specifies an alternate Windows account to use when enumerating drives on the server. May require Administrator privileges. To use: $cred = Get-Credential, then pass $cred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -NoSqlCheck Tests alignment on all disk partitions instead of limiting the check to only those containing SQL Server data or log files. Use this when you want a comprehensive disk alignment assessment for the entire server, not just SQL Server storage. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns multiple objects per partition (one object per stripe unit tested) for each disk partition on the target server(s). Properties: ComputerName: Computer name of the target server Name: Partition name or drive letter (e.g., \"C:\", \"D:\") PartitionSize: Total size of the partition in bytes (DbaSize object providing automatic unit conversion) PartitionType: Type of partition (e.g., \"Basic\", \"Logical Disk Manager\" for dynamic disks) TestingStripeSize: Stripe unit size being tested in this result (64KB, 128KB, 256KB, 512KB, or 1024KB; DbaSize object) OffsetModuluCalculation: Result of (partition offset modulo stripe size) for alignment verification (DbaSize object) StartingOffset: Partition starting offset in bytes (DbaSize object; best practice is 1MB/1048576 bytes) IsOffsetBestPractice: Boolean indicating if the offset matches a best practice value (64, 128, 256, 512, or 1024 KB) IsBestPractice: Boolean indicating if this partition aligns with the tested stripe size (offset % stripe size == 0) NumberOfBlocks: Number of blocks in the partition (from Win32_DiskPartition) BootPartition: Boolean indicating if this is the system boot partition PartitionBlockSize: Block size of the partition in bytes IsDynamicDisk: Boolean indicating if disk is managed by Windows Logical Disk Manager; results may be unreliable for dynamic disks Note: 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. The IsBestPractice property will be true for each stripe size that the partition aligns with. &nbsp;"
  },
  {
    "name": "Test-DbaDiskAllocation",
    "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't 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.\"",
    "category": "Utilities",
    "tags": [
      "storage",
      "disk",
      "os"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDiskAllocation",
    "popularityRank": 237,
    "synopsis": "Validates disk allocation unit sizes against SQL Server best practice recommendations.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaDiskAllocation View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates disk allocation unit sizes against SQL Server best practice recommendations. 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. The 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't require the 64KB allocation unit size. This validation is essential during SQL Server deployment planning and storage configuration audits, as improper allocation unit sizes can significantly impact database I/O performance. References: https://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.\" Syntax Test-DbaDiskAllocation [-ComputerName] [-NoSqlCheck] [[-SqlCredential] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Scans all disks on server sqlserver2014a for best practice allocation unit size PS C:\\> Test-DbaDiskAllocation -ComputerName sqlserver2014a Example 2: Scans all disks on server sqlserver2014a for allocation unit size and returns detailed results for each PS C:\\> Test-DbaDiskAllocation -ComputerName sqlserver2014 | Select-Output * Example 3: Scans all disks not hosting SQL Server data or log files on server sqlserver2014a for best practice... PS C:\\> Test-DbaDiskAllocation -ComputerName sqlserver2014a -NoSqlCheck Scans all disks not hosting SQL Server data or log files on server sqlserver2014a for best practice allocation unit size. Required Parameters -ComputerName Specifies the target server(s) to examine for disk allocation unit compliance. Accepts multiple server names for bulk validation. Use this to verify storage configuration across your SQL Server environment during deployment or storage audits. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -NoSqlCheck Skips detection of SQL Server database files and examines all NTFS volumes regardless of their SQL Server usage. Use this when you want to validate allocation units on all drives, not just those containing SQL Server data or log files. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Specifies an alternate Windows account to use when enumerating drives on the server. May require Administrator privileges. To use: $cred = Get-Credential, then pass $cred object to the -Credential parameter. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per NTFS volume found on the target server. Default properties (when -NoSqlCheck is not specified): Server: Computer name of the target server Name: Drive letter or volume name (e.g., \"C:\", \"D:\") Label: Volume label or name assigned to the drive BlockSize: Allocation unit size in bytes (65536 = 64KB is best practice) IsSqlDisk: Boolean indicating if the volume contains SQL Server database or log files IsBestPractice: Boolean indicating if BlockSize equals 65536 (64KB) - false for system drives When -NoSqlCheck is specified, the IsSqlDisk property is omitted: Server: Computer name of the target server Name: Drive letter or volume name Label: Volume label BlockSize: Allocation unit size in bytes IsBestPractice: Boolean indicating if BlockSize equals 65536 (64KB) &nbsp;"
  },
  {
    "name": "Test-DbaDiskSpeed",
    "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.",
    "category": "Utilities",
    "tags": [
      "diagnostic",
      "performance"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaDiskSpeed",
    "popularityRank": 151,
    "synopsis": "Analyzes database file I/O performance and identifies storage bottlenecks using SQL Server DMV statistics",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaDiskSpeed View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Analyzes database file I/O performance and identifies storage bottlenecks using SQL Server DMV statistics 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. Syntax Test-DbaDiskSpeed [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-AggregateBy] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Tests how disks are performing on sql2008 and sqlserver2012 PS C:\\> Test-DbaDiskSpeed -SqlInstance sql2008, sqlserver2012 Example 2: Tests how disks storing tempdb files on sql2008 are performing PS C:\\> Test-DbaDiskSpeed -SqlInstance sql2008 -Database tempdb Example 3: Returns the statistics aggregated to the file level PS C:\\> Test-DbaDiskSpeed -SqlInstance sql2008 -AggregateBy \"File\" -Database tempdb Returns 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 specific databases. Example 4: Returns the statistics aggregated to the database/disk level PS C:\\> Test-DbaDiskSpeed -SqlInstance sql2008 -AggregateBy \"Database\" Returns the statistics aggregated to the database/disk level. The -Database or -ExcludeDatabase params can be used to filter for specific databases. Example 5: Returns the statistics aggregated to the disk level PS C:\\> Test-DbaDiskSpeed -SqlInstance sql2008 -AggregateBy \"Disk\" Returns the statistics aggregated to the disk level. The -Database or -ExcludeDatabase params can be used to filter for specific databases. Example 6: Returns the statistics for instance1 and instance2 as part of a pipeline command PS C:\\> $results = @(instance1, instance2) | Test-DbaDiskSpeed Example 7: $results = Test-DbaDiskSpeed -SqlInstance sql2019 -Database $databases Returns the statistics for more than... PS C:\\> $databases = @('master', 'model') $results = Test-DbaDiskSpeed -SqlInstance sql2019 -Database $databases Returns the statistics for more than one database specified. Example 8: $results = Test-DbaDiskSpeed -SqlInstance sql2019 -ExcludeDatabase $excludedDatabases Returns the statistics... PS C:\\> $excludedDatabases = @('master', 'model') $results = Test-DbaDiskSpeed -SqlInstance sql2019 -ExcludeDatabase $excludedDatabases Returns the statistics for databases other than the exclusions specified. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to include in the I/O performance analysis. Accepts database names as strings or arrays. Use this when you need to focus on specific databases instead of analyzing all databases on the instance. Commonly used to isolate performance issues in production databases or exclude system databases from analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies which databases to exclude from the I/O performance analysis. Accepts database names as strings or arrays. Use this when you want to analyze most databases but skip specific ones like development databases or those with known issues. Helpful for excluding system databases (master, model, msdb) when focusing on user database performance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -AggregateBy Controls how I/O statistics are grouped and summarized in the results. Options are 'File' (default), 'Database', or 'Disk'. Use 'File' for detailed analysis of individual data and log files, 'Database' to compare performance across databases, or 'Disk' to identify storage-level bottlenecks. File-level analysis helps pinpoint specific problematic files, while disk-level aggregation is useful for storage capacity planning and identifying hardware issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | File | | Accepted Values | Database,Disk,File | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns I/O performance statistics aggregated at the file, database, or disk level based on the -AggregateBy parameter. Properties vary by aggregation level. Default properties (all aggregation levels): ComputerName: The computer name InstanceName: The SQL Server instance name SqlInstance: The full SQL instance name (computer\\instance) Reads: Number of read operations (summed across files at database/disk level) AverageReadStall: Average read latency in milliseconds ReadPerformance: Performance rating based on read latency - \"Very Good\" ( = 50ms) Writes: Number of write operations (summed across files at database/disk level) AverageWriteStall: Average write latency in milliseconds WritePerformance: Performance rating based on write latency - \"Very Good\", \"OK\", \"Slow, Needs Attention\", or \"Serious I/O Bottleneck\" Avg Overall Latency: Average combined read/write latency in milliseconds Avg Bytes/Read: Average bytes per read operation Avg Bytes/Write: Average bytes per write operation Avg Bytes/Transfer: Average bytes per I/O transfer operation Additional properties by aggregation level: When -AggregateBy 'File' (default): Database: Database name SizeGB: File size in gigabytes FileName: File name (Windows: letter+name like \"C:\\...\\file.mdf\", Linux: full path) FileID: File ID within the database FileType: Type of file - \"Log\" for transaction log, \"Data\" for data files When -AggregateBy 'Database': Database: Database name (aggregated across all files in the database) When -AggregateBy 'Disk': DiskLocation: Disk identifier - Windows letter like \"C\", \"D\"; Linux path prefix like \"/var/opt/mssql\" &nbsp;"
  },
  {
    "name": "Test-DbaEndpoint",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "endpoint"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaEndpoint",
    "popularityRank": 502,
    "synopsis": "Tests network connectivity to SQL Server endpoint TCP listener ports.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaEndpoint View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests network connectivity to SQL Server endpoint TCP listener ports. 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. The 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. Use this when diagnosing connectivity problems between SQL Server instances or validating firewall rules before setting up features that rely on endpoints. Syntax Test-DbaEndpoint [[-SqlInstance] ] [[-SqlCredential] ] [[-Endpoint] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Tests all endpoints on the local default SQL Server instance PS C:\\> Test-DbaEndpoint -SqlInstance localhost Tests all endpoints on the local default SQL Server instance. Note that if an endpoint does not have a tcp listener port, it will be skipped. Example 2: Tests all endpoints named Mirroring on sql2016 and localhost PS C:\\> Get-DbaEndpoint -SqlInstance localhost, sql2016 -Endpoint Mirror | Test-DbaEndpoint Tests all endpoints named Mirroring on sql2016 and localhost. Note that if an endpoint does not have a tcp listener port, it will be skipped. Example 3: Tests all endpoints named Mirroring on sql2016 and localhost PS C:\\> Test-DbaEndpoint -SqlInstance localhost, sql2016 -Endpoint Mirror Tests all endpoints named Mirroring on sql2016 and localhost. Note that if an endpoint does not have a tcp listener port, it will be skipped. Example 4: Tests all endpoints on the local default SQL Server instance PS C:\\> Test-DbaEndpoint -SqlInstance localhost -Verbose Tests all endpoints on the local default SQL Server instance. See all endpoints that were skipped due to not having a tcp listener port. Optional Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Endpoint Specifies which endpoint names to test for network connectivity. Accepts multiple endpoint names to filter testing to specific endpoints. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use this approach when you need to apply complex filtering logic before testing connectivity, such as testing only endpoints of a specific type or state. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per endpoint that has a TCP listener port. Each object contains the connection test results for both TCP and SSL connections. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Endpoint: The name of the endpoint being tested Port: The TCP listener port for the endpoint Connection: TCP connection status - \"Success\" for successful connection, or error message/exception if connection failed SslConnection: SSL connection status - \"Success\" for successful SSL connection, \"None\" if no SSL port configured, or error message/exception if SSL connection failed Endpoints without TCP listener ports are automatically skipped and do not produce output. &nbsp;"
  },
  {
    "name": "Test-DbaIdentityUsage",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "identity",
      "table",
      "column"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaIdentityUsage",
    "popularityRank": 478,
    "synopsis": "Analyzes IDENTITY column seed consumption and calculates percentage of available range used.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaIdentityUsage View Source Brandon Abshire, netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Analyzes IDENTITY column seed consumption and calculates percentage of available range used. 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. Syntax Test-DbaIdentityUsage [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Threshold] ] [-ExcludeSystem] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Check identity seeds for servers sql2008 and sqlserver2012 PS C:\\> Test-DbaIdentityUsage -SqlInstance sql2008, sqlserver2012 Example 2: Check identity seeds on server sql2008 for only the TestDB database PS C:\\> Test-DbaIdentityUsage -SqlInstance sql2008 -Database TestDB Example 3: Check identity seeds on server sql2008 for only the TestDB database, limiting results to 20% utilization of... PS C:\\> Test-DbaIdentityUsage -SqlInstance sql2008 -Database TestDB -Threshold 20 Check identity seeds on server sql2008 for only the TestDB database, limiting results to 20% utilization of seed range or higher Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to scan for IDENTITY column usage. Accepts multiple database names as an array. Use this when you need to focus analysis on specific databases rather than scanning all databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase The database(s) to exclude - this list is auto-populated from the server | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -ExcludeSystem Allows you to suppress output on system databases | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per IDENTITY column found in accessible databases, containing seed consumption analysis and identity range usage metrics. Default display properties (via Select-DefaultView with MaxNumberRows and NumberOfUses excluded): ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The database name containing the table with the identity column Schema: The schema name containing the table Table: The table name containing the identity column Column: The column name with the identity property SeedValue: The initial seed value of the identity column (bigint) IncrementValue: The increment value for identity generation (bigint) LastValue: The last identity value that was assigned (bigint) PercentUsed: Percentage of the available seed range consumed based on data type limits (0-100, numeric with 2 decimal places) *Additional properties available via Select-Object :** MaxNumberRows: Maximum number of rows possible for the data type (tinyint, smallint, int, or bigint) NumberOfUses: Number of times the identity value has been used (calculated from seed and last values) &nbsp;"
  },
  {
    "name": "Test-DbaInstanceName",
    "description": "When a SQL Server's 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't 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/",
    "category": "Server Management",
    "tags": [
      "spn",
      "instance",
      "utility"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaInstanceName",
    "popularityRank": 256,
    "synopsis": "Validates SQL Server instance name consistency with the host OS and identifies rename requirements and potential blockers.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaInstanceName View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates SQL Server instance name consistency with the host OS and identifies rename requirements and potential blockers. Description When a SQL Server's host OS is renamed, the SQL Server should be as well. This helps with Availability Groups and Kerberos. This command compares the SQL Server instance name (from @@servername) with the actual hostname and instance combination to determine if they match. When they don't match, a rename is typically required to prevent authentication issues and ensure proper cluster functionality. The 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. Use 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. https://www.mssqltips.com/sqlservertip/2525/steps-to-change-the-server-name-for-a-sql-server-machine/ Syntax Test-DbaInstanceName [-SqlInstance] [[-SqlCredential] ] [-ExcludeSsrs] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a PS C:\\> Test-DbaInstanceName -SqlInstance sqlserver2014a Example 2: Returns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016 PS C:\\> Test-DbaInstanceName -SqlInstance sqlserver2014a, sql2016 Example 3: Returns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016, but... PS C:\\> Test-DbaInstanceName -SqlInstance sqlserver2014a, sql2016 -ExcludeSsrs Returns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016, but skips validating if SSRS is installed on both instances. Example 4: Returns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016 PS C:\\> Test-DbaInstanceName -SqlInstance sqlserver2014a, sql2016 | Select-Object * Returns ServerInstanceName, SqlServerName, IsEqual and RenameRequired for sqlserver2014a and sql2016. If a Rename is required, it will also show Updatable, and Reasons if the server name is not updatable. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeSsrs Skips checking for SQL Server Reporting Services installations that would require manual updates after a server rename. Use this switch when you know SSRS isn't installed or when you want to focus only on core SQL Server rename blockers. Without this switch, the function will warn about SSRS configurations that need attention during rename operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance analyzed, containing instance identification, current vs. expected server names, rename requirements, and any blockers preventing safe rename operations. Properties: ComputerName: The name of the computer hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) ServerName: The current configured server name from @@servername NewServerName: The expected server name based on hostname and instance name RenameRequired: Boolean indicating whether a rename is needed (true when NewServerName differs from ServerName) 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) Warnings: Warning message about SQL Server Reporting Services needing update if found, or \"N/A\" if not applicable Blockers: Array of reasons preventing rename (database mirroring, replication, or remote logins), or \"N/A\" if no blockers exist &nbsp;"
  },
  {
    "name": "Test-DbaInstantFileInitialization",
    "description": "Audits Instant File Initialization (IFI) configuration for all SQL Server Engine services on the specified computer(s).\n\nIFI allows SQL Server to skip zeroing out data file space during file creation and auto-growth operations, which can dramatically speed up database creation, restore operations, and auto-growth events. Microsoft recommends enabling IFI as a best practice for all SQL Server installations.\n\nIFI is controlled by the Windows \"Perform Volume Maintenance Tasks\" privilege (SeManageVolumePrivilege). The recommended approach is to grant this privilege to the virtual service account \"NT SERVICE\\<ServiceName>\" rather than to the actual service account (StartName), as this follows the principle of least privilege and is account-independent.\n\nThis command checks both the virtual service account (NT SERVICE\\<ServiceName>) and the actual start account (StartName) to determine:\n- IsEnabled: IFI is enabled via either account (the service will benefit from IFI)\n- IsBestPractice: IFI is enabled via the virtual service account only (the recommended configuration)\n\nNote: This command checks direct privilege assignments only. IFI may also be enabled indirectly via group membership (e.g., Administrators), which is not detected by this command.\n\nRequires Local Admin rights on destination computer(s).\n\nReferences:\nhttps://docs.microsoft.com/en-us/sql/relational-databases/databases/database-instant-file-initialization\nhttps://blog.ordix.de/instant-file-initialization-microsoft-sql-server-set-up-check",
    "category": "Utilities",
    "tags": [
      "ifi",
      "privilege",
      "security",
      "bestpractice",
      "os"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaInstantFileInitialization",
    "popularityRank": 0,
    "synopsis": "Tests whether Instant File Initialization (IFI) is properly configured for SQL Server Engine service accounts.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaInstantFileInitialization View Source the dbatools team + Claude Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests whether Instant File Initialization (IFI) is properly configured for SQL Server Engine service accounts. Description Audits Instant File Initialization (IFI) configuration for all SQL Server Engine services on the specified computer(s). IFI allows SQL Server to skip zeroing out data file space during file creation and auto-growth operations, which can dramatically speed up database creation, restore operations, and auto-growth events. Microsoft recommends enabling IFI as a best practice for all SQL Server installations. IFI is controlled by the Windows \"Perform Volume Maintenance Tasks\" privilege (SeManageVolumePrivilege). The recommended approach is to grant this privilege to the virtual service account \"NT SERVICE\\ \" rather than to the actual service account (StartName), as this follows the principle of least privilege and is account-independent. This command checks both the virtual service account (NT SERVICE\\ ) and the actual start account (StartName) to determine: IsEnabled: IFI is enabled via either account (the service will benefit from IFI) IsBestPractice: IFI is enabled via the virtual service account only (the recommended configuration) Note: This command checks direct privilege assignments only. IFI may also be enabled indirectly via group membership (e.g., Administrators), which is not detected by this command. Requires Local Admin rights on destination computer(s). References: https://docs.microsoft.com/en-us/sql/relational-databases/databases/database-instant-file-initialization https://blog.ordix.de/instant-file-initialization-microsoft-sql-server-set-up-check Syntax Test-DbaInstantFileInitialization [[-ComputerName] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Tests IFI configuration for all SQL Server Engine services on sqlserver2019 PS C:\\> Test-DbaInstantFileInitialization -ComputerName sqlserver2019 Example 2: Tests IFI configuration for all SQL Server Engine services on sql1, sql2, and sql3 PS C:\\> Test-DbaInstantFileInitialization -ComputerName sql1, sql2, sql3 Example 3: Tests IFI configuration for all SQL Server Engine services on sql1 and sql2 PS C:\\> 'sql1', 'sql2' | Test-DbaInstantFileInitialization Example 4: Returns SQL Server services on sqlserver2019 where IFI is not configured as best practice PS C:\\> Test-DbaInstantFileInitialization -ComputerName sqlserver2019 | Where-Object IsBestPractice -eq $false Optional Parameters -ComputerName Specifies the SQL Server host computer(s) to test IFI configuration on. Accepts server names, IP addresses, or DbaInstance objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Specifies a PSCredential object used to authenticate to the target computer(s) when the current user account is insufficient. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server Engine service found on each computer tested. Default display properties (via Select-DefaultView): ComputerName: The target computer name InstanceName: The SQL Server instance name ServiceName: The Windows service name (e.g. MSSQLSERVER, MSSQL$INSTANCENAME) StartName: The actual Windows account running the service IsEnabled: Boolean indicating if IFI is enabled via either the virtual or start account IsBestPractice: Boolean indicating if IFI is enabled via the virtual service account (NT SERVICE\\ ) only Additional properties available: ServiceNameIFI: Boolean indicating if the virtual service account (NT SERVICE\\ ) has IFI privilege StartNameIFI: Boolean indicating if the actual start account (StartName) has IFI privilege &nbsp;"
  },
  {
    "name": "Test-DbaKerberos",
    "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 up to 18 base 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 (2 checks):\n- Forward lookup verification\n- Reverse lookup verification\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.",
    "category": "Utilities",
    "tags": [
      "kerberos",
      "spn",
      "authentication",
      "security"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaKerberos",
    "popularityRank": 0,
    "synopsis": "Tests Kerberos authentication configuration for SQL Server instances by performing comprehensive diagnostic checks.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaKerberos View Source Claude + Andreas Jordan + Chrissy LeMaire Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests Kerberos authentication configuration for SQL Server instances by performing comprehensive diagnostic checks. 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. The function performs up to 18 base checks across 9 categories (plus additional checks per AG listener): SPN (1-2+ checks): SPN Registration - Verifies required SPNs are registered using Test-DbaSpn AG Listener SPN - One check per Availability Group listener (if any exist) Time Sync (2 checks): Client-Server time synchronization (5-minute Kerberos threshold) Server-DC time synchronization DNS (2 checks): Forward lookup verification Reverse lookup verification Service Account (3 checks): Service account type validation (gMSA, domain account, built-in accounts) Account lock status in Active Directory Delegation settings (\"sensitive and cannot be delegated\" flag) Authentication (1 check): Current authentication scheme (Kerberos vs NTLM) Network (3 checks): Kerberos port TCP/88 connectivity to DC LDAP port TCP/389 connectivity to DC Kerberos-Kdc port TCP/464 connectivity to DC Security Policy (3 checks): Kerberos encryption types configuration Computer secure channel health Hosts file entries that may override DNS SQL Configuration (2 checks): SQL Server service account configuration Network protocol configuration (TCP/IP enabled) Client (1 check): Kerberos ticket cache inspection via klist Each check returns a structured result with ComputerName, InstanceName, Check, Category, Status (Pass/Fail/Warning), Details, and Remediation recommendations. Note: When using -ComputerName instead of -SqlInstance, SQL Server-specific checks (service account, authentication scheme, network protocols) are skipped. Syntax Test-DbaKerberos -SqlInstance [-SqlCredential ] [-Credential ] [-EnableException] [ ] Test-DbaKerberos -ComputerName [-SqlCredential ] [-Credential ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Performs comprehensive Kerberos diagnostic checks for the sql2016 instance, returning pass/fail/warning... PS C:\\> Test-DbaKerberos -SqlInstance sql2016 Performs comprehensive Kerberos diagnostic checks for the sql2016 instance, returning pass/fail/warning status for each check with remediation recommendations. Example 2: Tests Kerberos configuration using SQL credentials to connect to the instance and separate AD credentials for... PS C:\\> Test-DbaKerberos -SqlInstance sql2016 -SqlCredential (Get-Credential) -Credential (Get-Credential) Tests Kerberos configuration using SQL credentials to connect to the instance and separate AD credentials for remote WinRM and Active Directory queries. Example 3: Tests multiple SQL Server instances in a single command PS C:\\> Test-DbaKerberos -SqlInstance sql2016, sql2019 Example 4: Tests Kerberos configuration at the computer level using specified credentials for WinRM and AD queries PS C:\\> Test-DbaKerberos -ComputerName SERVER01 -Credential (Get-Credential) Tests Kerberos configuration at the computer level using specified credentials for WinRM and AD queries. SQL Server-specific checks are skipped. Example 5: Tests all registered servers and returns only the checks that failed, useful for identifying problems across... PS C:\\> Get-DbaRegServer -SqlInstance sqlcentral | Test-DbaKerberos | Where-Object Status -eq \"Fail\" Tests all registered servers and returns only the checks that failed, useful for identifying problems across your environment. Example 6: Returns only the SPN-related checks for the specified instance PS C:\\> Test-DbaKerberos -SqlInstance sql2016 | Where-Object Category -eq \"SPN\" Example 7: Displays results in a formatted table for easier reading PS C:\\> Test-DbaKerberos -SqlInstance sql2016 | Format-Table -AutoSize Required Parameters -SqlInstance The target SQL Server instance or instances to test Kerberos configuration. Accepts SQL Server instance names and supports pipeline input for bulk testing. All checks including SQL Server-specific checks will be performed. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -ComputerName Alternative parameter to specify target computers to test. Use this when you want to test Kerberos configuration at the computer level rather than for specific SQL instances. Accepts computer names, IP addresses, or fully qualified domain names. Note: SQL Server-specific checks will be skipped when using this parameter. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target SQL Server instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Credential for remote WinRM connections and Active Directory queries. Used for Invoke-Command calls to remote servers and for querying AD to verify SPN registrations and service account properties. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per diagnostic check performed (typically 12-18 checks depending on parameter set and configuration) with the following properties: ComputerName (string) - The name of the computer or SQL Server host that was tested InstanceName (string) - The SQL Server instance name if testing an instance; $null if testing at the computer level Check (string) - Name of the specific diagnostic check (e.g., \"SPN Registration\", \"Time Synchronization (Client-Server)\", \"DNS Forward Lookup\") Category (string) - Category grouping the check: SPN, Time Sync, DNS, Service Account, Authentication, Network, Security Policy, SQL Configuration, or Client Status (string) - Result of the check: \"Pass\" (configuration is correct), \"Fail\" (configuration error or problem detected), or \"Warning\" (potential issue or unable to verify) Details (string) - Specific details about the check result, including measurements (e.g., time differences in minutes, missing SPNs, port status) Remediation (string) - Recommended action to resolve the issue (or \"None\" if the check passed) Each check returns a separate PSCustomObject, enabling filtering by Category, Status, or other properties to focus on specific diagnostic areas. Output is returned immediately for each check, enabling real-time monitoring of diagnostic progress. The function may return additional checks for Availability Group listeners if any exist on the instance, each with a check name like \"AG Listener SPN - \". &nbsp;"
  },
  {
    "name": "Test-DbaLastBackup",
    "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",
    "category": "Backup & Restore",
    "tags": [
      "disasterrecovery",
      "backup",
      "restore"
    ],
    "verb": "Test",
    "popular": true,
    "url": "/Test-DbaLastBackup",
    "popularityRank": 48,
    "synopsis": "Quickly and easily tests the last set of full backups for a server.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaLastBackup View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Quickly and easily tests the last set of full backups for a server. Description Restores all or some of the latest backups and performs a DBCC CHECKDB. 1. Gathers information about the last full backups 2. Restores the backups to the Destination with a new name. If no Destination is specified, the originating SQL Server instance wil be used. 3. The database is restored as \"dbatools-testrestore-$databaseName\" by default, but you can change dbatools-testrestore to whatever you would like using -Prefix 4. The internal file names are also renamed to prevent conflicts with original database 5. A DBCC CHECKDB is then performed 6. And the test database is finally dropped Syntax Test-DbaLastBackup [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [[-Destination] ] [[-DestinationSqlCredential] ] [[-DataDirectory] ] [[-LogDirectory] ] [[-FileStreamDirectory] ] [[-Prefix] ] [-VerifyOnly] [-NoCheck] [-NoDrop] [-CopyFile] [[-CopyPath] ] [[-MaxSize] ] [[-DeviceType] ] [-IncludeCopyOnly] [-IgnoreLogBackup] [[-StorageCredential] ] [[-InputObject] ] [[-MaxTransferSize] ] [[-BufferCount] ] [-IgnoreDiffBackup] [[-MaxDop] ] [-ReuseSourceFolderStructure] [-Checksum] [[-Wait] ] [[-Path] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Determines the last full backup for ALL databases, attempts to restore all databases (with a different name... PS C:\\> Test-DbaLastBackup -SqlInstance sql2016 Determines 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 restore will be dropped. Example 2: Determines the last full backup for SharePoint_Config, attempts to restore it, then performs a DBCC CHECKDB PS C:\\> Test-DbaLastBackup -SqlInstance sql2016 -Database SharePoint_Config Example 3: Tests every database backup on sql2016 and sql2017 PS C:\\> Get-DbaDatabase -SqlInstance sql2016, sql2017 | Test-DbaLastBackup Example 4: Tests the database backup for the SharePoint_Config database on sql2016 and sql2017 PS C:\\> Get-DbaDatabase -SqlInstance sql2016, sql2017 -Database SharePoint_Config | Test-DbaLastBackup Example 5: Skips performing an action restore of the database and simply verifies the backup using VERIFYONLY option of... PS C:\\> Test-DbaLastBackup -SqlInstance sql2016 -Database model, master -VerifyOnly Skips performing an action restore of the database and simply verifies the backup using VERIFYONLY option of the restore. Example 6: Skips the DBCC CHECKDB check PS C:\\> Test-DbaLastBackup -SqlInstance sql2016 -NoCheck -NoDrop Skips the DBCC CHECKDB check. This can help speed up the tests but makes it less tested. The test restores will remain on the server. Example 7: Restores data and log files to alternative locations and only restores databases that are smaller than 10 GB PS C:\\> Test-DbaLastBackup -SqlInstance sql2016 -DataDirectory E:\\bigdrive -LogDirectory L:\\bigdrive -MaxSize 10240 Example 8: Copies the backup files for sql2014 databases to sql2016 default backup locations and then attempts restore... PS C:\\> Test-DbaLastBackup -SqlInstance sql2014 -Destination sql2016 -CopyFile Copies the backup files for sql2014 databases to sql2016 default backup locations and then attempts restore from there. Example 9: Copies the backup files for sql2014 databases to sql2016 default backup locations and then attempts restore... PS C:\\> Test-DbaLastBackup -SqlInstance sql2014 -Destination sql2016 -CopyFile -CopyPath \"\\\\BackupShare\\TestRestore\\\" Copies the backup files for sql2014 databases to sql2016 default backup locations and then attempts restore from there. Example 10: Determines the last full backup for ALL databases, attempts to restore all databases (with a different name... PS C:\\> Test-DbaLastBackup -SqlInstance sql2016 -NoCheck -MaxTransferSize 4194302 -BufferCount 24 Determines the last full backup for ALL databases, attempts to restore all databases (with a different name and file structure). The 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!!! When running the restore with these additional parameters and there is other server activity it could affect server OLTP performance. Please use with caution. Prior to running, you should check memory and server resources before configure it to run automatically. More information: https://www.mssqltips.com/sqlservertip/4935/optimize-sql-server-database-restore-performance/ Example 11: The use of the MaxDop parameter will limit the number of processors used during the DBCC command PS C:\\> Test-DbaLastBackup -SqlInstance sql2016 -MaxDop 4 Example 12: Verifies the backup files using RESTORE VERIFYONLY WITH CHECKSUM PS C:\\> Test-DbaLastBackup -SqlInstance sql2016 -Database model, master -VerifyOnly -Checksum Verifies the backup files using RESTORE VERIFYONLY WITH CHECKSUM. This will fail if the backups do not contain checksums, ensuring that backups follow best practices. Example 13: Tests all database backups on sql2016 and waits 5 seconds between each database restore test PS C:\\> Test-DbaLastBackup -SqlInstance sql2016 -Wait 5 Tests 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. Example 14: Tests the last backup of the Sales database where backups are stored in S3-compatible storage PS C:\\> Test-DbaLastBackup -SqlInstance sql2022 -Database Sales -StorageCredential \"S3Credential\" Tests the last backup of the Sales database where backups are stored in S3-compatible storage. Requires SQL Server 2022 or later for S3 support. Example 15: Scans the specified UNC path for backup files, then tests all databases found by restoring them to sql2016... PS C:\\> Test-DbaLastBackup -Path \"\\\\BackupShare\\Backups\\sql2016\" -Destination sql2016 Scans the specified UNC path for backup files, then tests all databases found by restoring them to sql2016 and performing a DBCC CHECKDB. Example 16: Scans the specified UNC path for AdventureWorks backup files and tests the restore on sql2016test PS C:\\> Test-DbaLastBackup -Path \"\\\\BackupShare\\Backups\\sql2016\" -Destination sql2016test -Database AdventureWorks Optional Parameters -SqlInstance The target SQL Server instance or instances. Unlike many of the other commands, you cannot specify more than one server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to include in the backup test. Accepts wildcards for pattern matching. Use this to limit testing to specific databases instead of all databases on the instance. Helpful when you only want to verify critical databases or troubleshoot specific backup issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to exclude from backup testing. Accepts wildcards for pattern matching. Use this to skip non-critical databases, large databases, or databases with known backup issues. Commonly used to exclude system databases or databases that would take too long to test. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Destination Specifies the SQL Server instance where test restores will be performed. Defaults to the source server if not specified. Use this when you want to test restores on a different server, such as isolating test operations from production workloads. When using a different destination server, backup files must be accessible from that server via shared storage or use -CopyFile. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for connecting to the destination SQL Server instance when different from the source. Use this when the destination server requires different authentication than the source server. Accepts PowerShell credentials (Get-Credential) and supports Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DataDirectory Specifies the directory where restored database data files (.mdf, .ndf) will be placed. Defaults to the SQL Server's default data directory. Use this when you need to direct test restores to specific storage, such as faster drives for testing or isolated storage locations. The SQL Server service account must have write permissions to this directory. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -LogDirectory Specifies the directory where restored database log files (.ldf) will be placed. Defaults to the SQL Server's default log directory. Use this when you want to separate test database logs from production logs or direct them to faster storage for testing. The SQL Server service account must have write permissions to this directory. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FileStreamDirectory Specifies the directory where FileStream data will be restored for databases that use FileStream storage. Use this when testing databases with FileStream-enabled tables to ensure the FileStream data is properly restored and accessible. Required only for databases that contain FileStream data and when not using -ReuseSourceFolderStructure. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Prefix Specifies the naming prefix for test databases. Defaults to 'dbatools-testrestore-' resulting in names like 'dbatools-testrestore-MyDB'. Use this to customize test database naming for organizational standards or to avoid naming conflicts. Choose prefixes that clearly identify databases as temporary test restores. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | dbatools-testrestore- | -VerifyOnly Performs backup verification only without actually restoring the database. Uses T-SQL RESTORE VERIFYONLY command. Use this for faster backup validation when you only need to confirm backup file integrity without full restore testing. Skips DBCC CHECKDB since no actual database is restored. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoCheck Skips the DBCC CHECKDB operation after restoring the test database. Use this to speed up the testing process when you only need to verify that backups can be restored successfully. Reduces testing time but provides less thorough validation of database integrity. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoDrop Prevents the test database from being automatically dropped after the test completes. Use this when you need to examine the restored database manually or perform additional testing. Remember to manually clean up test databases later to avoid storage issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CopyFile Copies backup files to the destination server's default backup directory before attempting the restore. Use this when backup files are not accessible from the destination server, such as local backups on different servers. Cannot be used with Azure SQL Database backups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CopyPath Specifies the destination directory where backup files will be copied when using -CopyFile. Defaults to the destination server's default backup directory. Use this to control where backup files are temporarily stored during testing, such as directing them to faster storage. Path must be accessible to the destination SQL Server service account. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MaxSize Maximum database size in MB. Databases with backups larger than this value will be skipped. Use this to avoid testing extremely large databases that would consume excessive time or storage resources. Helps focus testing on databases that can be practically tested within available resources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -DeviceType Filters backups by device type such as 'Disk', 'Tape', or 'Virtual Device'. Accepts multiple values. Use this when you need to test only backups from specific backup devices or exclude certain device types. Commonly used to test only disk backups or exclude tape backups that may be offline. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -IncludeCopyOnly Includes copy-only backups when determining the most recent backup to test. Use this when you want to test copy-only backups that were created for specific purposes like migrations or testing. Copy-only backups don't break the backup chain but are normally excluded from 'last backup' queries. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -IgnoreLogBackup Skips transaction log backups during restore, stopping at the most recent full or differential backup. Use this for faster testing when point-in-time recovery precision isn't critical for the test. Results in some data loss compared to a complete restore chain but significantly reduces testing time. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -StorageCredential Specifies the name of the SQL Server credential for accessing cloud storage where backups are stored. For Azure: Use credentials containing the storage account access key or configured for SAS authentication. For S3: Use credentials with Identity = 'S3 Access Key' and Secret = 'AccessKeyID:SecretKeyID'. Requires SQL Server 2022 or later. The credential must already exist on the destination SQL Server instance. | Property | Value | | --- | --- | | Alias | AzureCredential,S3Credential | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts database objects from Get-DbaDatabase for pipeline processing. Use this to test backups for databases selected through Get-DbaDatabase filtering options. Enables complex database selection scenarios beyond simple name matching. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -MaxTransferSize Sets the data transfer unit size for backup restoration. Must be a multiple of 64KB with a maximum of 4GB. Use this to optimize restore performance by increasing buffer size, especially for large databases on high-speed storage. Higher values can improve performance but consume more memory during the restore operation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -BufferCount Specifies the number of I/O buffers used during the restore operation. Use this to optimize restore performance by controlling memory allocation for the restore process. Higher values can improve performance but consume more memory, so balance against other server activity. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -IgnoreDiffBackup Skips differential backups during restore, using only full and transaction log backups. Use this to test restore scenarios that don't rely on differential backups or when differential backups are suspected to be problematic. May significantly increase restore time due to processing more transaction log backups. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -MaxDop Sets the maximum degree of parallelism for the DBCC CHECKDB operation. Limits the number of parallel processes used. Use this to control resource usage during integrity checks, especially on busy servers or when testing multiple databases. Lower values reduce CPU usage but increase DBCC runtime. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -ReuseSourceFolderStructure Maintains the original file paths and directory structure from the source database during restore. Use this when testing databases that have specific file location requirements or when simulating exact production restore scenarios. Ensures the destination server has the same directory structure as the source or the restore will fail. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Checksum Enables backup checksum verification during restore operations. When used with -VerifyOnly, forces the RESTORE VERIFYONLY command to use WITH CHECKSUM. Use this to ensure backup files contain checksums and validate them during testing, following backup best practices. Without this parameter, SQL Server verifies checksums if present but doesn't fail if checksums are missing. With this parameter, the operation fails if checksums are not present in the backup. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Wait Specifies the number of seconds to wait between each database restore test. Use this to prevent I/O errors on checkpoint files by allowing time for cleanup between restore operations. Helpful when restoring to network shares or storage systems that need additional time to release file handles. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -Path Specifies one or more folder paths containing backup files to test instead of querying backup history from a SQL instance. Use this when you want to validate backup files from a specific location without needing the original source SQL Server instance. Backup files will be discovered recursively from the specified paths. When using -Path, a -Destination server must be specified. Accepts local paths, UNC paths, Azure blob storage URLs, or S3 URLs accessible to the destination SQL Server instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per database tested with the following properties: SourceServer (string) - Name of the source SQL Server instance where the backup originated TestServer (string) - Name of the destination SQL Server instance where the restore was tested Database (string) - Name of the database being tested FileExists (boolean) - Whether the backup files were found and accessible ($true, $false, or $null) Size (dbasize) - Total size of the backup files; dbasize object convertible to Bytes, KB, MB, GB, TB RestoreResult (string) - Result of the restore operation: \"Success\", \"Failure\", \"Skipped\", or error message DbccResult (string) - Result of the DBCC CHECKDB operation: \"Success\", \"Failure\", \"Skipped\", or detailed error RestoreStart (datetime) - Date and time when the restore operation started RestoreEnd (datetime) - Date and time when the restore operation ended RestoreElapsed (timespan as string) - Formatted duration of the restore operation (HH:mm:ss format) DbccMaxDop (int) - Maximum degree of parallelism used for DBCC CHECKDB DbccStart (datetime) - Date and time when the DBCC CHECKDB operation started DbccEnd (datetime) - Date and time when the DBCC CHECKDB operation ended DbccElapsed (timespan as string) - Formatted duration of the DBCC CHECKDB operation (HH:mm:ss format) DbccOutput (string array) - Detailed informational messages returned by DBCC CHECKDB (row counts, Service Broker analysis, etc.); $null when skipped BackupDates (datetime array) - Array of backup start times for all backup files in the restore chain BackupFiles (string array) - Array of backup file paths used for the restore operation Output is returned immediately for each database processed, enabling real-time progress monitoring of multi-database restore tests. &nbsp;"
  },
  {
    "name": "Test-DbaLinkedServerConnection",
    "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's 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.",
    "category": "Utilities",
    "tags": [
      "linkedserver"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaLinkedServerConnection",
    "popularityRank": 242,
    "synopsis": "Tests connectivity to all linked servers on specified SQL Server instances",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaLinkedServerConnection View Source Thomas LaRock, thomaslarock.com Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests connectivity to all linked servers on specified SQL Server instances 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's 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. Syntax Test-DbaLinkedServerConnection [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Test all Linked Servers for the SQL Server instance DEV01 PS C:\\> Test-DbaLinkedServerConnection -SqlInstance DEV01 Example 2: Test all Linked Servers for the SQL Server instance sql2016 and output results to file PS C:\\> Test-DbaLinkedServerConnection -SqlInstance sql2016 | Out-File C:\\temp\\results.txt Example 3: Test all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012 PS C:\\> Test-DbaLinkedServerConnection -SqlInstance sql2016, sql2014, sql2012 Example 4: Test all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012 using SQL login credentials PS C:\\> $servers = \"sql2016\",\"sql2014\",\"sql2012\" PS C:\\> $servers | Test-DbaLinkedServerConnection -SqlCredential sqladmin Example 5: Test all Linked Servers for the SQL Server instances sql2016, sql2014 and sql2012 PS C:\\> $servers = \"sql2016\",\"sql2014\",\"sql2012\" PS C:\\> $servers | Get-DbaLinkedServer | Test-DbaLinkedServerConnection Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs Dataplat.Dbatools.Validation.LinkedServerResult Returns one object per linked server on each target instance, containing the connection test result and status information. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Name: The name of the linked server DataSource: The data source or connection string of the linked server Connectivity: Boolean indicating if the linked server connection was successful (true = connected, false = failed) Result: Connection test result message - either \"Success\" or the specific error message explaining the connection failure &nbsp;"
  },
  {
    "name": "Test-DbaLoginPassword",
    "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.",
    "category": "Security",
    "tags": [
      "login"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaLoginPassword",
    "popularityRank": 193,
    "synopsis": "Identifies SQL Server logins with weak passwords including empty, username-matching, or dictionary-based passwords",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaLoginPassword View Source Peter Samuelsson Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Identifies SQL Server logins with weak passwords including empty, username-matching, or dictionary-based passwords 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. Syntax Test-DbaLoginPassword [[-SqlInstance] ] [[-SqlCredential] ] [[-Login] ] [[-Dictionary] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Test all SQL logins that the password is null or same as username on SQL server instance Dev01 PS C:\\> Test-DbaLoginPassword -SqlInstance Dev01 Example 2: Test the &#39;sqladmin&#39; SQL login that the password is null or same as username on SQL server instance Dev01 PS C:\\> Test-DbaLoginPassword -SqlInstance Dev01 -Login sqladmin Example 3: Test all SQL logins that the password is null, same as username or Test1,Test2 on SQL server instance Dev0 PS C:\\> Test-DbaLoginPassword -SqlInstance Dev01 -Dictionary Test1,test2 Example 4: Test all logins on sql2017 and sql2016 PS C:\\> Get-DbaLogin -SqlInstance \"sql2017\",\"sql2016\" | Test-DbaLoginPassword Example 5: Test selected logins on all servers in the $servers variable PS C:\\> $servers | Get-DbaLogin | Out-GridView -PassThru | Test-DbaLoginPassword Optional Parameters -SqlInstance The SQL Server instance you're checking logins on. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Allows you to login to servers using SQL Logins instead of Windows Authentication (AKA Integrated or Trusted). To use: $scred = Get-Credential, then pass $scred object to the -SqlCredential parameter. Windows Authentication will be used if SqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials. To connect as a different Windows user, run PowerShell as that user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Login Specifies which SQL authentication logins to test for weak passwords instead of testing all SQL logins on the instance. Accepts single login names, arrays of login names, or wildcard patterns for filtering specific accounts. Useful when you want to focus testing on high-privilege logins or specific service accounts that need immediate attention. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Dictionary Specifies additional passwords to test against all SQL authentication logins using PWDCOMPARE(). Use this to check for organization-specific weak passwords like company names, common words, or previously breached passwords. These passwords are tested in addition to the default checks for empty passwords and username-matching passwords. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts login objects from Get-DbaLogin to test for weak passwords, enabling pipeline operations and complex filtering scenarios. Use this when you need to filter logins by properties like creation date, last login time, or server roles before testing passwords. Commonly used with Get-DbaLogin to test logins across multiple servers or with specific criteria that can't be achieved with the Login parameter alone. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL login with a weak password identified during testing. If no logins have weak passwords, nothing is returned. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name (defaults to 'MSSQLSERVER' for default instance) SqlInstance: The full SQL Server instance name SqlLogin: The name of the SQL login with weak password WeakPassword: String value 'True' indicating weak password was found Password: The weak password that matched (with @@Name placeholder replaced by actual login name for username-based matches) Disabled: Boolean indicating if the login is currently disabled CreatedDate: DateTime when the login was created ModifiedDate: DateTime when the login was last modified DefaultDatabase: The default database for the login &nbsp;"
  },
  {
    "name": "Test-DbaManagementObject",
    "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.",
    "category": "Advanced Features",
    "tags": [
      "smo"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaManagementObject",
    "popularityRank": 556,
    "synopsis": "Verifies if specific SQL Server Management Objects (SMO) library versions are installed on target computers.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaManagementObject View Source Ben Miller (@DBAduck), dbaduck.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Verifies if specific SQL Server Management Objects (SMO) library versions are installed on target computers. 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. Syntax Test-DbaManagementObject [[-ComputerName] ] [[-Credential] ] [-VersionNumber] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Returns True if the version exists, if it does not exist it will return False PS C:\\> Test-DbaManagementObject -VersionNumber 13 Required Parameters -VersionNumber Specifies the major version number(s) of SQL Server SMO assemblies to verify in the Global Assembly Cache. Common values include 11 (SQL 2012), 12 (SQL 2014), 13 (SQL 2016), 14 (SQL 2017), 15 (SQL 2019), and 16 (SQL 2022). | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -ComputerName Specifies the target computer(s) to check for SMO assemblies. Accepts pipeline input and defaults to the local computer. Use this when verifying SMO library versions across multiple servers in your environment. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential This command uses Windows credentials. This parameter allows you to connect remotely as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per queried SMO version on each target computer. Properties: ComputerName: The name of the computer where the SMO assembly check was performed Version: The major version number of SQL Server SMO assembly being checked (e.g., 13 for SQL 2016, 15 for SQL 2019) Exists: Boolean indicating whether the specified SMO assembly version is installed in the Global Assembly Cache (True if found, False if not found) &nbsp;"
  },
  {
    "name": "Test-DbaMaxDop",
    "description": "Analyzes your SQL Server's Max Degree of Parallelism (MAXDOP) settings and compares them against Microsoft's recommended values based on your server's 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's official guidelines but include warnings for scenarios where custom MAXDOP values may be intentionally set for specific applications.\n\nInspired by Sakthivel Chidambaram's MAXDOP Calculator methodology and Microsoft's 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/",
    "category": "Utilities",
    "tags": [
      "maxdop",
      "utility"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaMaxDop",
    "popularityRank": 159,
    "synopsis": "Tests SQL Server MAXDOP configuration against recommended values based on CPU cores and NUMA topology.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaMaxDop View Source Claudio Silva (@claudioessilva) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests SQL Server MAXDOP configuration against recommended values based on CPU cores and NUMA topology. Description Analyzes your SQL Server's Max Degree of Parallelism (MAXDOP) settings and compares them against Microsoft's recommended values based on your server's hardware configuration. This function examines CPU cores, NUMA topology, and SQL Server version to calculate optimal MAXDOP settings for query performance. The 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. For 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. Results include current settings, recommended values, and guidance notes about whether changes should be considered. The recommendations follow Microsoft's official guidelines but include warnings for scenarios where custom MAXDOP values may be intentionally set for specific applications. Inspired by Sakthivel Chidambaram's MAXDOP Calculator methodology and Microsoft's official guidance (KB 2806535). More info: https://support.microsoft.com/en-us/kb/2806535 https://blogs.msdn.microsoft.com/sqlsakthi/2012/05/23/wow-we-have-maxdop-calculator-for-sql-server-it-makes-my-job-easier/ Syntax Test-DbaMaxDop [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Get Max DOP setting for servers sql2008 and sqlserver2012 and also the recommended one PS C:\\> Test-DbaMaxDop -SqlInstance sql2008, sqlserver2012 Example 2: Shows Max DOP setting for server sql2014 with the recommended value PS C:\\> Test-DbaMaxDop -SqlInstance sql2014 | Select-Object Shows Max DOP setting for server sql2014 with the recommended value. Piping the output to Select-Object will also show the 'NumaNodes' and 'NumberOfCores' of each instance Example 3: Get Max DOP setting for servers sql2016 with the recommended value PS C:\\> Test-DbaMaxDop -SqlInstance sqlserver2016 | Select-Object Get Max DOP setting for servers sql2016 with the recommended value. Piping the output to Select-Object will also show the 'NumaNodes' and 'NumberOfCores' of each instance. Because it is an 2016 instance will be shown 'InstanceVersion', 'Database' and 'DatabaseMaxDop' columns. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance. For SQL Server 2016 and higher, also returns one object per user database with database-level MAXDOP settings. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) Database: The database name (N/A for instance-level results, database name for SQL 2016+ database-level results) DatabaseMaxDop: The database-level MAXDOP setting (N/A for instance-level results, numeric for SQL 2016+) CurrentInstanceMaxDop: The current instance-level MAXDOP configuration value (0 = unlimited, or specific number) RecommendedMaxDop: The Microsoft-recommended MAXDOP value based on CPU cores and NUMA topology Notes: Configuration guidance notes indicating whether the current setting matches recommendations *Additional properties available (via Select-Object ):** InstanceVersion: The full version of SQL Server (e.g., \"11.0.1234.56\") NumaNodes: The number of NUMA nodes detected on the instance NumberOfCores: The total number of logical processor cores visible to SQL Server &nbsp;"
  },
  {
    "name": "Test-DbaMaxMemory",
    "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's memory calculation methodology, this provides general recommendations that should be validated against your specific environment and workload requirements.",
    "category": "Performance",
    "tags": [
      "maxmemory",
      "memory"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaMaxMemory",
    "popularityRank": 109,
    "synopsis": "Calculates recommended SQL Server max memory settings to prevent OS memory pressure and optimize performance.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaMaxMemory View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Calculates recommended SQL Server max memory settings to prevent OS memory pressure and optimize performance. 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's memory calculation methodology, this provides general recommendations that should be validated against your specific environment and workload requirements. Syntax Test-DbaMaxMemory [-SqlInstance] [[-SqlCredential] ] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Calculate the &#39;Max Server Memory&#39; for SQL Server instances sqlcluster and sqlserver2012 PS C:\\> Test-DbaMaxMemory -SqlInstance sqlcluster,sqlserver2012 Example 2: Calculate the &#39;Max Server Memory&#39; settings for all servers within the SQL Server Central Management Server... PS C:\\> Get-DbaRegServer -SqlInstance sqlcluster | Test-DbaMaxMemory Calculate the 'Max Server Memory' settings for all servers within the SQL Server Central Management Server \"sqlcluster\" Example 3: Find all servers in CMS that have Max SQL memory set to higher than the total memory of the server (think... PS C:\\> Get-DbaRegServer -SqlInstance sqlcluster | Test-DbaMaxMemory | Where-Object { $_.MaxValue -gt $_.Total } | Set-DbaMaxMemory Find 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. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Credential Windows Credential with permission to log on to the server running the SQL instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance analyzed, providing memory configuration analysis. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance format) InstanceCount: The number of running SQL Engine instances detected on the server Total: Total system memory in megabytes (MB) MaxValue: Current max server memory setting in megabytes (MB) RecommendedValue: Calculated recommended max server memory in megabytes (MB) based on Jonathan Kehayias's algorithm, accounting for OS reserve and instance count Additional properties available: Server: Reference to the SMO Server object for the instance, allowing further server-specific queries or operations &nbsp;"
  },
  {
    "name": "Test-DbaMigrationConstraint",
    "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't 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.",
    "category": "Utilities",
    "tags": [
      "migration"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaMigrationConstraint",
    "popularityRank": 148,
    "synopsis": "Validates database migration compatibility between SQL Server instances by checking for edition-specific features.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaMigrationConstraint View Source Claudio Silva (@ClaudioESSilva) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates database migration compatibility between SQL Server instances by checking for edition-specific features. Description Prevents migration failures by identifying databases that use features incompatible with the destination SQL Server edition. This 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). Common 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. The function also checks FILESTREAM configuration compatibility and validates that Change Data Capture (CDC) isn't used when migrating to Express edition, since Express lacks SQL Server Agent. Validation works on SQL Server 2008 and higher versions using the sys.dm_db_persisted_sku_features DMV. Supported editions include Enterprise, Developer, Evaluation, Standard, and Express. SQL Server 2016 SP1 introduced feature parity across editions for many capabilities, so this function accounts for those changes when validating post-SP1 destinations. For more details see: https://blogs.msdn.microsoft.com/sqlreleaseservices/sql-server-2016-service-pack-1-sp1-released/ The -Database parameter is auto-populated for command-line completion. Syntax Test-DbaMigrationConstraint [-Source] [[-SourceSqlCredential] ] [-Destination] [[-DestinationSqlCredential] ] [[-Database] ] [[-ExcludeDatabase] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: All databases on sqlserver2014a will be verified for features in use that can&#39;t be supported on sqlcluster PS C:\\> Test-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster Example 2: All databases will be verified for features in use that can&#39;t be supported on the destination server PS C:\\> Test-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster -SourceSqlCredential $cred All databases will be verified for features in use that can't be supported on the destination server. SQL credentials are used to authenticate against sqlserver2014a and Windows Authentication is used for sqlcluster. Example 3: Only db1 database will be verified for features in use that can&#39;t be supported on the destination server PS C:\\> Test-DbaMigrationConstraint -Source sqlserver2014a -Destination sqlcluster -Database db1 Required Parameters -Source Specifies the source SQL Server instance containing databases to validate for migration compatibility. Must be SQL Server 2008 or higher since the function uses sys.dm_db_persisted_sku_features DMV to detect edition-specific features. Requires sysadmin access to query system views and database metadata. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Destination Specifies the destination SQL Server instance where databases will be migrated to. The function validates that database features are compatible with this target server's edition (Enterprise, Developer, Standard, or Express). Must be SQL Server 2008 or higher and requires sysadmin access to check server edition and configuration settings like FileStream access level. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SourceSqlCredential Credentials for authenticating to the source SQL Server instance when Windows Authentication is not available. Use this when running the function with a different account than your current Windows login, or when connecting to SQL instances that require SQL Authentication. Create with Get-Credential or pass stored credential objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -DestinationSqlCredential Credentials for authenticating to the destination SQL Server instance when Windows Authentication is not available. Required when the destination server uses different authentication than your current context, or when testing migrations across domains. Use Get-Credential to create or pass existing credential objects. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies which databases to validate for migration compatibility. When omitted, checks all user databases on the source instance (excludes system databases master, msdb, tempdb). Use this to focus validation on specific databases when planning selective migrations or troubleshooting particular database features. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeDatabase Specifies databases to skip during the migration validation process. Useful when you know certain databases won't be migrated or when focusing validation efforts on a subset of databases. Commonly used to exclude test databases, archived databases, or databases with known compatibility issues. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per database validated, providing detailed migration compatibility assessment. Properties: SourceInstance: Name of the source SQL Server instance DestinationInstance: Name of the destination SQL Server instance SourceVersion: Source server edition, product level, and version number (e.g., \"Enterprise SP1 (13.0.5850.14)\") DestinationVersion: Destination server edition, product level, and version number Database: Name of the database being validated FeaturesInUse: Comma-separated list of enterprise edition features detected (e.g., \"ChangeCapture,XTP\"), or empty string if none IsMigratable: Boolean indicating whether the database can be successfully migrated to the destination (True/False) Notes: Human-readable message explaining the migration status, including specific reasons if the database cannot be migrated (e.g., FileStream configuration mismatch, Express edition incompatibilities, or missing features on destination) &nbsp;"
  },
  {
    "name": "Test-DbaNetworkCertificate",
    "description": "Tests network certificate configuration for SQL Server instances in two ways.\n\nWithout the Thumbprint parameter (Way One): Calls Get-DbaNetworkConfiguration to retrieve\ninformation about the currently configured certificate and available suitable certificates.\nReturns a summary indicating whether the configured certificate is valid for the minimum\nrequired days and whether any suitable certificates are available.\n\nWith the Thumbprint parameter (Way Two): Executes detailed certificate validation tests\non the target machine to determine if the specified certificate is suitable for SQL Server\nnetwork encryption. Returns individual test results for each requirement, making it easy\nto identify which specific tests failed.\n\nThe certificate validation logic is aligned with Get-DbaNetworkConfiguration to ensure\nconsistent behavior. For details on certificate requirements, see\nhttps://learn.microsoft.com/en-us/sql/database-engine/configure-windows/certificate-requirements",
    "category": "Security",
    "tags": [
      "certificate",
      "encryption",
      "security",
      "network"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaNetworkCertificate",
    "popularityRank": 0,
    "synopsis": "Tests network certificate configuration and suitability for SQL Server instances",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaNetworkCertificate View Source the dbatools team + Claude Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests network certificate configuration and suitability for SQL Server instances Description Tests network certificate configuration for SQL Server instances in two ways. Without the Thumbprint parameter (Way One): Calls Get-DbaNetworkConfiguration to retrieve information about the currently configured certificate and available suitable certificates. Returns a summary indicating whether the configured certificate is valid for the minimum required days and whether any suitable certificates are available. With the Thumbprint parameter (Way Two): Executes detailed certificate validation tests on the target machine to determine if the specified certificate is suitable for SQL Server network encryption. Returns individual test results for each requirement, making it easy to identify which specific tests failed. The certificate validation logic is aligned with Get-DbaNetworkConfiguration to ensure consistent behavior. For details on certificate requirements, see https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/certificate-requirements Syntax Test-DbaNetworkCertificate [-SqlInstance] [[-Credential] ] [[-Thumbprint] ] [[-MinimumValidDays] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Tests the configured network certificate for the default instance on sql2019 PS C:\\> Test-DbaNetworkCertificate -SqlInstance sql2019 Tests the configured network certificate for the default instance on sql2019. Returns whether the configured certificate is valid and whether suitable certificates are available. Example 2: Tests the network certificate configuration for sql2019, requiring certificates to be valid for at least 30... PS C:\\> Test-DbaNetworkCertificate -SqlInstance sql2019 -MinimumValidDays 30 Tests the network certificate configuration for sql2019, requiring certificates to be valid for at least 30 more days. Example 3: Tests whether the certificate with the given thumbprint is suitable for SQL Server network encryption on... PS C:\\> Test-DbaNetworkCertificate -SqlInstance sql2019 -Thumbprint 1223FB1ACBCA44D3EE9640F81B6BA14A92F3D6E2 Tests whether the certificate with the given thumbprint is suitable for SQL Server network encryption on sql2019. Returns detailed test results for each requirement. Example 4: Tests whether the certificate is suitable for sql2019 and will remain valid for at least 30 days PS C:\\> Test-DbaNetworkCertificate -SqlInstance sql2019 -Thumbprint 1223FB1ACBCA44D3EE9640F81B6BA14A92F3D6E2 -MinimumValidDays 30 Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential Credential object used to connect to the Computer as a different user. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Thumbprint The thumbprint of a specific certificate to test for suitability (Way Two). When specified, the command performs detailed validation of that certificate and returns individual test results for each requirement. When omitted, the command checks the configured certificate and available suitable certificates using Get-DbaNetworkConfiguration (Way One). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -MinimumValidDays The minimum number of days the certificate must be valid from today. A certificate expiring within fewer than this many days will not be considered valid. Defaults to 0, meaning the certificate just needs to be currently valid. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Without -Thumbprint (Way One), returns one object per instance with: ComputerName: Computer name of the SQL Server instance InstanceName: SQL Server instance name SqlInstance: Full SQL Server instance name (computer\\instance format) ConfiguredCertificateValid: Boolean indicating if the configured certificate is valid for at least MinimumValidDays ConfiguredCertificateThumbprint: Thumbprint of the configured certificate, or $null if none is configured ConfiguredCertificateExpires: Expiration date of the configured certificate, or $null if none is configured ConfiguredCertificateDaysValid: Number of days until the configured certificate expires, or $null if none is configured SuitableCertificateAvailable: Boolean indicating if at least one suitable certificate is available for the minimum valid days SuitableCertificateCount: Number of suitable certificates available for the minimum valid days SuitableCertificates: Array of suitable certificate objects (Thumbprint, FriendlyName, NotBefore, NotAfter, DaysValid) With -Thumbprint (Way Two), returns one object per instance with: ComputerName: Computer name of the SQL Server instance InstanceName: SQL Server instance name SqlInstance: Full SQL Server instance name (computer\\instance format) Thumbprint: The thumbprint of the tested certificate IsSuitable: Boolean indicating if the certificate passes all validation tests CertificateFound: Boolean indicating if the certificate was found in LocalMachine\\My KeyUsagesValid: Boolean indicating if the certificate has the required key usages (DigitalSignature and KeyEncipherment) DnsNamesValid: Boolean indicating if the certificate's DNS names include the server's network name PrivateKeyValid: Boolean indicating if the private key is RSACryptoServiceProvider with KeyNumber Exchange PublicKeyValid: Boolean indicating if the public key is RSA with at least 2048 bits SignatureAlgorithmValid: Boolean indicating if the signature algorithm is SHA-256, SHA-384, or SHA-512 EnhancedKeyUsageValid: Boolean indicating if the certificate has the Server Authentication enhanced key usage ValidityPeriodOk: Boolean indicating if the certificate is currently valid and valid for at least MinimumValidDays KeyUsages: The actual key usage flags value DnsNames: Array of DNS names from the certificate PrivateKeyType: Full type name of the private key object PrivateKeyNumber: Key number from the CspKeyContainerInfo PublicKeySize: Public key size in bits PublicKeyAlgorithm: Public key algorithm friendly name SignatureAlgorithm: Signature algorithm friendly name EnhancedKeyUsageList: Array of enhanced key usage friendly names NotBefore: Certificate validity start date NotAfter: Certificate validity end date (expiration) DaysValid: Number of days until the certificate expires &nbsp;"
  },
  {
    "name": "Test-DbaNetworkLatency",
    "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.",
    "category": "Utilities",
    "tags": [
      "performance",
      "network"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaNetworkLatency",
    "popularityRank": 216,
    "synopsis": "Tests how long a query takes to return from SQL Server",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaNetworkLatency View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests how long a query takes to return from SQL Server 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. By 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. This allows you to see if the issue is with the connection or the SQL Server itself. Syntax Test-DbaNetworkLatency [-SqlInstance] [[-SqlCredential] ] [[-Query] ] [[-Count] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Tests the round trip return of &quot;SELECT TOP 100 FROM INFORMATION_SCHEMA.TABLES&quot; on sqlserver2014a and... PS C:\\> Test-DbaNetworkLatency -SqlInstance sqlserver2014a, sqlcluster Tests the round trip return of \"SELECT TOP 100 FROM INFORMATION_SCHEMA.TABLES\" on sqlserver2014a and sqlcluster using Windows credentials. Example 2: Tests the execution results return of &quot;SELECT TOP 100 FROM INFORMATION_SCHEMA.TABLES&quot; on sqlserver2014a... PS C:\\> Test-DbaNetworkLatency -SqlInstance sqlserver2014a -SqlCredential $cred Tests the execution results return of \"SELECT TOP 100 FROM INFORMATION_SCHEMA.TABLES\" on sqlserver2014a using SQL credentials. Example 3: Tests the execution results return of &quot;select top 10 from otherdb.dbo.table&quot; 10 times on sqlserver2014a... PS C:\\> Test-DbaNetworkLatency -SqlInstance sqlserver2014a, sqlcluster, sqlserver -Query \"select top 10 from otherdb.dbo.table\" -Count 10 Tests the execution results return of \"select top 10 from otherdb.dbo.table\" 10 times on sqlserver2014a, sqlcluster, and sqlserver using Windows credentials. Required Parameters -SqlInstance The SQL Server you want to run the test on. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. Increase 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 3 | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance queried, with latency measurements comparing total time vs. query execution time to isolate network delays. Default display properties (via Select-DefaultView): ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) ExecutionCount: The number of times the query was executed (same as -Count parameter) Total: Total elapsed time for all executions (including connection and network overhead) Average: Average elapsed time per query execution ExecuteOnlyTotal: Total time spent in query execution only (excluding network overhead) ExecuteOnlyAverage: Average query execution time per iteration NetworkOnlyTotal: Time spent on network latency and connection overhead All time properties are returned as prettytimespan objects that display in human-readable format (ms, sec, etc.). The 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 Server instance itself. &nbsp;"
  },
  {
    "name": "Test-DbaOptimizeForAdHoc",
    "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.",
    "category": "Utilities",
    "tags": [
      "configure",
      "spconfigure"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaOptimizeForAdHoc",
    "popularityRank": 446,
    "synopsis": "Tests whether the SQL Server \"optimize for ad-hoc workloads\" configuration setting is enabled.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaOptimizeForAdHoc View Source Brandon Abshire, netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests whether the SQL Server \"optimize for ad-hoc workloads\" configuration setting is enabled. 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. More info: https://msdn.microsoft.com/en-us/library/cc645587.aspx http://www.sqlservercentral.com/blogs/glennberry/2011/02/25/some-suggested-sql-server-2008-r2-instance-configuration-settings/ These are just general recommendations for SQL Server and are a good starting point for setting the \"optimize for ad-hoc workloads\" option. Syntax Test-DbaOptimizeForAdHoc [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Validates whether Optimize for AdHoc Workloads setting is enabled for servers sql2008 and sqlserver2012 PS C:\\> Test-DbaOptimizeForAdHoc -SqlInstance sql2008, sqlserver2012 Required Parameters -SqlInstance A collection of one or more SQL Server instance names to query. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per SQL Server instance queried, with configuration details and recommendations. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) CurrentOptimizeAdHoc: Current value of the optimize for ad-hoc workloads setting (0 or 1, where 1 is enabled) RecommendedOptimizeAdHoc: The recommended value for this setting (always 1 for enabled) Notes: Guidance message indicating if the setting is optimally configured or needs adjustment &nbsp;"
  },
  {
    "name": "Test-DbaPath",
    "description": "Verifies file and directory accessibility from SQL Server's 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's security context, which may differ from your user account's permissions. Returns detailed information about file existence and whether the path is a container (directory).",
    "category": "Utilities",
    "tags": [
      "storage",
      "path",
      "directory"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaPath",
    "popularityRank": 285,
    "synopsis": "Tests if files or directories are accessible to the SQL Server service account.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaPath View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests if files or directories are accessible to the SQL Server service account. Description Verifies file and directory accessibility from SQL Server's 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's security context, which may differ from your user account's permissions. Returns detailed information about file existence and whether the path is a container (directory). Syntax Test-DbaPath [-SqlInstance] [[-SqlCredential] ] [-Path] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Tests whether the service account running the &quot;sqlcluster&quot; SQL Server instance can access... PS C:\\> Test-DbaPath -SqlInstance sqlcluster -Path L:\\MSAS12.MSSQLSERVER\\OLAP Tests whether the service account running the \"sqlcluster\" SQL Server instance can access L:\\MSAS12.MSSQLSERVER\\OLAP. Logs into sqlcluster using Windows credentials. Example 2: Tests whether the service account running the &quot;sqlcluster&quot; SQL Server instance can access... PS C:\\> $credential = Get-Credential PS C:\\> Test-DbaPath -SqlInstance sqlcluster -SqlCredential $credential -Path L:\\MSAS12.MSSQLSERVER\\OLAP Tests whether the service account running the \"sqlcluster\" SQL Server instance can access L:\\MSAS12.MSSQLSERVER\\OLAP. Logs into sqlcluster using SQL authentication. Required Parameters -SqlInstance The SQL Server you want to run the test on. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Path Specifies the file or directory paths to test for accessibility from the SQL Server service account's perspective. Accepts single paths, arrays of paths, or pipeline input. Use this to verify SQL Server can access backup destinations, restore source files, or any location needed for database operations. Critical for pre-validating paths before backup, restore, or bulk operations that would otherwise fail with access denied errors. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs System.Boolean (when testing a single path on a single instance) Returns $true if the file or directory is accessible to the SQL Server service account, $false otherwise. PSCustomObject (when testing multiple paths, multiple instances, or array input) Returns one object per file or directory path tested, with the following properties: SqlInstance: Full instance name (computer\\instance format) InstanceName: The SQL Server instance name ComputerName: The computer name hosting the SQL Server instance FilePath: The file or directory path that was tested FileExists: Boolean indicating if the file or directory exists and is accessible IsContainer: Boolean indicating if the path is a directory (container) rather than a file Note: FileExists is true if either the file exists OR the path is a container (directory). IsContainer specifically identifies if it's a directory. &nbsp;"
  },
  {
    "name": "Test-DbaPowerPlan",
    "description": "Audits Windows Power Plan settings on SQL Server hosts to ensure compliance with Microsoft's 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/",
    "category": "Performance",
    "tags": [
      "powerplan",
      "os",
      "utility"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaPowerPlan",
    "popularityRank": 425,
    "synopsis": "Tests Windows Power Plan settings against SQL Server best practices and identifies non-compliant systems.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaPowerPlan View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests Windows Power Plan settings against SQL Server best practices and identifies non-compliant systems. Description Audits Windows Power Plan settings on SQL Server hosts to ensure compliance with Microsoft's performance recommendations. SQL Server runs optimally with the \"High Performance\" power plan, which prevents CPU throttling and ensures consistent performance under load. This 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. Returns 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. If your organization uses a different Power Plan that is considered best practice, specify -PowerPlan to test against that instead. References: https://support.microsoft.com/en-us/kb/2207548 http://www.sqlskills.com/blogs/glenn/windows-power-plan-effects-on-newer-intel-processors/ Syntax Test-DbaPowerPlan [-ComputerName] [[-Credential] ] [[-PowerPlan] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Checks the Power Plan settings for sqlserver2014a and indicates whether or not it complies with best... PS C:\\> Test-DbaPowerPlan -ComputerName sqlserver2014a Checks the Power Plan settings for sqlserver2014a and indicates whether or not it complies with best practices. Example 2: Checks the Power Plan settings for sqlserver2014a and indicates whether or not it is set to the Power Plan... PS C:\\> Test-DbaPowerPlan -ComputerName sqlserver2014a -PowerPlan 'Maximum Performance' Checks the Power Plan settings for sqlserver2014a and indicates whether or not it is set to the Power Plan \"Maximum Performance\". Example 3: Checks the Power Plan settings for newserver1 and newserver2 and indicates whether or not they comply with... PS C:\\> 'newserver1', 'newserver2' | Test-DbaPowerPlan Checks the Power Plan settings for newserver1 and newserver2 and indicates whether or not they comply with best practices. Example 4: Uses the Power Plan of oldserver as best practice and tests the Power Plan of newserver1 and newserver2... PS C:\\> Get-DbaPowerPlan -ComputerName oldserver | Test-DbaPowerPlan -ComputerName newserver1, newserver2 Uses the Power Plan of oldserver as best practice and tests the Power Plan of newserver1 and newserver2 against that. Required Parameters -ComputerName Specifies the SQL Server host(s) where you want to test Windows Power Plan compliance. Accepts server names, IP addresses, or DbaInstance objects. Use this to audit power settings across your SQL Server environment, especially important for performance-critical instances where CPU throttling can impact query response times. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue, ByPropertyName) | | Default Value | | Optional Parameters -Credential Specifies a PSCredential object to use in authenticating to the server(s), instead of the current user account. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -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. Useful 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. | Property | Value | | --- | --- | | Alias | CustomPowerPlan | | Required | False | | Pipeline | true (ByPropertyName) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns one object per computer tested with power plan compliance information. Default display properties (via Select-DefaultView): ComputerName: The target computer name ActivePowerPlan: Name of the currently active Windows Power Plan RecommendedPowerPlan: Name of the recommended power plan (High Performance by default, or custom if -PowerPlan specified) IsBestPractice: Boolean indicating if the active power plan matches the recommended plan Additional properties available: ActiveInstanceId: UUID of the currently active power plan RecommendedInstanceId: UUID of the recommended power plan Credential: The PSCredential object used for authentication If 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.\" &nbsp;"
  },
  {
    "name": "Test-DbaReplLatency",
    "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",
    "category": "Utilities",
    "tags": [
      "replication"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaReplLatency",
    "popularityRank": 559,
    "synopsis": "Measures transactional replication latency using tracer tokens across publisher, distributor, and subscriber instances.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaReplLatency View Source Colin Douglas Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Measures transactional replication latency using tracer tokens across publisher, distributor, and subscriber instances. 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. The 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. This is particularly useful when troubleshooting slow replication, validating replication performance after configuration changes, or establishing baseline performance metrics for replication monitoring. All replication commands need SQL Server Management Studio installed and are therefore currently not supported. Have a look at this issue to get more information: https://github.com/dataplat/dbatools/issues/7428 Syntax Test-DbaReplLatency [-SqlInstance] [[-Database] ] [[-SqlCredential] ] [[-PublicationName] ] [[-TimeToLive] ] [-RetainToken] [-DisplayTokenHistory] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Return replication latency for all transactional publications for servers sql2008 and sqlserver2012 PS C:\\> Test-DbaReplLatency -SqlInstance sql2008, sqlserver2012 Example 2: Return replication latency for all transactional publications on server sql2008 for only the TestDB database PS C:\\> Test-DbaReplLatency -SqlInstance sql2008 -Database TestDB Example 3: Return replication latency for the TestDB_Pub publication for the TestDB database located on the server... PS C:\\> Test-DbaReplLatency -SqlInstance sql2008 -Database TestDB -PublicationName TestDB_Pub Return replication latency for the TestDB_Pub publication for the TestDB database located on the server sql2008. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Database Specifies which databases containing transactional replication publications to test for latency. Accepts wildcards for pattern matching. Use this when you need to focus on specific publication databases instead of testing all replicated databases on the instance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PublicationName Specifies which transactional replication publications to test for latency. Accepts wildcards for pattern matching. Use this when you need to test specific publications instead of all transactional publications in the specified databases. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -TimeToLive Sets the maximum time in seconds to wait for tracer tokens to travel from publisher through distributor to all subscribers. Use 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 next publication. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 0 | -RetainToken Keeps the tracer tokens in the distribution database after latency testing is complete instead of automatically cleaning them up. Use 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. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -DisplayTokenHistory Shows latency measurements for all existing tracer tokens in each publication instead of just the newly created token. Use this to see historical latency patterns and trends for ongoing replication monitoring. Without this switch, only the current test token results are displayed. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 data. Each object represents the latency measurements for one tracer token's journey from publisher to a specific subscriber database. Properties: ComputerName (string): The name of the computer hosting the publisher SQL Server instance InstanceName (string): The SQL Server instance name of the publisher SqlInstance (string): The full SQL Server instance name of the publisher (computer\\instance format) TokenID (int): Unique identifier for the tracer token within the publication TokenCreateDate (datetime): The date and time when the tracer token was created and inserted into the publication transaction log PublicationServer (string): The name of the publisher SQL Server instance PublicationDB (string): The name of the database containing the transactional replication publication PublicationName (string): The name of the transactional replication publication PublicationType (string): The type of replication publication (Transactional, Merge, or Snapshot) DistributionServer (string): The name of the distributor SQL Server instance DistributionDB (string): The name of the distribution database on the distributor SubscriberServer (string): The name of the subscriber SQL Server instance receiving the replicated data SubscriberDB (string): The name of the subscription database on the subscriber 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 recorded 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 subscriber TotalLatency (timespan or DBNull): Combined latency (PublisherToDistributorLatency + DistributorToSubscriberLatency); DBNull if either component latency is not yet available &nbsp;"
  },
  {
    "name": "Test-DbaSpn",
    "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's configuration. For instances with TCP/IP enabled, it determines which ports they're 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's 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.",
    "category": "Server Management",
    "tags": [
      "spn"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaSpn",
    "popularityRank": 54,
    "synopsis": "Validates Service Principal Name (SPN) configuration for SQL Server instances by comparing required SPNs against Active Directory registrations",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaSpn View Source Drew Furgiuele (@pittfurg), port1433.com , niphlod Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates Service Principal Name (SPN) configuration for SQL Server instances by comparing required SPNs against Active Directory registrations 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. The function performs a complete SPN audit by first discovering all SQL Server instances via WMI, then generating the required SPNs based on each instance's configuration. For instances with TCP/IP enabled, it determines which ports they're 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. After 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. The 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's service account, required SPNs, registration status, and any configuration warnings. Use 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. Syntax Test-DbaSpn [-ComputerName] [[-Credential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Connects to a computer (SQLSERVERA) and queries WMI for all SQL instances and return &quot;required&quot; SPNs PS C:\\> Test-DbaSpn -ComputerName SQLSERVERA -Credential ad\\sqldba Connects to a computer (SQLSERVERA) and queries WMI for all SQL instances and return \"required\" SPNs. It will then take each SPN it generates and query Active Directory to make sure the SPNs are set. Example 2: Connects to multiple computers (SQLSERVERA, SQLSERVERB) and queries WMI for all SQL instances and return... PS C:\\> Test-DbaSpn -ComputerName SQLSERVERA,SQLSERVERB -Credential ad\\sqldba Connects to multiple computers (SQLSERVERA, SQLSERVERB) and queries WMI for all SQL instances and return \"required\" SPNs. It will then take each SPN it generates and query Active Directory to make sure the SPNs are set. Example 3: Connects to a computer (SQLSERVERC) on a specified and queries WMI for all SQL instances and return... PS C:\\> Test-DbaSpn -ComputerName SQLSERVERC -Credential ad\\sqldba Connects to a computer (SQLSERVERC) on a specified and queries WMI for all SQL instances and return \"required\" SPNs. It 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 Required Parameters -ComputerName Specifies the target computer(s) to scan for SQL Server instances and validate their SPN configuration. Accepts computer names, IP addresses, or fully qualified domain names and supports pipeline input for bulk operations. The function will discover all SQL Server instances on each specified computer and check their required SPNs against Active Directory. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -Credential The credential you want to use to connect to the remote server and active directory. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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 be returned per instance. Properties: ComputerName (string): The name of the computer (or cluster virtual name for clustered instances) where the SQL Server instance is running InstanceName (string): The name of the SQL Server instance (MSSQLSERVER for default instance, or the named instance name) SqlProduct (string): The SQL Server product version and edition information (e.g., \"15.0.2154.1 Enterprise Edition\") 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\") 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) IsSet (boolean): Boolean indicating whether the required SPN is currently registered in Active Directory under the service account Cluster (boolean): Boolean indicating whether this is a clustered SQL Server instance TcpEnabled (boolean): Boolean indicating whether TCP/IP protocol is enabled for this instance (instances without TCP/IP don't require SPNs) Port (string or null): The port number on which this instance is listening (null if using default 1433 or if TCP is disabled) DynamicPort (boolean): Boolean indicating whether this instance is using dynamic port assignment (port changes at each startup) Warning (string): Warning message about the SPN configuration (e.g., \"Dynamic port is enabled\" or \"None\") Error (string): Error message if the SPN configuration is invalid (e.g., \"SPN missing\" or \"None\") &nbsp;"
  },
  {
    "name": "Test-DbaTempDbConfig",
    "description": "Performs a comprehensive audit of tempdb configuration against Microsoft's 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't 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.",
    "category": "Utilities",
    "tags": [
      "tempdb",
      "configuration"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaTempDbConfig",
    "popularityRank": 174,
    "synopsis": "Tests tempdb configuration against SQL Server best practices and returns compliance status for each rule.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Test-DbaTempDbConfig View Source Michael Fal (@Mike_Fal), mikefal.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Tests tempdb configuration against SQL Server best practices and returns compliance status for each rule. Description Performs a comprehensive audit of tempdb configuration against Microsoft's 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. The function evaluates six critical areas of tempdb configuration: TF 1118 enabled - Is Trace Flag 1118 enabled (See KB328551). File Count - Does the count of data files in tempdb match the number of logical cores, up to 8? File Growth - Are any files set to have percentage growth? Best practice is all files have an explicit growth value. File Location - Is tempdb located on the C:\\? Best practice says to locate it elsewhere. File MaxSize Set (optional) - Do any files have a max size value? Max size could cause tempdb problems if it isn't allowed to grow. Data File Size Equal - Are the sizes of all the tempdb data files the same? Each 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. Syntax Test-DbaTempDbConfig [-SqlInstance] [[-SqlCredential] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Checks tempdb on the localhost machine PS C:\\> Test-DbaTempDbConfig -SqlInstance localhost Example 2: Checks tempdb on the localhost machine PS C:\\> Test-DbaTempDbConfig -SqlInstance localhost | Select-Object Checks tempdb on the localhost machine. All rest results are shown. Example 3: Checks tempdb configuration for a group of servers from SQL Server Central Management Server (CMS) PS C:\\> Get-DbaRegServer -SqlInstance sqlserver2014a | Test-DbaTempDbConfig | Select-Object | Out-GridView Checks tempdb configuration for a group of servers from SQL Server Central Management Server (CMS). Output includes all columns. Send output to GridView. Required Parameters -SqlInstance The target SQL Server instance or instances. SQL Server 2005 and higher are supported. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Properties (consistent across all 6 rule objects): ComputerName: The computer name hosting the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Rule: The name of the configuration rule being evaluated (string): \"TF 1118 Enabled\" - Trace Flag 1118 status for proportional fill algorithm \"File Count\" - Number of tempdb data files compared to recommended count \"File Growth in Percent\" - Whether any files use percentage-based growth (should be KB-based) \"File Location\" - Whether any files are located on C:\\ drive \"File MaxSize Set\" - Whether any files have maximum size limits set \"Data File Size Equal\" - Whether all tempdb data files are equally sized Recommended: The recommended value for this rule (bool or int): Integer for \"File Count\" rule (recommended = min(8, processor count)) Boolean false for \"File Growth in Percent\", \"File Location\", \"File MaxSize Set\" Boolean true for \"TF 1118 Enabled\" (SQL 2012 and below) or false (SQL 2016+) Boolean true for \"Data File Size Equal\" CurrentSetting: The actual current value on this instance (bool or int): Integer for \"File Count\" rule (actual count of tempdb data files) Boolean for all other rules IsBestPractice: Boolean indicating whether the current setting meets Microsoft's best practice recommendations Notes: Explanatory text describing the rule and recommendations All properties are accessible using Select-Object *. &nbsp;"
  },
  {
    "name": "Test-DbaWindowsLogin",
    "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.",
    "category": "Security",
    "tags": [
      "login"
    ],
    "verb": "Test",
    "popular": false,
    "url": "/Test-DbaWindowsLogin",
    "popularityRank": 196,
    "synopsis": "Validates Windows logins and groups in SQL Server against Active Directory to identify orphaned, disabled, or problematic accounts",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Test-DbaWindowsLogin View Source Stephen Bennett, sqlnotesfromtheunderground.wordpress.com , Chrissy LeMaire (@cl) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Validates Windows logins and groups in SQL Server against Active Directory to identify orphaned, disabled, or problematic accounts 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. Syntax Test-DbaWindowsLogin [[-SqlInstance] ] [[-SqlCredential] ] [[-Login] ] [[-ExcludeLogin] ] [[-FilterBy] ] [[-IgnoreDomains] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Tests all logins in the current Active Directory domain that are either disabled or do not exist on the SQL... PS C:\\> Test-DbaWindowsLogin -SqlInstance Dev01 Tests all logins in the current Active Directory domain that are either disabled or do not exist on the SQL Server instance Dev01 Example 2: Tests all Active Directory groups that have logins on Dev01, and shows all information for those logins PS C:\\> Test-DbaWindowsLogin -SqlInstance Dev01 -FilterBy GroupsOnly | Select-Object -Property Example 3: Tests all Domain logins excluding any that are from the testdomain PS C:\\> Test-DbaWindowsLogin -SqlInstance Dev01 -IgnoreDomains testdomain Example 4: Tests only the login returned by Get-DbaLogin PS C:\\> Get-DbaLogin -SqlInstance Dev01 -Login DOMAIN\\User | Test-DbaWindowsLogin Optional Parameters -SqlInstance The SQL Server instance you're checking logins on. You must have sysadmin access and server version must be SQL Server version 2000 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Accepts wildcards and multiple values. Helpful for focused security audits of high-privilege accounts or problem logins. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ExcludeLogin Excludes specific Windows logins from validation checks. Use this to skip service accounts or known system logins that you don't need to audit. Accepts wildcards and multiple values. Common exclusions include application service accounts and break-glass emergency accounts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -FilterBy Limits validation to either individual user accounts or Active Directory groups. Use 'LoginsOnly' when auditing user access or 'GroupsOnly' when reviewing group-based permissions. Default of 'None' validates both types. GroupsOnly is useful for reviewing role-based access control implementation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | None | | Accepted Values | 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. Helpful when you have old domain trusts or want to audit only production domains while excluding development or test domains. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Enables powerful filtering scenarios by piping pre-filtered login objects instead of processing all Windows logins on the server. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject Returns 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. Windows User and Computer Account Properties: Server: Full SQL Server instance name (computer\\instance) Domain: Active Directory domain name Login: Windows login username Type: Account type - either \"User\" or \"Computer\" Found: Boolean indicating whether the account exists in Active Directory SamAccountNameMismatch: Boolean indicating whether the SAM account name differs between SQL Server and AD DisabledInSQLServer: Boolean indicating whether the login is disabled in SQL Server Enabled: Boolean indicating whether the account is enabled in Active Directory (null for groups) AccountNotDelegated: Boolean indicating whether the account is marked as non-delegated LockedOut: Boolean indicating whether the account is currently locked out PasswordExpired: Boolean indicating whether the password has expired PasswordNeverExpires: Boolean indicating whether the password is set to never expire PasswordNotRequired: Boolean indicating whether a password is required for the account CannotChangePassword: Boolean indicating whether the user account is password-change protected AllowReversiblePasswordEncryption: Boolean indicating whether reversible password encryption is allowed SmartcardLogonRequired: Boolean indicating whether smartcard logon is required TrustedForDelegation: Boolean indicating whether the account is trusted for delegation UserAccountControl: Raw integer UserAccountControl value from Active Directory Windows Group Account Properties: Server, Domain, Login, Type, Found, SamAccountNameMismatch, DisabledInSQLServer: Same as above All security properties (Enabled, AccountNotDelegated, LockedOut, etc.): null for group accounts Default display properties (via Select-DefaultView): Server, Domain, Login, Type, Found, SamAccountNameMismatch, DisabledInSQLServer All properties are accessible using Select-Object . &nbsp;"
  },
  {
    "name": "Uninstall-DbaSqlWatch",
    "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.",
    "category": "Utilities",
    "tags": [
      "community",
      "sqlwatch"
    ],
    "verb": "Uninstall",
    "popular": false,
    "url": "/Uninstall-DbaSqlWatch",
    "popularityRank": 449,
    "synopsis": "Completely removes SqlWatch monitoring solution from a SQL Server instance",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Uninstall-DbaSqlWatch View Source Ken K (github.com/koglerk) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Completely removes SqlWatch monitoring solution from a SQL Server instance 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. Syntax Uninstall-DbaSqlWatch [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Deletes all user objects, agent jobs, and historical data associated with SqlWatch from the master database PS C:\\> Uninstall-DbaSqlWatch -SqlInstance server1 Required Parameters -SqlInstance SQL Server name or SMO object representing the SQL Server to connect to. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database containing the SqlWatch installation to remove. Defaults to master. Use this when SqlWatch was installed in a database other than the default master database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | master | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts to confirm actions | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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 sessions, Service Broker components, and other related resources from the specified SQL Server instance. &nbsp;"
  },
  {
    "name": "Unregister-DbatoolsConfig",
    "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.",
    "category": "Utilities",
    "tags": [
      "module"
    ],
    "verb": "Unregister",
    "popular": false,
    "url": "/Unregister-DbatoolsConfig",
    "popularityRank": 641,
    "synopsis": "Removes persisted dbatools configuration settings from registry and configuration files.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Unregister-DbatoolsConfig View Source Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Removes persisted dbatools configuration settings from registry and configuration files. 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. The 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. Note: This command only removes persisted settings and has no effect on configuration values currently loaded in PowerShell memory. Syntax Unregister-DbatoolsConfig [-ConfigurationItem ] [-FullName ] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [ ] Unregister-DbatoolsConfig -Module [-Name ] [-Scope {UserDefault | UserMandatory | SystemDefault | SystemMandatory | FileUserLocal | FileUserShared | FileSystem}] [ ] &nbsp; Examples &nbsp; Example 1: Completely removes all registered configurations currently loaded in memory PS C:\\> Get-DbatoolsConfig | Unregister-DbatoolsConfig Completely removes all registered configurations currently loaded in memory. In most cases, this will mean removing all registered configurations. Example 2: Unregisters the setting &#39;MyModule.Path.DefaultExport&#39; from the list of computer-wide defaults PS C:\\> Unregister-DbatoolsConfig -Scope SystemDefault -FullName 'MyModule.Path.DefaultExport' Unregisters the setting 'MyModule.Path.DefaultExport' from the list of computer-wide defaults. Note: Changing system wide settings requires running the console with elevation. Example 3: Unregisters all configuration settings for the module MyModule PS C:\\> Unregister-DbatoolsConfig -Module MyModule Required Parameters -Module Specifies the module name to target for configuration removal. Use this to remove all configuration settings belonging to a specific dbatools module or component. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -ConfigurationItem Specifies configuration objects to remove from persistent storage, as returned by Get-DbatoolsConfig. Use this when you want to unregister specific settings already identified through Get-DbatoolsConfig. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -FullName Specifies the complete name of the configuration setting to remove from persistent storage. Use this when you know the exact setting name in the format 'module.category.setting'. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -Name Specifies the setting name pattern to match within the targeted module. Supports wildcards. Use with the Module parameter to narrow down which settings to remove, defaults to '' to match all settings. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Scope Specifies which configuration storage locations to target for removal: user settings, computer-wide settings, or file-based configurations. Defaults to UserDefault which removes settings from the current user's registry. Use SystemDefault to remove computer-wide settings (requires elevation). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | UserDefault | Outputs None This command does not return any output objects. It removes persisted configuration settings from registry and configuration files based on the specified parameters. &nbsp;"
  },
  {
    "name": "Update-DbaBuildReference",
    "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 'assets.sqlbuildreference' to see the current download URL.",
    "category": "Utilities",
    "tags": [
      "utility",
      "sqlbuild"
    ],
    "verb": "Update",
    "popular": false,
    "url": "/Update-DbaBuildReference",
    "popularityRank": 111,
    "synopsis": "Downloads the latest SQL Server build reference database used for patch compliance and version tracking",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Update-DbaBuildReference View Source Simone Bizzotto (@niphold) , Friedrich Weinmann (@FredWeinmann) Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Downloads the latest SQL Server build reference database used for patch compliance and version tracking 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. DBAs 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. The 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. Use Get-DbatoolsConfigValue -Name 'assets.sqlbuildreference' to see the current download URL. Syntax Update-DbaBuildReference [[-LocalFile] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Looks online if there is a newer version of the build reference PS C:\\> Update-DbaBuildReference Example 2: Uses the given file instead of downloading the file to update the build reference PS C:\\> Update-DbaBuildReference -LocalFile \\\\fileserver\\Software\\dbatools\\dbatools-buildref-index.json Optional Parameters -LocalFile Specifies the path to a local JSON build reference file to use instead of downloading from the internet. Use this in air-gapped environments or when you need to use a specific version of the build reference data. The file must be the dbatools-buildref-index.json format containing SQL Server build mappings and patch information. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs None This 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 updates. The function modifies files on disk: If the reference file needs updating, it writes the new version to the writable location (typically in the dbatools data directory) Messages are written to indicate the update timestamp comparison and result To track the update result, capture Write-Message output or monitor the exit status of the command. &nbsp;"
  },
  {
    "name": "Update-DbaInstance",
    "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'ing 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 'commands.initialize-credssp.bypass' to $true. CredSSP configuration requires running from an elevated PowerShell session.\n\nAlways backup databases and configurations before applying any SQL Server updates.",
    "category": "Server Management",
    "tags": [
      "deployment",
      "install",
      "patching",
      "update"
    ],
    "verb": "Update",
    "popular": true,
    "url": "/Update-DbaInstance",
    "popularityRank": 16,
    "synopsis": "Installs SQL Server Service Packs and Cumulative Updates across local and remote instances automatically.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Update-DbaInstance View Source Kirill Kravtsov (@nvarscar), nvarscar.wordpress.com Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Installs SQL Server Service Packs and Cumulative Updates across local and remote instances automatically. 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. The patching process includes: Discovering all SQL Server instances on target computers via registry scanning Validating current versions against target update requirements Locating appropriate KB installers in your patch repository Establishing secure remote connections using CredSSP or other protocols Extracting and executing patches from temporary directories Managing restarts and chaining multiple updates when needed Cleaning up temporary files after installation Processing multiple computers in parallel for faster deployment This replaces the manual process of RDP'ing 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. The impact of this function is set to High. Use -Confirm:$false to suppress interactive prompts for automated deployments. For CredSSP authentication, the function automatically configures PowerShell remoting when credentials are provided. This can be disabled by setting dbatools configuration 'commands.initialize-credssp.bypass' to $true. CredSSP configuration requires running from an elevated PowerShell session. Always backup databases and configurations before applying any SQL Server updates. Syntax Update-DbaInstance [[-ComputerName] ] [-Credential ] [-Version ] [-Type ] [-InstanceName ] [-Path ] [-Restart] [-Continue] [-Throttle ] [-Authentication ] [-UseSSL] [-Port ] [-ExtractPath ] [-ArgumentList ] [-Download] [-NoPendingRenameCheck] [-EnableException] [-WhatIf] [-Confirm] [ ] Update-DbaInstance [[-ComputerName] ] [-Credential ] -KB [-InstanceName ] [-Path ] [-Restart] [-Continue] [-Throttle ] [-Authentication ] [-UseSSL] [-Port ] [-ExtractPath ] [-ArgumentList ] [-Download] [-NoPendingRenameCheck] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Updates all applicable SQL Server installations on SQL1 to SP3 PS C:\\> Update-DbaInstance -ComputerName SQL1 -Version SP3 -Path \\\\network\\share Updates all applicable SQL Server installations on SQL1 to SP3. Binary files for the update will be searched among all files and folders recursively in \\\\network\\share. Prompts for confirmation before the update. Example 2: Updates all applicable SQL Server installations on SQL1 and SQL2 with the most recent patch (that has at... PS C:\\> Update-DbaInstance -ComputerName SQL1, SQL2 -Restart -Path \\\\network\\share -Confirm:$false Updates all applicable SQL Server installations on SQL1 and SQL2 with the most recent patch (that has at least a \"CU\" flag). It will install latest ServicePack, restart the computers, install latest Cumulative Update, and finally restart the computer once again. Binary files for the update will be searched among all files and folders recursively in \\\\network\\share. Does not prompt for confirmation. Example 3: Updates SQL Server 2012 on SQL1 with the most recent ServicePack found in your patch repository PS C:\\> Update-DbaInstance -ComputerName SQL1 -Version 2012 -Type ServicePack -Path \\\\network\\share Updates SQL Server 2012 on SQL1 with the most recent ServicePack found in your patch repository. Binary files for the update will be searched among all files and folders recursively in \\\\network\\share. Prompts for confirmation before the update. Example 4: Installs KB 123456 on SQL1 and restarts the computer PS C:\\> Update-DbaInstance -ComputerName SQL1 -KB 123456 -Restart -Path \\\\network\\share -Confirm:$false Installs KB 123456 on SQL1 and restarts the computer. Binary files for the update will be searched among all files and folders recursively in \\\\network\\share. Does not prompt for confirmation. Example 5: Updates SQL 2012 to SP3 and SQL 2016 to SP2CU3 on Server1 PS C:\\> Update-DbaInstance -ComputerName Server1 -Version SQL2012SP3, SQL2016SP2CU3 -Path \\\\network\\share -Restart -Confirm:$false Updates SQL 2012 to SP3 and SQL 2016 to SP2CU3 on Server1. Each update will be followed by a restart. Binary files for the update will be searched among all files and folders recursively in \\\\network\\share. Does not prompt for confirmation. Example 6: Updates all applicable SQL Server installations on Server1 with the most recent patch PS C:\\> Update-DbaInstance -ComputerName Server1 -Path \\\\network\\share -Restart -Confirm:$false -ExtractPath \"C:\\temp\" Updates all applicable SQL Server installations on Server1 with the most recent patch. Each update will be followed by a restart. Binary files for the update will be searched among all files and folders recursively in \\\\network\\share. Does not prompt for confirmation. Extracts the files in local driver on Server1 C:\\temp. Example 7: Updates all applicable SQL Server installations on Server1 with the most recent patch PS C:\\> Update-DbaInstance -ComputerName Server1 -Path \\\\network\\share -ArgumentList \"/SkipRules=RebootRequiredCheck\" Updates all applicable SQL Server installations on Server1 with the most recent patch. Additional command line parameters would be passed to the executable. Binary files for the update will be searched among all files and folders recursively in \\\\network\\share. Example 8: Downloads an appropriate CU KB to \\\\network\\share and installs it onto SQL1 PS C:\\> Update-DbaInstance -ComputerName SQL1 -Version CU3 -Download -Path \\\\network\\share -Confirm:$false Downloads an appropriate CU KB to \\\\network\\share and installs it onto SQL1. Does not prompt for confirmation. Example 9: Updates SQL Server on db01.internal.local using SSL-encrypted WinRM connection on port 5986 PS C:\\> Update-DbaInstance -ComputerName \"db01.internal.local\" -Credential $cred -UseSSL -Port 5986 -Path \"\\\\fs01.internal.local\\SQL2022_Patch\\CU13\" Updates SQL Server on db01.internal.local using SSL-encrypted WinRM connection on port 5986. Requires the remote server to be configured for HTTPS WinRM (typically port 5986). Credentials are provided to access both the remote server and the network share containing patch files. Required Parameters -KB Installs a specific Knowledge Base update or list of updates by KB number. Use this when you need to apply a particular security patch or bug fix identified by Microsoft. Accepts formats like 123456 or KB123456, and supports multiple KB numbers for batch installations. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -ComputerName Target computer with SQL instance or instances. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | true (ByValue) | | Default Value | $env:COMPUTERNAME | -Credential Windows Credential with permission to log on to the remote server. Must be specified for any remote connection if update Repository is located on a network folder. Authentication will default to CredSSP if -Credential is used. For CredSSP see also additional information in DESCRIPTION. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Version Defines the target SQL Server version level to reach using pattern . Use this to standardize SQL Server instances to a specific patch level across your environment. Examples: 2008R2SP1 (SQL 2008R2 to SP1), 2016CU3 (SQL 2016 to CU3), SP1CU7 (all versions to SP1 then CU7). When omitted, installs the latest available patches for each detected SQL Server version. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Type Specifies which types of SQL Server updates to install: All, ServicePack, or CumulativeUpdate. Use this when you want to apply only specific update types, such as installing only Service Packs during maintenance windows. Defaults to All, which installs both Service Packs and Cumulative Updates in proper sequence. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @('All') | | Accepted Values | All,ServicePack,CumulativeUpdate | -InstanceName Limits patching to a specific named SQL Server instance on the target computer. Use this when you have multiple SQL instances and need to patch only one, such as updating a development instance while leaving production untouched. Omit this parameter to update all SQL Server instances found on the target computers. | Property | Value | | --- | --- | | Alias | Instance | | Required | False | | Pipeline | false | | Default Value | | -Path Specifies the folder path containing SQL Server update files for installation. Use this to point to your centralized patch repository where you store downloaded SQL Server updates. Files must follow Microsoft's naming pattern (SQLServer-KB-x*.exe) and path must be accessible from both client and target servers. Configure a default path with Set-DbatoolsConfig -Name Path.SQLServerUpdates to avoid specifying this repeatedly. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -Name 'Path.SQLServerUpdates') | -Restart Automatically restarts the server after successful patch installation and waits for it to come back online. Required for chaining multiple updates since SQL Server patches mandate a restart between installations. Use this during planned maintenance windows when you can afford server downtime for complete patch sequences. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Continue Resumes a previously failed SQL Server update installation from where it left off. Use this when a patch installation was interrupted due to network issues, timeouts, or other temporary failures. Without this switch, the function will abort and clean up any failed installation attempts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Throttle Controls the maximum number of servers that can be updated simultaneously during parallel operations. Use a lower value (5-10) for large production environments to limit network load and system resource usage. Defaults to 50, but consider your network bandwidth and the number of concurrent patch installations your infrastructure can handle. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 50 | -Authentication Specifies the PowerShell remoting authentication method for connecting to remote SQL Server hosts. Defaults to CredSSP when using -Credential to avoid double-hop authentication issues with network patch repositories. Use CredSSP when your patch files are stored on network shares that require credential delegation to remote servers. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | @('Credssp', 'Default')[$null -eq $Credential] | | Accepted Values | Default,Basic,Negotiate,NegotiateWithImplicitCredential,Credssp,Digest,Kerberos | -UseSSL Enables SSL encryption for PowerShell remoting connections to target servers. Use this when remote servers are configured to only accept encrypted WinRM connections (typically on port 5986). Defaults to the value configured in PSRemoting.PsSession.UseSSL configuration setting (false if not configured). Explicitly specifying this parameter overrides the configuration default. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -FullName \"PSRemoting.PsSession.UseSSL\" -Fallback $false) | -Port Specifies the WinRM port to use for PowerShell remoting connections. Common values: 5985 (standard HTTP), 5986 (HTTPS/SSL). Use this when remote servers have WinRM configured on non-standard ports or when using SSL. Defaults to the value configured in PSRemoting.PsSession.Port configuration setting (standard ports if not configured). Explicitly specifying this parameter overrides the configuration default. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (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. Use this to control where temporary installation files are placed, especially on servers with limited C: drive space. Defaults to system temporary directory if not specified, but consider using a dedicated drive with sufficient space. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ArgumentList Passes additional command-line parameters to the SQL Server patch installer executable. Use this to customize installation behavior such as skipping specific validation rules or running in quiet mode. Common examples include /SkipRules=RebootRequiredCheck to bypass reboot checks, or /Q for silent installation. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Download Automatically downloads missing SQL Server update files from Microsoft when they're not found in your patch repository. Use this to ensure patches are available during installation without manually downloading them beforehand. Files download to your local temp folder first, then get distributed to target servers or directly to network paths. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoPendingRenameCheck Bypasses the check for pending file rename operations that typically require a reboot before patching. Use this in environments where you're confident no pending renames exist or when system monitoring tools show false positives. Exercise caution as installing patches with pending renames can lead to installation failures. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (Get-DbatoolsConfigValue -Name 'OS.PendingRename' -Fallback $false) | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns one object per SQL Server instance updated, providing detailed information about the installation result and outcome. Properties: ComputerName (string) - The computer name of the target instance InstanceName (string) - The SQL Server instance name (MSSQLSERVER for default instance) MajorVersion (int) - The SQL Server major version number (2008, 2012, 2016, 2019, 2022, etc.) TargetLevel (string) - The target patch level that was applied (e.g., \"SP3CU15\") KB (string) - The Knowledge Base number of the update that was installed Installer (string) - Full path to the installer executable that was executed Successful (bool) - Boolean indicating whether the patch installation completed successfully Restarted (bool) - Boolean indicating whether the server was restarted after patching Notes (object[]) - Array of messages describing the installation process, any warnings, or errors encountered &nbsp;"
  },
  {
    "name": "Update-DbaMaintenanceSolution",
    "description": "Updates the stored procedures for Ola Hallengren's Maintenance Solution on SQL Server instances where it's 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's 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'll need to use Install-DbaMaintenanceSolution for a complete reinstallation instead.",
    "category": "Utilities",
    "tags": [
      "community",
      "olahallengren"
    ],
    "verb": "Update",
    "popular": false,
    "url": "/Update-DbaMaintenanceSolution",
    "popularityRank": 238,
    "synopsis": "Updates existing Ola Hallengren Maintenance Solution stored procedures to the latest version",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Update-DbaMaintenanceSolution View Source Andreas Jordan, @JordanOrdix Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Updates existing Ola Hallengren Maintenance Solution stored procedures to the latest version Description Updates the stored procedures for Ola Hallengren's Maintenance Solution on SQL Server instances where it's already installed. This function downloads the latest version from GitHub and replaces only the procedure code, leaving all existing tables, jobs, and configurations intact. Use 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's currently installed. This 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'll need to use Install-DbaMaintenanceSolution for a complete reinstallation instead. Syntax Update-DbaMaintenanceSolution [-SqlInstance] [[-SqlCredential] ] [[-Database] ] [[-Solution] ] [[-LocalFile] ] [-Force] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Updates Ola Hallengren&#39;s Solution objects on RES14224 in the DBA database PS C:\\> Update-DbaMaintenanceSolution -SqlInstance RES14224 -Database DBA Required Parameters -SqlInstance The target SQL Server instance onto which the Maintenance Solution will be updated. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | true (ByValue) | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the database containing the existing Ola Hallengren maintenance solution stored procedures. Defaults to master. Change this if you installed the maintenance solution in a different database like DBA or Admin. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | master | -Solution Controls which maintenance solution components to update. Valid options are All, Backup, IntegrityCheck, IndexOptimize, or CommandExecute. Use this when you only want to update specific procedures instead of the entire solution. Only procedures that already exist will be updated. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | All | | Accepted Values | All,Backup,IntegrityCheck,IndexOptimize,CommandExecute | -LocalFile Path to a local zip file containing Ola Hallengren's maintenance solution instead of downloading from GitHub. Use this in environments without internet access or when you need to deploy a specific version that differs from the latest release. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Force Forces download of the latest maintenance solution from GitHub even if a cached version exists locally. Use this when you want to ensure you're getting the absolute latest version or if the cached version is corrupted. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs PSCustomObject Returns 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 for each attempt. Properties: ComputerName: The computer name of the SQL Server instance InstanceName: The SQL Server instance name SqlInstance: The full SQL Server instance name (computer\\instance) Solution: The maintenance solution component name (CommandExecute, Backup, IntegrityCheck, or IndexOptimize) Procedure: The name of the stored procedure being updated IsUpdated: Boolean indicating if the procedure was successfully updated Results: Status or error message. Possible values: \"Updated\", \"Procedure not installed\", \"File not found\", or an error object if the update failed &nbsp;"
  },
  {
    "name": "Update-DbaServiceAccount",
    "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't 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.",
    "category": "Server Management",
    "tags": [
      "service",
      "sqlserver",
      "instance",
      "connect"
    ],
    "verb": "Update",
    "popular": false,
    "url": "/Update-DbaServiceAccount",
    "popularityRank": 69,
    "synopsis": "Changes the service account or password for SQL Server Engine and Agent services.",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Update-DbaServiceAccount View Source Kirill Kravtsov (@nvarscar) Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Changes the service account or password for SQL Server Engine and Agent services. 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't require a restart unless you want the changes to take effect immediately. This 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. Supports 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. Syntax Update-DbaServiceAccount [-ComputerName ] [-Credential ] [-ServiceName] [-Username ] [-ServiceCredential ] [-PreviousPassword ] [-SecurePassword ] [-NoRestart] [-EnableException] [-WhatIf] [-Confirm] [ ] Update-DbaServiceAccount [-Credential ] -InputObject [-Username ] [-ServiceCredential ] [-PreviousPassword ] [-SecurePassword ] [-NoRestart] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Changes the current service account&#39;s password of the service MSSQL$MYINSTANCE to &#39;Qwerty1234&#39; PS C:\\> $SecurePassword = (Get-Credential NoUsernameNeeded).Password PS C:\\> Update-DbaServiceAccount -ComputerName sql1 -ServiceName 'MSSQL$MYINSTANCE' -SecurePassword $SecurePassword Example 2: Requests credentials from the user and configures them as a service account for the SQL Server engine and... PS C:\\> $cred = Get-Credential PS C:\\> Get-DbaService sql1 -Type Engine,Agent -Instance MYINSTANCE | Update-DbaServiceAccount -ServiceCredential $cred Requests credentials from the user and configures them as a service account for the SQL Server engine and agent services of the instance sql1\\MYINSTANCE Example 3: Configures SQL Server engine and agent services on the machines sql1 and sql2 to run under Network Service... PS C:\\> Update-DbaServiceAccount -ComputerName sql1,sql2 -ServiceName 'MSSQLSERVER','SQLSERVERAGENT' -Username NETWORKSERVICE Configures SQL Server engine and agent services on the machines sql1 and sql2 to run under Network Service system user. Example 4: Configures SQL Server engine service on the machine sql1 to run under MyDomain\\sqluser1 PS C:\\> Get-DbaService sql1 -Type Engine -Instance MSSQLSERVER | Update-DbaServiceAccount -Username 'MyDomain\\sqluser1' Configures SQL Server engine service on the machine sql1 to run under MyDomain\\sqluser1. Will request user to input the account password. Example 5: Configures SQL Server engine service on the machine sql1 to run under MyDomain\\sqluser1 PS C:\\> Get-DbaService sql1 -Type Engine -Instance MSSQLSERVER | Update-DbaServiceAccount -Username 'MyDomain\\sqluser1' -NoRestart Configures SQL Server engine service on the machine sql1 to run under MyDomain\\sqluser1. Will request user to input the account password. Will not restart, which means the changes will not go into effect, so you will still have to restart during your planned outage window. Required Parameters -InputObject Accepts service objects from Get-DbaService for pipeline operations. Must contain ComputerName and ServiceName properties. Use 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. | Property | Value | | --- | --- | | Alias | ServiceCollection | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -ServiceName Specifies the exact SQL Server service name to update, such as 'MSSQLSERVER' for default instances or 'MSSQL$INSTANCENAME' for named instances. Use this when you need to target specific services rather than all SQL Server services on a computer. Supports SQL Server Agent services like 'SQLSERVERAGENT' or 'SQLAgent$INSTANCENAME'. | Property | Value | | --- | --- | | Alias | Name,Service | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -ComputerName Specifies the SQL Server computers where service account changes will be applied. Accepts multiple computer names for bulk operations. Use this when you need to update service accounts across multiple SQL Server instances in your environment. | Property | Value | | --- | --- | | Alias | cn,host,Server | | Required | False | | Pipeline | false | | Default Value | $env:COMPUTERNAME | -Credential Windows Credential with permission to log on to the server running the SQL instance | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Username Specifies the service account username in DOMAIN\\\\Username format for domain accounts. Cannot be combined with -ServiceCredential parameter. Use 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. | Property | Value | | --- | --- | | Alias | User | | Required | False | | Pipeline | false | | Default Value | | -ServiceCredential Provides a PSCredential object containing the domain account and password for the SQL Server service. Cannot be combined with -Username parameter. Use 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 LOCALSYSTEM and empty passwords. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -PreviousPassword Specifies the current password of the service account when performing password-only changes. Required for non-admin users but optional for local administrators. Use this when you're rotating passwords for compliance and need to provide the existing password to validate the change. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | (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. Use this when changing passwords for domain service accounts. Managed Service Accounts (MSAs) and local system accounts automatically ignore this parameter since they don't require passwords. | Property | Value | | --- | --- | | Alias | Password,NewPassword | | Required | False | | Pipeline | false | | Default Value | (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. Use this when you need to schedule service restarts during planned maintenance windows to avoid unexpected downtime during business hours. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -WhatIf Shows what would happen if the command were to run. No actions are actually performed. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm Prompts you for confirmation before executing any changing operations within the command. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs Microsoft.SqlServer.Management.Smo.Wmi.SqlService Returns one service object per service that was updated, with additional properties added to indicate the result of the operation. Default display properties (via Select-DefaultView): ComputerName: The name of the computer hosting the SQL Server service ServiceName: The Windows service name (e.g., MSSQLSERVER, SQLSERVERAGENT, MSSQL$INSTANCENAME) State: The current state of the service after the update operation (Running, Stopped, Start Pending, Stop Pending) StartName: The user account under which the service runs after the update Status: Result of the operation (Successful, Failed, or \"No changes made - running in -WhatIf mode.\") Message: Detailed message describing the outcome (e.g., \"The login account for the service has been successfully set.\" or error message) Additional properties available on the service object (from SMO SqlService): ServiceType: The type of SQL Server service (Engine, Agent, etc.) InstanceName: The SQL Server instance name associated with the service DisplayName: The friendly display name of the service StartMode: The startup mode of the service (Automatic, Manual, Disabled) All properties from the base SMO SqlService object are accessible using Select-Object * even though only the 6 default properties are displayed by default. &nbsp;"
  },
  {
    "name": "Update-Dbatools",
    "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's native Install-Module and Update-Module commands which provide better dependency management and version control.",
    "category": "Utilities",
    "tags": [
      "module"
    ],
    "verb": "Update",
    "popular": true,
    "url": "/Update-Dbatools",
    "popularityRank": 27,
    "synopsis": "Updates the dbatools PowerShell module to the latest version",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Update-Dbatools View Source Shawn Melton (@wsmelton), wsmelton.github.io Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Updates the dbatools PowerShell module to the latest version 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's native Install-Module and Update-Module commands which provide better dependency management and version control. Syntax Update-Dbatools [-Development] [-Cleanup] [-EnableException] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Updates dbatools PS C:\\> Update-Dbatools Updates dbatools. Deletes current copy and replaces it with freshest copy. Example 2: Updates dbatools to the current development branch PS C:\\> Update-Dbatools -dev Updates dbatools to the current development branch. Deletes current copy and replaces it with latest from github. Optional Parameters -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't been officially released yet. Development builds may contain untested changes, so avoid using this in production environments unless specifically needed for troubleshooting or testing. | Property | Value | | --- | --- | | Alias | dev,devbranch | | Required | False | | Pipeline | false | | Default Value | 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 only the latest version. Without this switch, old versions remain on the system which can occasionally cause module loading issues or consume unnecessary disk space. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This command is deprecated and returns no output. It displays a warning message to console directing users to use PowerShell's built-in Install-Module and Update-Module commands instead. No pipeline objects are generated. &nbsp;"
  },
  {
    "name": "Watch-DbaDbLogin",
    "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.",
    "category": "Security",
    "tags": [
      "login"
    ],
    "verb": "Watch",
    "popular": false,
    "url": "/Watch-DbaDbLogin",
    "popularityRank": 113,
    "synopsis": "Monitors active connections across SQL Server instances and logs client details to a central tracking table",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Watch-DbaDbLogin View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Monitors active connections across SQL Server instances and logs client details to a central tracking table 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. The 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. You 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. Syntax Watch-DbaDbLogin [[-SqlInstance] ] [[-SqlCredential] ] [[-Database] ] [[-Table] ] [[-SqlCms] ] [[-ServersFromFile] ] [[-InputObject] ] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: A list of all database instances within the Central Management Server SqlCms1 is generated PS C:\\> Watch-DbaDbLogin -SqlInstance sqlserver -SqlCms SqlCms1 A 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 table Dblogins in the DatabaseLogins database on SQL Server sqlserver. Example 2: A list of servers is gathered from the file sqlservers.txt in the current directory PS C:\\> Watch-DbaDbLogin -SqlInstance sqlcluster -Database CentralAudit -ServersFromFile .\\sqlservers.txt A 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 Dblogins in the CentralAudit database on SQL Server sqlcluster. Example 3: A list of servers is generated using database instance names within the SQL2014Clusters group on the Central... PS C:\\> Watch-DbaDbLogin -SqlInstance sqlserver -SqlCms SqlCms1 -SqlCredential $cred A 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 gathers login information and saves it to the table Dblogins in the DatabaseLogins database on sqlserver. Example 4: Pre-connects two instances sqldev01 and sqldev02 and then using pipelining sends them to Watch-DbaDbLogin to... PS C:\\> $instance1 = Connect-DbaInstance -SqlInstance sqldev01 PS C:\\> $instance2 = Connect-DbaInstance -SqlInstance sqldev02 PS C:\\> $instance1, $instance2 | Watch-DbaDbLogin -SqlInstance sqltest01 -Database CentralAudit Pre-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 DbaTools-WatchDbLogins table in the CentralAudit database on the sqltest01 instance. Note: This is the method to use if the instances have different credentials than the instance used to store the watch data. Optional Parameters -SqlInstance The SQL Server that stores the Watch database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target database where connection monitoring data will be stored. This database should be dedicated to audit and monitoring functions, separate from production databases. If not specified, the function will attempt to use a default database on the SqlInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Table Specifies the table name where login monitoring data will be inserted. Defaults to \"DbaTools-WatchDbLogins\" if not specified, and will be auto-created if it doesn't exist. Use a consistent naming convention across environments for easier reporting and analysis. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | DbaTools-WatchDbLogins | -SqlCms Specifies a Central Management Server to retrieve registered SQL Server instances for monitoring. Use this when you need to monitor multiple servers that are already organized in CMS groups. The function will connect to each registered server found in the CMS to capture login activity. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -ServersFromFile Specifies a text file containing SQL Server instance names to monitor, with one instance per line. Use this when you have a custom list of servers not managed through CMS, or when scripting across different environments. Supports both named instances (SERVER\\INSTANCE) and default instances (SERVER). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -InputObject Accepts pre-connected SQL Server instances from Connect-DbaInstance via pipeline. Use this method when monitoring servers with different authentication requirements than the storage instance. Allows for more granular credential control when connecting to multiple instances with varying security contexts. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs None This 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 from monitored instances and inserts the captured session details into the central tracking table for ongoing monitoring and audit purposes. &nbsp;"
  },
  {
    "name": "Watch-DbaXESession",
    "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",
    "category": "Performance",
    "tags": [
      "extendedevent",
      "xe",
      "xevent"
    ],
    "verb": "Watch",
    "popular": false,
    "url": "/Watch-DbaXESession",
    "popularityRank": 455,
    "synopsis": "Monitors Extended Events sessions in real-time, streaming live event data as it occurs",
    "availability": "Windows only",
    "windowsOnly": true,
    "fullContent": "Watch-DbaXESession View Source Chrissy LeMaire (@cl), netnerds.net Windows only On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Monitors Extended Events sessions in real-time, streaming live event data as it occurs 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. Thanks to Dave Mason (@BeginTry) for some straightforward code samples https://itsalljustelectrons.blogspot.be/2017/01/SQL-Server-Extended-Event-Handling-Via-Powershell.html Syntax Watch-DbaXESession [[-SqlInstance] ] [[-SqlCredential] ] [[-Session] ] [[-InputObject] ] [-Raw] [-EnableException] [ ] &nbsp; Examples &nbsp; Example 1: Shows events for the system_health session as it happens PS C:\\> Watch-DbaXESession -SqlInstance sql2017 -Session system_health Example 2: Exports live events to CSV PS C:\\> Watch-DbaXESession -SqlInstance sql2017 -Session system_health | Export-Csv -NoTypeInformation -Path C:\\temp\\system_health.csv Exports live events to CSV. Ctrl-C may not not cancel out of it - fastest way is to stop the session. Example 3: Exports live events to CSV PS C:\\> Get-DbaXESession -SqlInstance sql2017 -Session system_health | Start-DbaXESession | Watch-DbaXESession | Export-Csv -NoTypeInformation -Path C:\\temp\\system_health.csv Exports live events to CSV. Ctrl-C may not not cancel out of this. The fastest way to do so is to stop the session. Optional Parameters -SqlInstance The target SQL Server instance or instances. You must have sysadmin access and server version must be SQL Server version 2008 or higher. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -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. Common sessions include system_health for general diagnostics or custom sessions you've created for specific monitoring needs. | Property | Value | | --- | --- | | Alias | Name | | Required | False | | Pipeline | false | | Default Value | | -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. This enables workflows like 'Get-DbaXESession | Where Name -like \"perf\" | Start-DbaXESession | Watch-DbaXESession' for batch operations. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | true (ByValue) | | Default Value | | -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 processing or integration with other tools. Most DBAs should use the default processed output which provides cleaner, more readable event data. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | Outputs PSCustomObject (default) Returns 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. Default properties include: name: The Extended Event type name (e.g., sql_statement_completed, rpc_completed) timestamp: The DateTime when the event was captured Additional dynamic properties: All event fields (with \"collect_\" prefix removed) and all event actions (with the last part after dot separator) The 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 properties like statement, batch_text, duration, cpu_time, logical_reads, writes, etc. System.Object[] (when -Raw is specified) Returns 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 integration with other tools. &nbsp;"
  },
  {
    "name": "Write-DbaDbTableData",
    "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.",
    "category": "Data Operations",
    "tags": [
      "table",
      "data",
      "insert"
    ],
    "verb": "Write",
    "popular": true,
    "url": "/Write-DbaDbTableData",
    "popularityRank": 13,
    "synopsis": "Performs high-speed bulk inserts of data into SQL Server tables using SqlBulkCopy.",
    "availability": "Windows, Linux, macOS",
    "windowsOnly": false,
    "fullContent": "Write-DbaDbTableData View Source Chrissy LeMaire (@cl), netnerds.net Windows, Linux, macOS On this page: Synopsis · Description · Syntax · Examples · Parameters · Outputs Synopsis Performs high-speed bulk inserts of data into SQL Server tables using SqlBulkCopy. 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. Syntax Write-DbaDbTableData -SqlInstance [-SqlCredential ] [-Database ] -InputObject [-Table] [[-Schema] ] [-BatchSize ] [-NotifyAfter ] [-AutoCreateTable] [-NoTableLock] [-CheckConstraints] [-FireTriggers] [-KeepIdentity] [-KeepNulls] [-Truncate] [-BulkCopyTimeOut ] [-ColumnMap ] [-EnableException] [-UseDynamicStringLength] [-WhatIf] [-Confirm] [ ] &nbsp; Examples &nbsp; Example 1: Performs a bulk insert of all the data in customers.csv into database mydb, schema dbo, table customers PS C:\\> $DataTable = Import-Csv C:\\temp\\customers.csv PS C:\\> Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers Performs 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, the import will be halted. Example 2: Pulls data from a SQL Server instance and then performs a bulk insert of the dataset to a new, auto-generated... PS C:\\> $tableName = \"MyTestData\" PS C:\\> $query = \"SELECT name, create_date, owner_sid FROM sys.databases\" PS C:\\> $dataset = Invoke-DbaQuery -SqlInstance 'localhost,1417' -SqlCredential $containerCred -Database master -Query $query -As DataSet PS C:\\> $dataset | Write-DbaDbTableData -SqlInstance 'localhost,1417' -SqlCredential $containerCred -Database tempdb -Table $tableName -AutoCreateTable Pulls data from a SQL Server instance and then performs a bulk insert of the dataset to a new, auto-generated table tempdb.dbo.MyTestData. Example 3: Performs a bulk insert of all the data in customers.csv PS C:\\> $DataTable = Import-Csv C:\\temp\\customers.csv PS C:\\> Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers -AutoCreateTable -Confirm Performs 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. Prompts for confirmation before a variety of steps. Example 4: Performs a bulk insert of all the data in customers.csv PS C:\\> $DataTable = Import-Csv C:\\temp\\customers.csv PS C:\\> Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Table mydb.dbo.customers -Truncate Performs 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 prompted again to perform the import. Example 5: Performs a bulk insert of all the data in customers.csv into mydb.dbo.customers PS C:\\> $DataTable = Import-Csv C:\\temp\\customers.csv PS C:\\> Write-DbaDbTableData -SqlInstance sql2014 -InputObject $DataTable -Database mydb -Table customers -KeepNulls Performs 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. Example 6: This performs the same operation as the previous example, but against a SQL Azure Database instance using the... PS C:\\> $passwd = (Get-Credential NoUsernameNeeded).Password PS C:\\> $AzureCredential = New-Object System.Management.Automation.PSCredential(\"AzureAccount\"),$passwd) PS C:\\> $DataTable = Import-Csv C:\\temp\\customers.csv PS C:\\> Write-DbaDbTableData -SqlInstance AzureDB.database.windows.net -InputObject $DataTable -Database mydb -Table customers -KeepNulls -SqlCredential $AzureCredential -BulkCopyTimeOut 300 This performs the same operation as the previous example, but against a SQL Azure Database instance using the required credentials. Example 7: Creates a table based on the Process object with over 60 columns, converted from PowerShell data types to SQL... PS C:\\> $process = Get-Process PS C:\\> Write-DbaDbTableData -InputObject $process -SqlInstance sql2014 -Table \"[[DbName]]].[Schema.With.Dots].[`\"[Process]]`\"]\" -AutoCreateTable Creates 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 information into the table Writes the results of Get-Process to a table named: \"[Process]\" in schema named: Schema.With.Dots in database named: [DbName] The Table name, Schema name and Database name must be wrapped in square brackets [ ] Special characters like \" must be escaped by a ` character. In addition any actual instance of the ] character must be escaped by being duplicated. This 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 thanks to ConvertTo-DbaDataTable. Example 8: The dataset column &#39;value1&#39; is inserted into SQL column &#39;col1&#39; and dataset column value2 is inserted into the... PS C:\\> $server = Connect-DbaInstance -SqlInstance SRV1 PS C:\\> $server.Invoke(\"CREATE TABLE tempdb.dbo.test (col1 INT, col2 VARCHAR(100))\") PS C:\\> $data = Invoke-DbaQuery -SqlInstance $server -Query \"SELECT 123 AS value1, 'Hello world' AS value2\" -As DataSet PS C:\\> $data | Write-DbaDbTableData -SqlInstance $server -Table 'tempdb.dbo.test' -ColumnMap @{ value1 = 'col1' ; value2 = 'col2' } The dataset column 'value1' is inserted into SQL column 'col1' and dataset column value2 is inserted into the SQL Column 'col2'. All other columns are ignored and therefore null or default values. Example 9: Imports sales_data.csv into mydb.reporting.sales PS C:\\> $DataTable = Import-Csv C:\\temp\\sales_data.csv PS C:\\> Write-DbaDbTableData -SqlInstance sql2016 -InputObject $DataTable -Database mydb -Schema reporting -Table sales -AutoCreateTable Imports sales_data.csv into mydb.reporting.sales. If the reporting schema doesn't exist, it will be automatically created with dbo as owner. The sales table will then be created with columns inferred from the CSV structure. Required Parameters -SqlInstance The target SQL Server instance or instances. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | -InputObject Accepts various data formats including DataTable, DataSet, CSV files, or PowerShell objects for bulk insertion. Use 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. PowerShell objects are automatically converted to DataTable format before import. | Property | Value | | --- | --- | | Alias | DataTable | | Required | True | | Pipeline | true (ByValue) | | Default Value | | -Table Specifies the destination table using one, two, or three-part naming (database.schema.table). Supports temp tables with # prefix. Use square brackets for special characters: [Schema.Name].[Table]] for tables containing brackets. Three-part names override the Database parameter. Combine with -AutoCreateTable to create missing tables, though manual table creation provides better data type control. | Property | Value | | --- | --- | | Alias | | | Required | True | | Pipeline | false | | Default Value | | Optional Parameters -SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Database Specifies the target database for the bulk insert operation. Required when using one or two-part table names. Use this when you need to target a specific database different from the default connection database. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -Schema Sets the schema for the destination table when not specified in the table name. Defaults to 'dbo'. Use this when working with non-default schemas or when security policies require specific schema targeting. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | dbo | -BatchSize Controls how many rows are sent to SQL Server in each batch operation. Defaults to 50,000 rows. Lower values (5,000-10,000) work better for wide tables or limited memory, while higher values improve performance for narrow tables with sufficient resources. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 50000 | -NotifyAfter Determines how frequently progress notifications appear during the import operation. Defaults to every 5,000 rows. Set higher for less frequent updates on large imports, or lower for more granular progress tracking on smaller datasets. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 5000 | -AutoCreateTable Automatically creates the destination table and schema when they don't exist, using data types inferred from the source data. The 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 constraints. Note: Schema creation is skipped for temp tables (tables starting with #). | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -NoTableLock Disables the default TABLOCK hint during bulk insert operations, allowing concurrent access to the destination table. Use when importing to tables that need concurrent read access, though this may reduce import performance compared to the default exclusive lock. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -CheckConstraints Enforces check constraints during the bulk insert operation instead of the default behavior of bypassing them. Use when data integrity validation is critical, though this reduces import performance. Constraints are normally checked after bulk operations complete. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -FireTriggers Executes INSERT triggers during the bulk copy operation instead of bypassing them for performance. Essential when triggers maintain audit trails, calculated fields, or related table updates. Significantly impacts import speed but preserves all database logic. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepIdentity Preserves identity column values from the source data instead of generating new sequential values. Critical for maintaining referential integrity when importing related tables or restoring data with existing identity dependencies. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -KeepNulls Maintains NULL values from source data instead of replacing them with column default values. Use when NULL has specific business meaning in your data or when you need to preserve exact source data representation including missing values. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -Truncate Removes all existing data from the destination table before performing the bulk insert operation. Useful for refreshing tables with new data while maintaining table structure, indexes, and permissions. Always prompts for confirmation before execution. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -BulkCopyTimeOut Sets the maximum time in seconds to wait for the bulk copy operation to complete. Defaults to 5,000 seconds. Increase for very large datasets or slow storage systems. Set to 0 for unlimited timeout when importing millions of rows. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 5000 | -ColumnMap Defines custom mapping between source and destination columns using a hashtable when automatic column mapping fails. Use when column names differ between source and target, or when you need to import only specific columns. Format: @{SourceColumn='DestColumn'}. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | | -EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with \"sea of red\" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this \"nice by default\" feature off and enables you to catch exceptions with your own try/catch. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | False | -UseDynamicStringLength Creates string columns with lengths based on source data MaxLength property instead of defaulting to NVARCHAR(MAX). Improves storage efficiency and query performance when AutoCreateTable is used, but requires source data to provide accurate length information. | Property | Value | | --- | --- | | Alias | | | Required | False | | Pipeline | false | | Default Value | 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. | Property | Value | | --- | --- | | Alias | wi | | Required | False | | Pipeline | false | | Default Value | | -Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. | Property | Value | | --- | --- | | Alias | cf | | Required | False | | Pipeline | false | | Default Value | | Outputs None This 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 Write-Progress during the import operation, and verbose messages are written to the verbose stream for troubleshooting. &nbsp;"
  }
]
