LoginSignup
4
4

More than 5 years have passed since last update.

PowerShell を使ってGo言語をインストールする

Last updated at Posted at 2014-07-17

要 .NET Framework 4.5 or later.

スクレイピングして最新版を取得するとかバージョンを選択してインストールとかそう言った割と面倒なことはしていないので随時ダウンロードURLは変えてください。
あとデフォルトではCドライブ直下にインストールするので必要に応じて引数充ててください。

function Install-Golang
{
    [CmdletBinding()]
    param(
        [Parameter()]
        [ValidateSet("Auto", "64bit","32bit")]
        $Architecture = "Auto",
        [Parameter()]
        [string]$InstallPath = "C:\",
        [Parameter()]
        [string]$GoPath = "C:\golib\"
    )

    begin
    {
        if ($Architecture -eq "Auto") {
            $Architecture = if ([Environment]::Is64BitOperatingSystem) { "64bit" } else { "32bit" }
        }

        $InstallPath | ? { !(Test-Path $_) } | %{ New-Item -Path $_ -ItemType Directory -Force }

        $DownloadUrl = GetDownloadUrl($Architecture)
        $TempDir = "C:\Temp\Golang"
        $FileName = "GolangInstaller.msi"
        try
        {
            Add-Type -AssemblyName System.IO.Compression.FileSystem
        }
        catch
        {
        }
    }

    end
    {
        Write-Verbose -Message "Download Installer..."
        DownloadFile -Uri $DownloadUrl -DestinationPath "$TempDir\$FileName"
        Write-Verbose -Message "Done."

        Write-Verbose -Message "Extract Zip Archive..."
        [System.IO.Compression.ZipFile]::ExtractToDirectory("$TempDir\$FileName", $InstallPath)
        Write-Verbose -Message "Done."

        Write-Verbose -Message "Set Environment Variable..."
        [Environment]::SetEnvironmentVariable("Path", "$(Join-Path $InstallPath "go\bin\")", "User")
        [Environment]::SetEnvironmentVariable("GOPATH", $GoPath, "User")
        Write-Verbose -Message "Done."

        Write-Verbose -Message "Remove Downloaded File ($TempDir)..."
        Remove-Item -LiteralPath "$TempDir" -Recurse -Force
        Write-Verbose -Message "Done."

        Write-Verbose -Message "Complete."
    }
}

function GetDownloadUrl([string]$Architecture)
{
    if ($Architecture -eq "64bit") {
        return "http://golang.org/dl/go1.3.windows-amd64.zip"
    }
    else {
        return "http://golang.org/dl/go1.3.windows-386.zip"
    }
}

function DownloadFile
{
    param(
        [parameter(Mandatory = $true)]
        [string] $Uri,
        [parameter(Mandatory = $true)]
        [string] $DestinationPath,
        [string] $UserAgent,
        [System.Collections.Hashtable] $Headers,
        [System.Management.Automation.PSCredential] $Credential
    )

    begin
    {
        try { Add-Type -AssemblyName System.Net }
        catch { }
        $file = New-Object System.IO.FileInfo $DestinationPath
        if (!(Test-Path $file.Directory.FullName)) {
            New-Item -Path $file.Directory.FullName -ItemType Directory -Force
        }
    }

    end
    {
        try
        {
            $client = New-Object System.Net.WebClient
            $request = [System.Net.WebRequest]::Create($Uri)
            $request.Method = "HEAD"

            foreach ($key in $Headers.Keys)
            {
                $client.Headers[$key] = $Headers[$key]
            }

            if ($UserAgent -ne $null)
            {
                $client.Headers["User-Agent"] = $UserAgent
            }

            if ($Credential -ne $null)
            {
                $request.Credentials = $client.Credentials = $Credential.GetNetworkCredential()
            }

            $response = $request.GetResponse()
            $contentLength = $response.ContentLength
            $task = $client.DownloadFileTaskAsync($Uri, $DestinationPath);

            while (!$task.IsCompleted)
            {
                $downloadedLength = (Get-Item $DestinationPath).Length
                Write-Progress -Activity "[Downloading] $Uri" -Status "$($downloadedLength.ToString("#,###,###,###")) bytes" -PercentComplete ($downloadedLength / $contentLength *100)
                Start-Sleep -Milliseconds 100
            }
            Write-Progress -Activity "[Download completed] $Uri" -Status "$((Get-Item $DestinationPath).Length.ToString("#,###,###,###")) bytes" -PercentComplete 100 -Completed
        }
        catch
        {
            throw "Invoking download file failed: $_"
        }
        finally
        {
            $client.Dispose()
        }
    }
}

Install-Golang -Verbose

ダウンロードはInvoke-WebRequestでもいいですがアウトオブメモリーになる可能性ありなので非推奨ですの。
割とてきとーなので誰か突っ込んでくださいお願いします。
システム破壊したらさーせん><

GOPATHも設定するようにした。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4