這是本文件的舊版!


PostgreSQL - Unattended installation on windows

要將別人軟體包裝到自己軟體中,不可或缺的東西就是Unattended installation。以Unattended installation來說,我們可以選擇透過Installer的silent mode安裝,也可以透過把目標軟體做成portable的版本。本篇文章分享這兩種方法,教導大家如何將PostgreSQL透過Unattended installation方式安裝到目標系統成為service。

Tips

安裝程式或反安裝程式的參數,除了可以直接上官網搜尋Installation User Guide以外,也可以直接使用–help參數查詢:

postgresql-10.7-2-windows-x64.exe --help
Windows安裝程式主要有EnterpriseDB與BigSQL兩種。BigSQL版本安裝元件是透過網路下載且支援參數不如EnterpriseDB版本多,以我們需求來說,我們傾向於使用EnterpriseDB版本。接下來分享給大家安裝與反安裝方法。

Installation

@echo off
set INSTALL_DIR=C:\postgres10
set INSTALLER=postgresql-10.7-2-windows-x64.exe
 
rem options for installation
set SSMDB_SERVICE=postgresql-10
set MODE=--unattendedmodeui none --mode unattended
 
set DB_PASSWD=--superpassword postgres
set DB_PORT=--serverport 5432
 
set SERVICE_NAME=--servicename %SSMDB_SERVICE%
 
set PREFIX=--prefix "%INSTALL_DIR%"
set DATA_DIR=--datadir "%INSTALL_DIR%\data"
 
set OPTIONS=%MODE% %PREFIX% %DB_PASSWD% %DATA_DIR% %DB_PORT% %SERVICE_NAME% --disable-components stackbuilder,pgAdmin
 
echo %INSTALLER% %OPTIONS%
%INSTALLER% %OPTIONS%
從我的batch變數名稱,大都可以猜出個別參數用途。我額外說明的參數如下:

  • prefix: 這指安裝目錄。
  • disable-components: 不安裝的項目。以我的例子來說,我不需要將stackbuilder與pgAdmin安裝到目標系統上。
  • install_runtimes: 是否要安裝c++ distribution,預設是1,要安裝。

Un-installation

taskkill /f /im pgadmin4.exe
uninstall-postgresql.exe --mode unattended
這裡要特別做的是要kill pgadmin4的process,因為在uninstall postgresql時,它並不會去停止pgadmin4,這將導致pgadmin4殘留在系統中。

Tips

把安裝完的東西複製一份出來並不困難,只要它的conf沒紀錄與路徑有關或相依於註冊檔內容,你有很大機會可以做成portable版本。按照以前在PostgreSQL 9.1的經驗,在我們還原備份出來的東西後,只要把service註冊好,就能夠正常使用了。

Portable Pack


在安裝完的postgresql中,我保留如上圖的內容。在備份之前,我先停止了原本正在執行的postgresql的service,並且砍掉了data/log的所有檔案。

Setup Service & Remove Service

在將Portable pack部屬到目標系統並解開後,可以透過pg_ctl.exe去註冊service。我的工作目錄是在安裝目錄下,service名稱為postgresql-10:

@echo off
set BASE=%~dp0
 
set SERVICE=postgresql-10
set PG_CTL=%BASE%bin\pg_ctl.exe
set PG_DATA=%BASE%data
 
"%PG_CTL%" register -N "%SERVICE%" -D "%PG_DATA%" -w
假如要移除service,可以使用以下腳本:
@echo off
set SERVICE=postgresql-10
 
net stop %SERVICE%
sc delete %SERVICE%