PowerShellでPythonをWindowsに自動インストール

Developer

初めに

このブログでは、PowerShellスクリプトを活用して、Pythonの自動インストールを実現する方法を解説します。特に、クラウド環境での効率的なセットアップを目指す方や、Computeインスタンスの作成時に自動的にインストールしたい方にとって、一助となれば幸いです。

cloud-init スクリプトに組み込むことで、インスタンスの初期設定時に Python を自動インストールでき、手動作業を省略できます。これにより、環境構築のスピードと再現性を大幅に向上させることが可能になります。

環境情報
OS: Windows Server 2019 Standard Edition (VM)
Python バージョン: 3.14.2 (x64)

ステップ

  • インストーラのダウンロード(リンク
  • インストール開始(/quiet PrependPath=1
  • インストーラの削除(オプション)
#ps1_sysnative

# Define the URL of the Python installer
$PythonVersion = "3.14.2"
$InstallerFile = "python-$PythonVersion-amd64.exe"
$InstallerUrl = "https://www.python.org/ftp/python/$PythonVersion/$InstallerFile"

# Define the path where you want to save the installer
$InstallerPath = Join-Path $env:TEMP $InstallerFile

# Download the installer
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest -Uri $InstallerUrl -OutFile $InstallerPath

# Unblock the downloaded file
Unblock-File -Path $InstallerPath

# Execute the installer silently
Start-Process  -Wait -FilePath $InstallerPath -Args "/quiet PrependPath=1"

# Clean up the installer after installation (optional)
Remove-Item $InstallerPath
OCI cloud-init で実行した場合は、先頭に#ps1_sysnativeを追加する必要があります。

パラメータ
/quiet: ユーザーインターフェイスを表示せずにインストール/アンインストールを行います。
PrependPath=1: インストール・ディレクトリおよびスクリプト・ディレクトリを 環境変数 PATHに追加し、.PYを 環境変数 PATHEXT に追加します(デフォルト値はゼロ)。

インストール後の確認

PS C:\Users\opc> python -V
Python 3.14.2

以上

オフィシャルドキュメント
Python Download
Using Python on Windows: 英語 日本語

タイトルとURLをコピーしました