Posted On September 24, 2021

Use PowerShell to Set Microsoft SQL Database Owner

kimconnect 0 comments
blog.KimConnect.com >> Codes , Database >> Use PowerShell to Set Microsoft SQL Database Owner
$owner='CAP\SQL Admins'
$databaseName='TestDb'
$sqlServer=$env:computername

function setDbOwner{
  param(
    $principle=$env:USERDOMAIN+'\Domain Admins',
    $databaseName='TestDB',
    $sqlServer
  )
  
  function includeSqlTools{
    $ErrorActionPreference='stop'
    try{
      $trustedPsgallery=(Get-PSRepository PSGallery).InstallationPolicy -eq 'Trusted'
      if(!$trustedPsgallery){
          Set-PSRepository -Name PSGallery -InstallationPolicy Trusted 
      }
      if(!(Get-Module sqlserver)){
          Install-Module sqlserver -Confirm:$False
      }
      if(!(Get-Module dbatools)){
          Install-Module dbatools -Confirm:$False
      }
      Import-Module sqlserver  
      Import-Module dbatools
      return $true
    }catch{
      write-warning $_
      return $false
    }
  }

  try{
    if(!(includeSqlTools)){
      write-warning "Cannot proceed with SQL Tools"
      return $false
    }
    $server=New-Object ('Microsoft.SqlServer.Management.Smo.Server') $sqlServer
    $db=New-Object Microsoft.SqlServer.Management.Smo.Database
    $db=$server.Databases.Item($databaseName)
    $db.SetOwner($principle, $TRUE)
    $db.Alter()
    return $true
  }catch{
    Write-Warning
    return $false
  }
}

setDbOwner $owner $databaseName $sqlServer

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

PowerShell: Grant Current User Full Access to File or Folder

# Grant Current User Full Access to Object $object='C:\temp' $acl=Get-Acl $object $currentUser=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name $grantAccess=New-Object System.Security.AccessControl.FileSystemAccessRule("$currentUser","FullControl","Allow") $acl.AddAccessRule($grantAccess)…

PowerShell: Outdated Method of Sending Emails

# Credentials section $emailFrom = "[email protected]" $password = "eatYourSalad!" | ConvertTo-SecureString -AsPlainText -Force # plaintext…

PowerShell: Quickly Test Connectivity from a List of Sources toward a Destination on a Specific Port

# testRemotePort.ps1 $connectFrom=@' windows1 windows2 '@ $connectTo=@' \\servername\sharename '@ $testPort=445 $sources=@($connectFrom -split "`n")|%{$_.Trim()} $destinations=@($connectTo -split…