Skip to content

Instantly share code, notes, and snippets.

@MasFlam
Created August 14, 2020 15:05
Show Gist options
  • Save MasFlam/f083a55fafb9b9e7ed7de9fd6ffd5313 to your computer and use it in GitHub Desktop.
Save MasFlam/f083a55fafb9b9e7ed7de9fd6ffd5313 to your computer and use it in GitHub Desktop.
PowerShell script to run psql prompting for connection details
Write-Host "Enter connection details:"
$server = "localhost"
$server_maybe = (Read-Host -Prompt "Server [$server]")
If($server_maybe -ne "") {
$server = $server_maybe
}
$db = "postgres"
$db_maybe = (Read-Host -Prompt "Database [$db]")
If($db_maybe -ne "") {
$db = $db_maybe
}
$port = 5432
[int]$port_maybe = (Read-Host -Prompt "Port [$port]")
If($port_maybe -ne "") {
$port = $port_maybe
}
$username = "postgres"
$username_maybe = (Read-Host -Prompt "Username [$username]")
If($username_maybe -ne "") {
$username = $username_maybe
}
Write-Host "Running psql"
Write-Host
psql -h $server -U $username -d $db -p $port
@sarabjot294
Copy link

sarabjot294 commented May 20, 2021

Thank you for your list of commands.

It works!
but it opens postgres=# terminal on powershell.
I want to write commands like create database, create table, etc. in the PowerShell file, so they can be executed automatically. Any ideas how?

@MasFlam
Copy link
Author

MasFlam commented May 20, 2021

According to man psql it's the -c command line option.

@sarabjot294
Copy link

Thank you for your comment.

Yes, how how can I write those commands in Powershell?
After executing your commands, it just opens up the Postgres terminal. After successful login, I want commands to execute automatically.
Any Idea how to write it in powershell?
Thanks in advance.

@MasFlam
Copy link
Author

MasFlam commented May 20, 2021

Add -c 'your command' to the end of the last line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment