create database if not exists

  • abdalah.mehdoini

    SSC Eights!

    Points: 875

    Good morning all

    I am looking to create a sql server database if the database does not exist on my instance

    I use this script for this

    Import-Module "SQLPS" -DisableNameChecking
    Import-Module -Name "${PSScriptRoot}\Module\logModule.psm1" -DisableNameChecking
    Add-Type -AssemblyName "Microsoft.SqlServer.Smo"

    foreach($server in $servers)
    Set-Location SQLSERVER:\SQL\$server
    $db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database -Argumentlist $server, $database

    if($db -ne $null)
    InitLog -PathLog "${PSScriptRoot}\${Instance}\DbaWhoIsActive.log" -NameScript "PsBackupFull"
    Log -message "Server : ${$server}"
    Install-DbaWhoIsActive -SqlInstance $server -Database $database


    attached the error that I have if the base exists

    Sans titre


    thanks for your help


  • John Mitchell-245523

    SSC Guru

    Points: 148769

    Your New-Object command is running before you've done any existence check.  If the database already exists then you'll get an error.


Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply