Skip to main content

A PowerShell function that accepts a SQL Server name and query to execute against the target database.

Function log($string, $color)
{
    if ($Color -eq $null)
    {
        $color = "white"
    }
    write-host $string -foregroundcolor $color
    $string | out-file -Filepath $logfile -append
}

Function InfoMessage($Text)
{
    $time = Get-Date -Format dd:MM:yyyy:hh:mm:ss
    Write-host "[$time] Info::$Text" -ForegroundColor Yellow
    log "[$time] Info::$Text"
}

Function ErrorMessage($Text)
{
    $time = Get-Date -Format dd:MM:yyyy:hh:mm:ss
    Write-host "[$time] Error::$Text" -ForegroundColor Red
    log "[$time] Error::$Text"
}

Function fn_Execute($DBServerName, $query)
{
    $ErrorActionPreference = "Stop";

    try
    {
        InfoMessage("Running the query $query on the server $DBServerName  ")

        $cn = new-object System.Data.SqlClient.SqlConnection "server=$DBServerName;database=master;Integrated Security=sspi"
        $sql = $cn.CreateCommand()
        $sql.CommandText = $query
        $cn.Open()
        $rdr = $sql.ExecuteNonQuery();

        InfoMessage("completed running query ")
    }
    catch
    {
        ErrorMessage "Error While Executing query file "
        ErrorMessage "Error While copying file $Error[0].Exception"
        Break
    }
    finally
    {
        $ErrorActionPreference = "Continue"; #Reset the error action pref to default
    }
 }

 # fn_Execute $DBServerName "BACKUP DATABASE $DbName TO DISK='$PathoftheBackup\$DbName.bak'"