Configurations/PowerShellLab/PostSetup/Install-VSCode.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#requires -version 5.1

#Download and install the latest 64bit version of VSCode

[CmdletBinding(DefaultParameterSetName = "VM")]
Param(
    [Parameter(Mandatory, ParameterSetName = 'VM')]
    #specify the name of a VM
    [string]$VMName,
    [Parameter(Mandatory, ParameterSetName = 'VM')]
    #Specify the user credential
    [pscredential]$Credential,
    [Parameter(Mandatory, ParameterSetName = "session")]
    #specify an existing PSSession object
    [System.Management.Automation.Runspaces.PSSession]$Session
)

#download the setup file on the host and then copy to VM to avoid strange name resolution problems
$path = $env:temp
$uri = 'https://vscode-update.azurewebsites.net/latest/win32-x64/stable'
# 'https://vscode-update.azurewebsites.net/latest/win32-x64/stable'
# 'https://go.microsoft.com/fwlink/?Linkid=852157'
$out = Join-Path -Path $Path -ChildPath VSCodeSetup-x64.exe

Try {
    Write-Host " Downloading from $uri" -foreground magenta
    Invoke-WebRequest -Uri $uri -OutFile $out -DisableKeepAlive -UseBasicParsing
}
Catch {
    Throw $_
    #bail out
    Return
}

Try {
    if ($PSCmdlet.ParameterSetName -eq 'VM') {
        Write-Host "Creating PSSession to $VMName" -ForegroundColor cyan
        $session = New-PSSession @PSBoundParameters -ErrorAction stop
    }

    #copy the file to the VM
    copy-item -Path $out -Destination C:\ -ToSession $Session

    $sb = {
        $file = 'C:\VSCodeSetup-x64.exe'
        Write-Host "[$($env:computername)] Installing VSCode" -foreground magenta
        $loadInf = '@
[Setup]
Lang=english
Dir=C:\Program Files\Microsoft VS Code
Group=Visual Studio Code
NoIcons=0
Tasks=desktopicon,addcontextmenufiles,addcontextmenufolders,addtopath
@'

        $infPath = "${env:TEMP}\load.inf"
        $loadInf | Out-File $infPath

        Start-Process -FilePath $file -ArgumentList "/VERYSILENT /LOADINF=${infPath}" -Wait
        Write-Host "[$($env:computername)] Finished Installing VSCode" -foreground magenta
    } #close scriptblock

    Invoke-Command -ScriptBlock $sb -Session $session

    if ($PSCmdlet.ParameterSetName -eq 'VM') {
        Write-Host "Removing PSSession" -ForegroundColor cyan
        $Session | Remove-PSSession
    }
}
Catch {
    Throw $_
}