$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
September 24, 2021September 24, 2021
0 Comments