Post

Run the SQL commands on Windows PowerShell

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$SqlPath = "$([System.IO.Path]::GetFullPath("$($MyInvocation.MyCommand.Path)\.."))\sql"

$DBHost = "localhost"
$DBPort = "5432"
$DBName = "myapp"
$DBUser = "postgres"
$DBPassword = "postgres"

$Env:PGPASSWORD = $DBPassword

# Check Database name exist
$PsqlCommand = "psql -U $DBUser -h $DBHost -p $DBPort -d postgres -c 'SELECT datname FROM pg_catalog.pg_database WHERE datname = ''$DBName'';'"
$Result = Invoke-Expression -Command $PsqlCommand

if ($Result -match $DBName) {
    Write-Host "Database $DBName exists!"
    Exit 1
}

# Run SQL command from the sql file
$PsqlCommand = "psql -U $DBUser -h $DBHost -p $DBPort -d postgres -f $SqlPath/query.sql"
Invoke-Expression $PsqlCommand
This post is licensed under CC BY 4.0 by the author.