# git subtree add --prefix .github-actions https://github.com/actions/virtual-environments.git master --squash

git subtree pull --prefix .github-actions https://github.com/actions/virtual-environments.git master


# Author: Florian Grehl - www.virten.net
# Reference: -
# Description: Check ESXi 6.7 support with JSON based HCL provided by www.virten.net
#              (http://www.virten.net/2016/05/vmware-hcl-in-json-format/)
#
# Requires Check-HCL function (https://github.com/fgrehl/virten-scripts/blob/master/powershell/Check-HCL.ps1)

#$scope = Get-VMHost esx73.virten.lab
#$scope = Get-Cluster Production | Get-VMHost
$scope = Get-VMHost

(New-Object System.Net.WebClient).DownloadFile("https://raw.githubusercontent.com/fgrehl/virten-scripts/master/powershell/Check-HCL.ps1", "$Env:temp\Check-HCL.ps1")
. $Env:temp\Check-HCL.ps1
$check = Check-HCL $scope
foreach ($esx in $check){
  Write-Host "$($esx.VMHost) ($($esx.Model)): "  -NoNewline
  if($esx.SupportedReleases){
    if ($esx.SupportedReleases -match "6.7"){
      Write-Host "ESXi 6.7 supported" -ForegroundColor Green
    } else {
      Write-Host "ESXi 6.7 unsupported" -ForegroundColor Red
    }
  } else {
    Write-Host "unknown"
  }
}


<#
.summary
    Test suite for MSFT_xPackageResource.psm1
#>
[CmdletBinding()]
param()

Import-Module $PSScriptRoot\..\DSCResources\MSFT_xPackageResource\MSFT_xPackageResource.psm1

$ErrorActionPreference = 'stop'
Set-StrictMode -Version latest

function Suite.BeforeAll {
    # Remove any leftovers from previous test runs
    Suite.AfterAll

}

function Suite.AfterAll {
    Remove-Module MSFT_xPackageResource
}

function Suite.BeforeEach {
}

try
{
    InModuleScope MSFT_xPackageResource {
    Describe 'Get-RegistryValueIgnoreError' {

        It 'Should get values from HKLM' {
                $installValue = Get-RegistryValueIgnoreError 'LocalMachine' "SOFTWARE\Microsoft\Windows\CurrentVersion" "ProgramFilesDir" Registry64
                $installValue | should be $env:programfiles
        }
        It 'Should get values from HKCU' {
                $installValue = Get-RegistryValueIgnoreError 'CurrentUser' "Environment" "Temp" Registry64
                $installValue | should be $env:temp
        }

    }
    }
}
finally
{
    Suite.AfterAll
}

Add fix for running in Terminal Services

<#
.summary
    Test suite for MSFT_xPackageResource.psm1
#>
[CmdletBinding()]
param()

Import-Module $PSScriptRoot\..\DSCResources\MSFT_xPackageResource\MSFT_xPackageResource.psm1

$ErrorActionPreference = 'stop'
Set-StrictMode -Version latest

function Suite.BeforeAll {
    # Remove any leftovers from previous test runs
    Suite.AfterAll

}

function Suite.AfterAll {
    Remove-Module MSFT_xPackageResource
}

function Suite.BeforeEach {
}

try
{
    InModuleScope MSFT_xPackageResource {
    Describe 'Get-RegistryValueIgnoreError' {

        It 'Should get values from HKLM' {
                $installValue = Get-RegistryValueIgnoreError 'LocalMachine' "SOFTWARE\Microsoft\Windows\CurrentVersion" "ProgramFilesDir" Registry64
                $installValue | should be $env:programfiles
        }
        It 'Should get values from HKCU' {
                $installValue = Get-RegistryValueIgnoreError 'CurrentUser' "Environment" "Temp" Registry64
                $installValue.length -gt 3 | should be $true
                $envBeginning = $env:temp.substring(0,$installValue.length)
                $installValue | should be $envBeginning
        }

    }
    }
}
finally
{
    Suite.AfterAll
}


<#
VS+MSBuild.psm1 - Visual Studio and MSBuild utilities.

Copyright (c) 2013 Precision Mojo, LLC.

This file is part of the Unity3D.DLLs project (< URL >) which is distributed under the MIT License.
Refer to the LICENSE.MIT.md document located in the project directory for licensing terms.

Several functions are copied from scripts found in David Fowler's NuGetPowerTools package (https://github.com/davidfowl/NuGetPowerTools).
NuGetPowerTools is licensed under the Apache License 2.0 (https://nuget.codeplex.com/license).
#>

function Get-ProjectFromName
{
	param
	(
		[Parameter(ValueFromPipelineByPropertyName=$true)]
		[String[]] $ProjectName
	)

	if ($ProjectName)
	{
		$projects = Get-Project $ProjectName
	}
	else
	{
		$projects = Get-Project
	}

	$projects
}

function Get-MSBuildProject
{
	param
	(
		[Parameter(ValueFromPipelineByPropertyName=$true)]
		[String[]] $ProjectName,
		[switch] $SpecifyUserProject
	)

	process
	{
		(Get-ProjectFromName $ProjectName) | % {
			if ($SpecifyUserProject)
			{
				$path = $_.FullName + ".user"
			}
			else
			{
				$path = $_.FullName
			}

			@([Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($path))[0]
		}
	}
}

Rename Get-ProjectByName to Get-Projects and fix its semantics.

<#
VS+MSBuild.psm1 - Visual Studio and MSBuild utilities.

Copyright (c) 2013 Precision Mojo, LLC.

This file is part of the Unity3D.DLLs project (< URL >) which is distributed under the MIT License.
Refer to the LICENSE.MIT.md document located in the project directory for licensing terms.

Several functions are copied from scripts found in David Fowler's NuGetPowerTools package (https://github.com/davidfowl/NuGetPowerTools).
NuGetPowerTools is licensed under the Apache License 2.0 (https://nuget.codeplex.com/license).
#>

function Get-Projects
{
	param
	(
		[Parameter(ValueFromPipelineByPropertyName=$true)]
		[String[]] $ProjectName
	)

	if ($ProjectName)
	{
		$projects = Get-Project $ProjectName
	}
	else
	{
		$projects = Get-Project -All
	}

	$projects
}

function Get-MSBuildProject
{
	param
	(
		[Parameter(ValueFromPipelineByPropertyName=$true)]
		[String[]] $ProjectName,
		[switch] $SpecifyUserProject
	)

	process
	{
		(Get-Projects $ProjectName) | % {
			if ($SpecifyUserProject)
			{
				$path = $_.FullName + ".user"
			}
			else
			{
				$path = $_.FullName
			}

			@([Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($path))[0]
		}
	}
}


$nugetversion = $env:DOTNETR2RMLSTORE_NUGETVERSION

function Update-NuspecVersion
{
  Param ([string]$Version)

  foreach ($o in $input)
  {
    Write-output ('Updating nuspec file ' + $o.FullName)
    $TmpFile = $o.FullName + ".tmp"

     get-content $o.FullName |
        %{$_ -replace '\$version\$', $Version } > $TmpFile

     move-item $TmpFile $o.FullName -force
  }
}

function Pack-Nuget
{
  foreach ($o in $input)
  {
    Write-output ('Packing ' + $o.FullName)

	nuget pack $o.FullName -Symbols
  }
}

if($nugetversion)
{
	Add-AppveyorMessage -Message ('Nuget version ' + $nugetversion)

	$env:APPVEYOR_BUILD_FOLDER | get-childitem -recurse |? { $_.Name -like '*.nuspec' } | Update-NuspecVersion $nugetversion;
	$env:APPVEYOR_BUILD_FOLDER | get-childitem -recurse |? { $_.Name -like '*.nuspec' } | Pack-Nuget
}

Get-ChildItem .\*.nupkg | % { Push-AppveyorArtifact $_.FullName -FileName $_.Name }

Store bin folder from tagged build

$nugetversion = $env:DOTNETR2RMLSTORE_NUGETVERSION

function Update-NuspecVersion
{
  Param ([string]$Version)

  foreach ($o in $input)
  {
    Write-output ('Updating nuspec file ' + $o.FullName)
    $TmpFile = $o.FullName + ".tmp"

     get-content $o.FullName |
        %{$_ -replace '\$version\$', $Version } > $TmpFile

     move-item $TmpFile $o.FullName -force
  }
}

function Pack-Nuget
{
  foreach ($o in $input)
  {
    Write-output ('Packing ' + $o.FullName)

	nuget pack $o.FullName -Symbols
  }
}

if($nugetversion)
{
	Add-AppveyorMessage -Message ('Nuget version ' + $nugetversion)

	$env:APPVEYOR_BUILD_FOLDER | get-childitem -recurse |? { $_.Name -like '*.nuspec' } | Update-NuspecVersion $nugetversion;
	$env:APPVEYOR_BUILD_FOLDER | get-childitem -recurse |? { $_.Name -like '*.nuspec' } | Pack-Nuget

	Get-ChildItem .\*.nupkg | % { Push-AppveyorArtifact $_.FullName -FileName $_.Name }

	Add-AppveyorMessage -Message 'Publish bin folder of the build where nuget was created'
	Push-AppveyorArtifact 'src\Slp.r2rml4net.Storage\Slp.r2rml4net.Storage\bin' -FileName 'Slp.r2rml4net.Storage_bin'
}


### Install handy tools and apps for my dev machine
### Run this script from an administrative shell

Set-ExecutionPolicy RemoteSigned

# Install Chocolatey
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Install some software with Chocolatey
choco install -y 7zip
choco install -y dotnetcore-sdk
choco install -y git
choco install -y keepass
choco install -y linqpad
choco install -y nodejs-lts
choco install -y notepadplusplus
choco install -y poshgit
choco install -y rdcman
choco install -y sql-server-management-studio
RefreshEnv.cmd

# Install some software with npm
npm install -g @angular/cli
npm install -g typescript

Install Fira Code font with Chocolatey

### Install handy tools and apps for my dev machine
### Run this script from an administrative shell

Set-ExecutionPolicy RemoteSigned

# Install Chocolatey
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

# Install some software with Chocolatey
choco install -y 7zip
choco install -y dotnetcore-sdk
choco install -y firacode
choco install -y git
choco install -y keepass
choco install -y linqpad
choco install -y nodejs-lts
choco install -y notepadplusplus
choco install -y poshgit
choco install -y rdcman
choco install -y sql-server-management-studio
RefreshEnv.cmd

# Install some software with npm
npm install -g @angular/cli
npm install -g typescript


$url = "http://ninite.com/plex/ninite.exe"
$file = "plex.exe"

(New-Object net.webclient).DownloadFile($url, $file)

(New-Object -com shell.application).shellExecute($file)

Update the plex install script to use chocolatey

choco install plexmediaserver

## Filebot is probably optional, but great for handling renaming of tv episodes based on tvdb

choco install filebot


function prompt()
{
    $host.ui.RawUI.WindowTitle = $pwd

    Write-Host ""
    Write-Host "$pwd" -ForegroundColor DarkBlue
    Write-Host ">" -ForegroundColor DarkMagenta -NoNewline
    return " "
}

$dotfiles = "$home\dotfiles"

# Sourcing sub-dir files

foreach($item in Get-ChildItem $dotfiles -Recurse -Filter "aliases.ps1")
{
    . $item
}

# PSReadLine

$PSReadLineOptions = @{
    EditMode = "Vi"
}
Set-PSReadlineOption @PSReadLineOptions

function OnViModeChange
{
    if ($args[0] -eq 'Command')
    {
        # Set the cursor to a blinking block.
        Write-Host -NoNewLine "`e[1 q"
    }
    else
    {
        # Set the cursor to a blinking line.
        Write-Host -NoNewLine "`e[5 q"
    }
}
Set-PSReadLineOption -ViModeIndicator Script -ViModeChangeHandler $Function:OnViModeChange

Add svn status to powershell profile

function prompt()
{
    $host.ui.RawUI.WindowTitle = $pwd

    $svn_branch = get_svn_branch

    Write-Host ""
    Write-Host "$pwd" -ForegroundColor DarkBlue -NoNewline
    Write-Host " $svn_branch" -ForegroundColor DarkGray
    Write-Host "❯" -ForegroundColor DarkMagenta -NoNewline
    return " "
}

function exists($command)
{
    return Get-Command $command -errorAction SilentlyContinue
}

function get_svn_branch()
{
    if(!(exists svn)){ return "" }

    $output = svn info --show-item relative-url
    if($null -eq $output) { return "" }

    $output_split = $output.split("/")
    if($output_split.count -lt 2) { return "" }

    $location = $output_split[1] # [0] should always be ^

    if($location -eq "trunk")
    {
        return $location
    }
    elseif($location -eq "branches")
    {
        return $output_split[2]
    }
    elseif($location -eq "tags")
    {
        return $location + "/" + $output_split[2]
    }

    return ""
}

function get_svn_status() # leaving for posterity but svn st is too slow for actual prompt use
{
    if(!(exists svn)){ return "" }

    $output = svn st -q
    if($null -eq $output) { return "" }

    return "*"
}

$dotfiles = "$home\dotfiles"

foreach($item in Get-ChildItem $dotfiles -Recurse -Filter "aliases.ps1")
{
    . $item
}


Add Powershell script to build content layer images

[CmdletBinding()]
param
(
	[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,HelpMessage="Name of the output image")]
	[string] $OutputImage,
	[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,HelpMessage="Path to the SQL script")]
	[string] $SqlFile,
    [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,HelpMessage="Path to the database directory")]
    [string] $DatabaseDir
)

function PrintFatal($errorMsg)
{
    Write-Host $errorMsg -ForegroundColor Red
}

function Build($config)
{
    $initialLocation = $pwd.Path
    Try
    {
        $tempDirName = [System.Guid]::NewGuid().ToString()
        Set-Location $env:temp
        $tempDir = New-Item -Type Directory -Name $tempDirName

        Try
        {
            Set-Location $tempDir
            Copy-Item -Path $config.SqlFile -Destination ([System.IO.Path]::Combine($tempDir.FullName, 'script.sql'))

            $tempDatabaseDir = New-Item -ItemType Directory -Name 'DATA'
            ForEach ($extension in '*.mdf', '*.ldf')
            {
                Get-ChildItem -Path $config.DatabaseDir -Filter $extension | Copy-Item -Destination $tempDatabaseDir
            }

            $webClient = New-Object System.Net.WebClient
            $webClient.DownloadFile('https://raw.githubusercontent.com/turboapps/turbome/master/sqlserver/content-layer/build.me', "$tempDir\build.me")

            & "turbo.exe" build --overwrite --name $config.OutputImage build.me script.sql DATA
        }
        Finally
        {
            Set-Location $env:temp
            Remove-Item -Recurse $tempDirName
        }
    }
    Finally
    {
        Set-Location $initialLocation
    }
}

$sqlFileExists = Test-Path $SqlFile
if(-not $sqlFileExists)
{
    PrintFatal "Script file '$SqlFile' was not found"
    Exit -1
}

$databaseDirExists = Test-Path $DatabaseDir
if(-not $databaseDirExists)
{
    PrintFatal "Database directory '$DatabaseDir' was not found"
    Exit -1
}

$config = New-Object -TypeName PsObject -Property (@{
    'OutputImage' = $OutputImage;
    'SqlFile' = (Get-Item $SqlFile | % { $_.FullName });
    'DatabaseDir'= (Get-Item $DatabaseDir | % { $_.FullName });
})

Try
{
    Build $config
}
Catch
{
    PrintFatal $_.Exception.Message
    PrintFatal $_.Exception.StackTrace
    Exit -1
}


Invoke-WebRequest "https://github.com/svaarala/duktape-releases/archive/v1.4.0.zip" -OutFile ".\dependencies\duktape-1.4.0.zip"
[System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
if (Test-Path .\dependencies\duktape-1.4.0) {
    Remove-Item .\dependencies\duktape-1.4.0 -Force -Recurse
}
[System.IO.Compression.ZipFile]::ExtractToDirectory((Get-Location).ToString() + '\dependencies\duktape-1.4.0.zip', (Get-Location).ToString() + '\dependencies')
Remove-Item .\dependencies\duktape-1.4.0.zip -Force

Rename duktape release folder on windows as the folder name changed

Invoke-WebRequest "https://github.com/svaarala/duktape-releases/archive/v1.4.0.zip" -OutFile ".\dependencies\duktape-1.4.0.zip"
[System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
if (Test-Path .\dependencies\duktape-1.4.0) {
    Remove-Item .\dependencies\duktape-1.4.0 -Force -Recurse
}
[System.IO.Compression.ZipFile]::ExtractToDirectory((Get-Location).ToString() + '\dependencies\duktape-1.4.0.zip', (Get-Location).ToString() + '\dependencies')
Move-Item .\dependencies\duktape-releases-1.4.0 .\dependencies\duktape-1.4.0
Remove-Item .\dependencies\duktape-1.4.0.zip -Force


$artifactsSearchPattern = "./*.vsix"
$artifactsCollection = (Get-ChildItem $artifactsSearchPattern -Recurse)

$vsixMyGetUploadEndpoint = "https://www.myget.org/F/nanoframework-dev/vsix/upload"

# for the environment variable MyGetToken to work here it has to be set in AppVeyor UI

foreach($file in $artifactsCollection)
{
    'Uploading VSIX package to MyGet feed...' | Write-Host -ForegroundColor White -NoNewline

    $webClient = New-Object System.Net.WebClient
    $webClient.Headers.add('X-NuGet-ApiKey', $env:MyGetToken)
    $webClient.UploadFile($vsixMyGetUploadEndpoint, 'POST', $file)
    'OK' | Write-Host -ForegroundColor Green
}

Update script to skip uploading on pull requests

# skip pull requests
if ($env:APPVEYOR_PULL_REQUEST_NUMBER)
{
    return
}

$artifactsSearchPattern = "./*.vsix"
$artifactsCollection = (Get-ChildItem $artifactsSearchPattern -Recurse)

$vsixMyGetUploadEndpoint = "https://www.myget.org/F/nanoframework-dev/vsix/upload"

# for the environment variable MyGetToken to work here it has to be set in AppVeyor UI

foreach($file in $artifactsCollection)
{
    'Uploading VSIX package to MyGet feed...' | Write-Host -ForegroundColor White -NoNewline

    $webClient = New-Object System.Net.WebClient
    $webClient.Headers.add('X-NuGet-ApiKey', $env:MyGetToken)
    $webClient.UploadFile($vsixMyGetUploadEndpoint, 'POST', $file)
    'OK' | Write-Host -ForegroundColor Green
}


Add a Powershell script for running tests on windows

Set-PSDebug -Off
$ErrorActionPreference='Stop'

Write-Host "--- Extracting the artifacts ---"
mkdir -Force artifacts | out-null
tar xzf artifacts.tar.gz -C artifacts

pushd artifacts/bin

function check_help_version {
  try {
    .\bitcoind.exe -version
    .\bitcoind.exe -help
    .\bitcoin-qt.exe -version
    .\bitcoin-qt.exe -help
    .\bitcoin-cli.exe -version
    .\bitcoin-cli.exe -help
    .\bitcoin-tx.exe -help
    .\bitcoin-wallet -help
  }
  catch {
    Write-Error $_
  }
  finally {
    Stop-Process -name bitcoin-qt -Force -ErrorAction SilentlyContinue
  }
}

function check_bitcoind {
  trap {
    Stop-Process -name bitcoind -Force
  }

  Write-Host "Launching bitcoind in the background"
  Start-Process -NoNewWindow .\bitcoind.exe "-noprinttoconsole"

  for($i=60; $i -gt 0; $i--) {
    Start-Sleep -Seconds 1
    if(.\bitcoin-cli.exe help) {
      break
    }
  }
  if($i -eq 0) {
    throw "Failed to start bitcoind"
  }

  Write-Host "Stopping bitcoind"
  .\bitcoin-cli.exe stop

  for($i=60; $i -gt 0; $i--) {
    Start-Sleep -Seconds 1
    if(-Not (Get-Process -Name bitcoind -ErrorAction SilentlyContinue)) {
      break
    }
  }
  if($i -eq 0) {
    throw "Failed to stop bitcoind"
  }
}

Write-Host "--- Checking helps and versions ---"
check_help_version

Write-Host "--- Checking bitcoind can run and communicate via bitcoin-cli ---"
check_bitcoind

Write-Host "--- Running bitcoin unit tests ---"
.\test_bitcoin.exe
Write-Host "--- Running bitcoin-qt unit tests ---"
.\test_bitcoin-qt.exe -platform windows
Write-Host "--- Running pow unit tests ---"
.\test-pow.exe
Write-Host "--- Running avalanche unit tests ---"
# FIXME: figure out why the poll_inflight_timeout test fails and fix it
.\test-avalanche.exe -t !processor_tests/poll_inflight_timeout

popd

Write-Host -ForegroundColor Green "--- All checks passed ---"


###
### Install Visual Studio Code via Chocolatey and my preferred extensions
###

$Extensions = @(
    'ms-dotnettools.csharp',
    'ms-vscode.powershell',
    'ms-azuretools.vscode-docker',
    'eamodio.gitlens',
    'ms-mssql.mssql',
    'esbenp.prettier-vscode'
)

choco install vscode

foreach($Extension in $Extensions)
{
    Write-Output "Installing VSCode Extension $Extension"

    & "C:\Program Files\Microsoft VS Code\bin\code.cmd" --install-extension $Extension
}

Add Azure Db tools (incl CosmosDB)

###
### Install Visual Studio Code via Chocolatey and my preferred extensions
###

$Extensions = @(
    'ms-dotnettools.csharp',
    'ms-vscode.powershell',
    'ms-azuretools.vscode-docker',
    'eamodio.gitlens',
    'ms-mssql.mssql',
    'esbenp.prettier-vscode',
    'ms-azuretools.vscode-cosmosdb'
)

choco install vscode

foreach($Extension in $Extensions)
{
    Write-Output "Installing VSCode Extension $Extension"

    & "C:\Program Files\Microsoft VS Code\bin\code.cmd" --install-extension $Extension
}


Import-Module SwisPowerShell

# SolarWinds connection details
$hostname = 'localhost'
$username = 'admin'
$password = ''

$swis = Connect-Swis -Hostname $hostname -Username $username -Password $password

$query = "
    SELECT Uri
    FROM Cirrus.Nodes
    WHERE AgentIP = '192.0.2.0'
"
$uri = Get-SwisData $swis $query

$properties = @{
    ConnectionProfile = 1
}

Set-SwisObject $swis $uri $properties


$scriptName = 'buildAgent.ps1'

# Common expression logging and error handling function, copied, not referenced to ensure atomic process
function executeExpression ($expression) {
	$error.clear()
	Write-Host "[$scriptName] $expression"
	try {
		Invoke-Expression $expression
	    if(!$?) { Write-Host "[$scriptName] `$? = $?"; exit 1 }
	} catch { echo $_.Exception|format-list -force; exit 2 }
    if ( $error[0] ) { Write-Host "[$scriptName] `$error[0] = $error"; exit 3 }
    if (( $LASTEXITCODE ) -and ( $LASTEXITCODE -ne 0 )) { Write-Host "[$scriptName] `$LASTEXITCODE = $LASTEXITCODE "; exit $LASTEXITCODE }
}

# Use the CDAF provisioning helpers
Write-Host "`n[$scriptName] ---------- start ----------`n"

if ( Test-Path "c:\vagrant" ) {
	executeExpression 'cd c:\vagrant'
}

Write-Host "[$scriptName] Install Chocolately, Python and Python Package Manager (PiP)`n"
executeExpression "./automation/provisioning/base.ps1 'python git'"

Write-Host "[$scriptName] Use Python Package Manager (PiP) to install dependancies:`n"
cat requirements.txt

Write-Host
executeExpression 'pip install -r requirements.txt'

Write-Host "`n[$scriptName] ---------- stop ----------`n"

Load https_proxy if http_proxy has been set

$scriptName = 'buildAgent.ps1'

# Common expression logging and error handling function, copied, not referenced to ensure atomic process
function executeExpression ($expression) {
	$error.clear()
	Write-Host "[$scriptName] $expression"
	try {
		Invoke-Expression $expression
	    if(!$?) { Write-Host "[$scriptName] `$? = $?"; exit 1 }
	} catch { echo $_.Exception|format-list -force; exit 2 }
    if ( $error[0] ) { Write-Host "[$scriptName] `$error[0] = $error"; exit 3 }
    if (( $LASTEXITCODE ) -and ( $LASTEXITCODE -ne 0 )) { Write-Host "[$scriptName] `$LASTEXITCODE = $LASTEXITCODE "; exit $LASTEXITCODE }
}

# Use the CDAF provisioning helpers
Write-Host "`n[$scriptName] ---------- start ----------`n"
if ( $env:http_proxy ) {
	Write-Host "[$scriptName] Set HTTPS proxy for Python Package Manager (PiP)`n"
	executeExpression "`$env:https_proxy = '$env:http_proxy'"
}

if ( Test-Path "c:\vagrant" ) {
	executeExpression 'cd c:\vagrant'
}

Write-Host "[$scriptName] Install Chocolately, Python and Python Package Manager (PiP)`n"
executeExpression "./automation/provisioning/base.ps1 'python git'"

Write-Host "[$scriptName] Use Python Package Manager (PiP) to install dependancies:`n"
cat requirements.txt

Write-Host
executeExpression 'pip install -r requirements.txt'

Write-Host "`n[$scriptName] ---------- stop ----------`n"


Create ps script for common system logs.

$scriptLocation = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
. "$scriptLocation\config.ps1"

systeminfo >> "$openstackLogs\systeminfo.log"
wmic qfe list >> "$openstackLogs\windows_hotfixes.log"
pip freeze >> "$openstackLogs\pip_freeze.log"
ipconfig /all >> "$openstackLogs\ipconfig.log"

powershell -executionpolicy remotesigned get-netadapter ^| Select-object * >> "$openstackLogs\get_netadapter.log"
powershell -executionpolicy remotesigned get-vmswitch ^| Select-object * >> "$openstackLogs\get_vmswitch.log"
powershell -executionpolicy remotesigned get-WmiObject win32_logicaldisk ^| Select-object * >> "$openstackLogs\disk_free.log"
powershell -executionpolicy remotesigned get-netfirewallprofile ^| Select-Object * >> "$openstackLogs\firewall.log"
powershell -executionpolicy remotesigned get-process ^| Select-Object * >> "$openstackLogs\get_process.log"
powershell -executionpolicy remotesigned get-service ^| Select-Object * >> "$openstackLogs\get_service.log"

sc qc nova-compute >> "$openstackLogs\nova_compute_service.log"
sc qc neutron-hyperv-agent >> "$openstackLogs\neutron_hyperv_agent_service.log"


cd 'Visual Studio Project Template C#'
& 'C:\Program Files\7-Zip\7z.exe' a -tzip NppPlugin.zip *
cd ..
& 'C:\Program Files\7-Zip\7z.exe' a -tzip c:\temp\nppDemoAndProjectTemplate.zip *
rm 'Visual Studio Project Template C#\NppPlugin.zip'

Make buildscript also copy pluginbase to VS folder

cd 'Visual Studio Project Template C#'
& 'C:\Program Files\7-Zip\7z.exe' a -tzip NppPlugin.zip *
$path = [Environment]::GetFolderPath("MyDocuments")+'\Visual Studio 2015\Templates\ProjectTemplates\Visual C#\'
copy NppPlugin.zip $path
cd ..
& 'C:\Program Files\7-Zip\7z.exe' a -tzip c:\temp\nppDemoAndProjectTemplate.zip *
rm 'Visual Studio Project Template C#\NppPlugin.zip'


Add a script to which build contains a changese/commit

##-----------------------------------------------------------------------
## <copyright file="Get-BuildContainingChangeset.ps1">(c) Richard Fennell. </copyright>
##-----------------------------------------------------------------------
# From a changeset/commit numver find any builds that are associated

param (
    [parameter(Mandatory=$true,HelpMessage="URL of the Team Project Collection e.g. 'http://myserver:8080/tfs/defaultcollection'")]
    [string] $serverName,

    [parameter(Mandatory=$true,HelpMessage="Team Project name e.g. 'My Team project'")]
    [string] $teamproject,

    [parameter(Mandatory=$false,HelpMessage="Username for use with Password (should be blank if using Personal Access Toekn or default credentials)")]
    $username,

    [parameter(Mandatory=$false,HelpMessage="Password or Personal Access Token (if blank default credentials are used)")]
    $password,

    [parameter(Mandatory=$true,HelpMessage="Changeset/Commit number")]
    [string]$id
)

function Get-WebClient
{
param
    (
       [string]$username,
       [string]$password,
       [string]$ContentType = "application/json"
    )

    $wc = New-Object System.Net.WebClient
    $wc.Headers["Content-Type"] = $ContentType

    if ([System.String]::IsNullOrEmpty($password))
    {
        $wc.UseDefaultCredentials = $true
    } else
    {
       $pair = "${username}:${password}"
       $bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
       $base64 = [System.Convert]::ToBase64String($bytes)
       $wc.Headers.Add("Authorization","Basic $base64");
    }
    $wc
}
function Get-BuildDefinitions
{
    param (
        [string]$username,
        [string]$password,
        [string]$tfsUri)

    $wc = Get-WebClient -username $username -password $password
    $uri = "$($tfsUri)/_apis/build/definitions?api-version=4.1"
    $wc.DownloadString($uri) | ConvertFrom-Json
}

function Get-BuildByDefinition
{
    param (
        [string]$username,
        [string]$password,
        [string]$tfsUri,
        [string]$id,
        [string]$token)

    $wc = Get-WebClient -username $username -password $password
    $uri = "$($tfsUri)/_apis/build/builds?definitions=$id&deletedFilter=includeDeleted&continuationToken=$token&api-version=4.1"
    $wc.DownloadString($uri) | ConvertFrom-Json
}

$builddefs = Get-BuildDefinitions -tfsUri $serverName/$teamproject -password $password -username $username
write-verbose "Found $($builddefs.Count) build definitions"
foreach ($def in $builddefs.value)
{
    $builds = Get-BuildByDefinition -tfsUri  $serverName/$teamproject -password $password -username $username -id $def.id
    write-verbose "Found $($builds.count) builds using definition $($def.Name)"
    foreach ($build in $builds.value)
    {
        if ($build.sourceVersion -contains $id)
        {
            write-host "Changeset/Commit $id was found in the build '$($build.buildNumber)' with ID '$($build.id)'"
        }
    }
}


Add %UserProfile%\bin to %PATH% environment variable

# file    : extend-PATH-environment-variable.ps1
# author  : bryjamus <bryjamus@gmail.com>
# license : MIT

# This script:
# * Adds to %PTH% environment variable paths

Function AddTo-SystemPath {
  Param([array] $PathToAdd)
  $VerifiedPathsToAdd = $Null
  Foreach ($Path in $PathToAdd) {
    if ($env:Path -like "*$Path*") {
      Write-Host "Currnet item in path is: $Path"
      Write-Host "$Path already exists in Path statement"
    }
    else {
      $VerifiedPathsToAdd += ";$Path"
      Write-Host "`$VerifiedPathsToAdd updated to contain: $Path"
    }

    if($VerifiedPathsToAdd -ne $null) {
      Write-Host "`$VerifiedPathsToAdd contains: $verifiedPathsToAdd"
      Write-Host "Adding $Path to Path statement now..."
      [Environment]::SetEnvironmentVariable("Path",$env:Path + $VerifiedPathsToAdd,"Process")
    }
  }
}

$Path = Join-Path $ENV:UserProfile 'bin'

AddTo-SystemPath(@($Path))


# Be sure to run "Set-ExecutionPolicy RemoteSigned" before running powershell scripts

# Use TestExceptions to filter out tests with known problems, separated by a colon
# i.e. run_all_tests.ps1 -TestExceptions VkLayerTest.RequiredParameter:VkLayerTest.UnrecognizedValue

# To trigger Debug tests, specify the parameter with a hyphen
# i.e  run_all_tests.ps1 -Debug

Param(
    [switch]$Debug,
    [string]$TestExceptions
)

if ($Debug) {
    $dPath = "Debug"
} else {
    $dPath = "Release"
}

Set-Item -path env:Path -value ($env:Path + ";..\loader\$dPath")
Set-Item -path env:Path -value ($env:Path + ";gtest-1.7.0\$dPath")
$env:VK_LAYER_PATH = "..\layers\$dPath"

& $dPath\vk_loader_validation_tests
if ($lastexitcode -ne 0) {
   exit 1
}

& $dPath\vk_layer_validation_tests --gtest_filter=-$TestExceptions

exit $lastexitcode

Allow filtering loader tests on Windows

# Be sure to run "Set-ExecutionPolicy RemoteSigned" before running powershell scripts

# Use TestExceptions to filter out tests with known problems, separated by a colon
# i.e. run_all_tests.ps1 -TestExceptions VkLayerTest.RequiredParameter:VkLayerTest.UnrecognizedValue

# To trigger Debug tests, specify the parameter with a hyphen
# i.e  run_all_tests.ps1 -Debug

Param(
    [switch]$Debug,
    [string]$LoaderTestExceptions,
    [string]$TestExceptions
)

if ($Debug) {
    $dPath = "Debug"
} else {
    $dPath = "Release"
}

Set-Item -path env:Path -value ($env:Path + ";..\loader\$dPath")
Set-Item -path env:Path -value ($env:Path + ";gtest-1.7.0\$dPath")
$env:VK_LAYER_PATH = "..\layers\$dPath"

& $dPath\vk_loader_validation_tests --gtest_filter=-$LoaderTestExceptions
if ($lastexitcode -ne 0) {
   exit 1
}

& $dPath\vk_layer_validation_tests --gtest_filter=-$TestExceptions

exit $lastexitcode


Add build script for pushing packages to NuGet.org

[CmdletBinding()]
Param([Parameter(Mandatory=$True)][Version]$versionNumber)

# Move to the project root folder (parent from current script folder)

function Get-ScriptDirectory
{
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value
    Split-Path $Invocation.MyCommand.Path
}

$rootFolder = (Get-Item (Get-ScriptDirectory)).Parent.FullName
Set-Location $rootFolder

# Check NuGet is installed and updated

If (!(Test-Path .\.nuget\nuget.exe))
{
    New-Item .\.nuget -type directory -Force | Out-Null
    Invoke-WebRequest 'https://www.nuget.org/nuget.exe' -OutFile '.\.nuget\nuget.exe'
}

.\.nuget\NuGet.exe update -self

# Push packages to NuGet.org

.\.nuget\NuGet.exe push .\artifacts\Okra.Data.$versionNumber.nupkg


# Powershell script to pull the VM files from GitHub into the current folder.
# Edit the following to match the version of the VM that is compatible with this image

param
(
    [string]$VMversion="v7.0.2.1"
)

Try
{
	$scriptDir = Split-Path $script:MyInvocation.MyCommand.Path;
	Write-Host "Fetching DolphinVM.zip" $VMversion
	$source = "https://github.com/dolphinsmalltalk/DolphinVM/releases/download/$VMversion/DolphinVM.zip";
	$zipFile = $scriptDir+"\DolphinVM.zip";
	Invoke-WebRequest $source -OutFile $zipFile;
}
Catch
{
	Write-Host "Unable to fetch DolphinVM.zip" $VMversion;
	Break;
}

$shell = new-object -com shell.application;
$zip = $shell.NameSpace($zipFile);
foreach($item in $zip.items())
{
	Write-Host "..unpack" $item.Name
	$shell.Namespace($scriptDir).copyhere($item, 0x14);
}
Write-Host "Removing Zip"
Remove-Item $zipFile
Write-Host "Done fetching DolphinVM.zip" $VMversion

Upgrade to use v7.0.3 VM by default

# Powershell script to pull the VM files from GitHub into the current folder.
# Edit the following to match the version of the VM that is compatible with this image

param
(
    [string]$VMversion="v7.0.3"
)

Try
{
	$scriptDir = Split-Path $script:MyInvocation.MyCommand.Path;
	Write-Host "Fetching DolphinVM.zip" $VMversion
	$source = "https://github.com/dolphinsmalltalk/DolphinVM/releases/download/$VMversion/DolphinVM.zip";
	$zipFile = $scriptDir+"\DolphinVM.zip";
	Invoke-WebRequest $source -OutFile $zipFile;
}
Catch
{
	Write-Host "Unable to fetch DolphinVM.zip" $VMversion;
	Break;
}

$shell = new-object -com shell.application;
$zip = $shell.NameSpace($zipFile);
foreach($item in $zip.items())
{
	Write-Host "..unpack" $item.Name
	$shell.Namespace($scriptDir).copyhere($item, 0x14);
}
Write-Host "Removing Zip"
Remove-Item $zipFile
Write-Host "Done fetching DolphinVM.zip" $VMversion


Add ability to update an APIM Api from a release

<#
.SYNOPSIS
Update an APIM API with a swagger definition

.PARAMETER ResourceGroupName
The name of the resource group that contains the APIM instnace

.PARAMETER InstanceName
The name of the APIM instnace

.PARAMETER ApiName
The name of the API to update

.PARAMETER SwaggerSpecificationName
The full path to the swagger defintion

For example:
https://sit-manage-vacancy.apprenticeships.sfa.bis.gov.uk/swagger/docs/v1

#>
[CmdletBinding()]
Param(
    [Parameter(Mandatory=$true)]
    [String]$ResourceGroupName,
    [Parameter(Mandatory=$true)]
    [String]$InstanceName,
    [Parameter(Mandatory=$true)]
    [String]$ApiName,
    [Parameter(Mandatory=$true)]
    [String]$SwaggerSpecificationUrl
)

try {
    # --- Build context and retrieve apiid
    Write-Host "Building APIM context for $ResourceGroupName\$InstanceName"
    $Context = New-AzureRmApiManagementContext -ResourceGroupName $ResourceGroupName -ServiceName $InstanceName
    Write-Host "Retrieving ApiId for API $ApiName"
    $ApiId = (Get-AzureRmApiManagementApi -Context $Context -Name $ApiName).ApiId

    # --- Throw if ApiId is null
    if (!$ApiId) {
        throw "Could not retrieve ApiId for API $ApiName"
    }

    # --- Import swagger definition
    Write-Host "Updating API $ApiId\$InstanceName from definition $SwaggerSpecficiationUrl"
    Import-AzureRmApiManagementApi -Context $Context -SpecificationFormat "Swagger" -SpecificationUrl $SwaggerSpecificationUrl -ApiId $ApiId -ErrorAction Stop -Verbose:$VerbosePreference
} catch {
   throw $_
}


param(
[string]$a
)
<#
.\go.ps1 "Text Comment for Commit"

	Make sure to have a "My Dropbox" link in the Documents Library
#>
if (!$a)
{
	$a = Read-Host 'comment: or (<cr> for generic comment)'
}
if (!$a)
{
	$a = Get-Date
	$a = $a + " page updated."
}
git add -A
git commit -m $a
git push
echo "Copying webpage to Dropbox"
copy "$env:USERPROFILE\Documents\github\webpage\index.html" "$env:USERPROFILE\Documents\My Dropbox\ftp sync\index.html"

Rename 'Dropbox' folder to 'My Dropbox'

param(
[string]$a
)
<#
.\go.ps1 "Text Comment for Commit"

	Make sure to have Dropbox folder named as "My Dropbox"
#>
if (!$a)
{
	$a = Read-Host 'comment: or (<cr> for generic comment)'
}
if (!$a)
{
	$a = Get-Date
	$a = $a + " page updated."
}
git add -A
git commit -m $a
git push
echo "Copying webpage to Dropbox"
copy "$env:USERPROFILE\Documents\github\webpage\index.html" "$env:USERPROFILE\Documents\My Dropbox\ftp sync\index.html"


# Copyright 2017 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# We're going to store nvm-windows in the .\nvm directory.
$env:NVM_HOME = (Get-Item -Path ".\" -Verbose).FullName + "\nvm"

# Downloading and unpacking nvm-windows
Invoke-WebRequest -Uri https://github.com/coreybutler/nvm-windows/releases/download/1.1.5/nvm-noinstall.zip -OutFile nvm-noinstall.zip
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::ExtractToDirectory("nvm-noinstall.zip", "nvm")

$env:Path = $env:NVM_HOME + ";" + $env:Path
Out-File -Encoding "OEM" nvm\settings.txt
nvm root $env:NVM_HOME
"%*" | Out-File -Encoding "OEM" nvm\elevate.cmd

Update Windows test to force using TLS/1.2

# Copyright 2017 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# We're going to store nvm-windows in the .\nvm directory.
$env:NVM_HOME = (Get-Item -Path ".\" -Verbose).FullName + "\nvm"

# Switching to TLS/1.2 - see https://githubengineering.com/crypto-removal-notice/
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# Downloading and unpacking nvm-windows
Invoke-WebRequest -Uri https://github.com/coreybutler/nvm-windows/releases/download/1.1.5/nvm-noinstall.zip -OutFile nvm-noinstall.zip
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::ExtractToDirectory("nvm-noinstall.zip", "nvm")

$env:Path = $env:NVM_HOME + ";" + $env:Path
Out-File -Encoding "OEM" nvm\settings.txt
nvm root $env:NVM_HOME
"%*" | Out-File -Encoding "OEM" nvm\elevate.cmd


[CmdletBinding(DefaultParameterSetName='Build')]
param(
    [Parameter(Mandatory=$true,ParameterSetName='Clean')]
    [Switch]
    # Runs the build in clean mode, which removes any files, tools, packages created by previous builds.
    $Clean,

    [Parameter(Mandatory=$true,ParameterSetName='Initialize')]
    [Switch]
    # Initializes the repository.
    $Initialize
)

#Requires -Version 4
Set-StrictMode -Version Latest

& (Join-Path -Path $PSScriptRoot -ChildPath '.whiskey\Import-Whiskey.ps1' -Resolve)

$configPath = Join-Path -Path $PSScriptRoot -ChildPath 'whiskey.yml' -Resolve

$optionalArgs = @{ }
if( $Clean )
{
    $optionalArgs['Clean'] = $true
}

if( $Initialize )
{
    $optionalArgs['Initialize'] = $true
}

$context = New-WhiskeyContext -Environment 'Dev' -ConfigurationPath $configPath
Invoke-WhiskeyBuild -Context $context @optionalArgs

Add publishing API keys to Whiskey.

[CmdletBinding(DefaultParameterSetName='Build')]
param(
    [Parameter(Mandatory=$true,ParameterSetName='Clean')]
    [Switch]
    # Runs the build in clean mode, which removes any files, tools, packages created by previous builds.
    $Clean,

    [Parameter(Mandatory=$true,ParameterSetName='Initialize')]
    [Switch]
    # Initializes the repository.
    $Initialize
)

#Requires -Version 4
Set-StrictMode -Version Latest

& (Join-Path -Path $PSScriptRoot -ChildPath '.whiskey\Import-Whiskey.ps1' -Resolve)

$configPath = Join-Path -Path $PSScriptRoot -ChildPath 'whiskey.yml' -Resolve

$optionalArgs = @{ }
if( $Clean )
{
    $optionalArgs['Clean'] = $true
}

if( $Initialize )
{
    $optionalArgs['Initialize'] = $true
}

$context = New-WhiskeyContext -Environment 'Dev' -ConfigurationPath $configPath

$apiKeys = @{
    'PowerShellGallery' = 'POWERSHELL_GALLERY_API_KEY'
    'github.com' = 'GITHUB_ACCESS_TOKEN'
}

$apiKeys.Keys |
    Where-Object { Test-Path -Path ('env:{0}' -f $apiKeys[$_]) } |
    ForEach-Object {
        $apiKeyID = $_
        $envVarName = $apiKeys[$apiKeyID]
        Write-Verbose ('Adding API key "{0}" with value from environment variable "{1}".' -f $apiKeyID,$envVarName)
        Add-WhiskeyApiKey -Context $context -ID $apiKeyID -Value (Get-Item -Path ('env:{0}' -f $envVarName)).Value
    }

Invoke-WhiskeyBuild -Context $context @optionalArgs


<#
VS+MSBuild.psm1 - Visual Studio and MSBuild utilities.

Copyright (c) 2013 Precision Mojo, LLC.

This file is part of the Unity3D.DLLs project (< URL >) which is distributed under the MIT License.
Refer to the LICENSE.MIT.md document located in the project directory for licensing terms.

Several functions are copied from scripts found in David Fowler's NuGetPowerTools package (https://github.com/davidfowl/NuGetPowerTools).
NuGetPowerTools is licensed under the Apache License 2.0 (https://nuget.codeplex.com/license).
#>

function Get-ProjectFromName
{
	param (
		[Parameter(ValueFromPipelineByPropertyName=$true)]
		[String[]]$projectName
	)

	if ($projectName)
	{
		$projects = Get-Project $projectName
	}
	else
	{
		$projects = Get-Project
	}

	$projects
}

function Get-MSBuildProject
{
	param (
		[Parameter(ValueFromPipelineByPropertyName=$true)]
		[String[]]$projectName
	)

	process
	{
		(Get-ProjectFromName $projectName) | % {
			$path = $_.FullName
			@([Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($path))[0]
		}
	}
}

Extend Get-MSBuildProject to return the .user project.

<#
VS+MSBuild.psm1 - Visual Studio and MSBuild utilities.

Copyright (c) 2013 Precision Mojo, LLC.

This file is part of the Unity3D.DLLs project (< URL >) which is distributed under the MIT License.
Refer to the LICENSE.MIT.md document located in the project directory for licensing terms.

Several functions are copied from scripts found in David Fowler's NuGetPowerTools package (https://github.com/davidfowl/NuGetPowerTools).
NuGetPowerTools is licensed under the Apache License 2.0 (https://nuget.codeplex.com/license).
#>

function Get-ProjectFromName
{
	param
	(
		[Parameter(ValueFromPipelineByPropertyName=$true)]
		[String[]] $ProjectName
	)

	if ($ProjectName)
	{
		$projects = Get-Project $ProjectName
	}
	else
	{
		$projects = Get-Project
	}

	$projects
}

function Get-MSBuildProject
{
	param
	(
		[Parameter(ValueFromPipelineByPropertyName=$true)]
		[String[]] $ProjectName,
		[switch] $SpecifyUserProject
	)

	process
	{
		(Get-ProjectFromName $ProjectName) | % {
			if ($SpecifyUserProject)
			{
				$path = $_.FullName + ".user"
			}
			else
			{
				$path = $_.FullName
			}

			@([Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($path))[0]
		}
	}
}


Describe "ExecutionPolicy" {
    # We check against Windows because Linux and OS X behavior is the same
    $isWindows = [System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform([System.Runtime.InteropServices.OSPlatform]::Windows)

    Context "Check Get-ExecutionPolicy behavior" {
	It "Should throw PlatformNotSupported when not on Windows" {
	    if (!$isWindows) {
		{ Get-ExecutionPolicy } | Should Throw "Operation is not supported on this platform."
	    }
	}

	It "Should return Microsoft.Powershell.ExecutionPolicy PSObject on Windows" {
	    if ($isWindows) {
		(Get-ExecutionPolicy).GetType() | Should Be Microsoft.Powershell.ExecutionPolicy
	    }
	}
    }

    Context "Check Set-ExecutionPolicy behavior" {
	It "Should throw PlatformNotSupported when not on Windows" {
	    if (!$isWindows) {
		{ Set-ExecutionPolicy Unrestricted } | Should Throw "Operation is not supported on this platform."
	    }
	}

	It "Should succeed on Windows" {
	    if ($isWindows) {
		# We use the Process scope to avoid affecting the system
		# Unrestricted is assumed "safe", otherwise these tests would not be running
		{ Set-ExecutionPolicy -Force -Scope Process -ExecutionPolicy Unrestricted } | Should Not Throw
	    }
	}
    }
}

Fix ExecutionPolicy tests to -Skip instead of return

Describe "ExecutionPolicy" {

    Context "Check Get-ExecutionPolicy behavior" {
        It "Should throw PlatformNotSupported when not on Windows" -Skip:$IsWindows {
            { Get-ExecutionPolicy } | Should Throw "Operation is not supported on this platform."
        }

        It "Should return Microsoft.Powershell.ExecutionPolicy PSObject on Windows" -Skip:($IsLinux -Or $IsOSX) {
            (Get-ExecutionPolicy).GetType() | Should Be Microsoft.Powershell.ExecutionPolicy
        }
    }

    Context "Check Set-ExecutionPolicy behavior" {
        It "Should throw PlatformNotSupported when not on Windows" -Skip:$IsWindows {
            { Set-ExecutionPolicy Unrestricted } | Should Throw "Operation is not supported on this platform."
        }

        It "Should succeed on Windows" -Skip:($IsLinux -Or $IsOSX) {
            # We use the Process scope to avoid affecting the system
            # Unrestricted is assumed "safe", otherwise these tests would not be running
            { Set-ExecutionPolicy -Force -Scope Process -ExecutionPolicy Unrestricted } | Should Not Throw
	}
    }
}


Install-ChocolateyZipPackage 'bytemark-client' 'http://repo.bytemark.co.uk/bytemark-client/windows/bytemark-0.4.268.zip' "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"

Update chocolatey package's zip URL

Install-ChocolateyZipPackage 'bytemark-client' 'http://repo.bytemark.co.uk/bytemark-client/windows/bytemark-0.5.0.zip' "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"


$mainClass = "com.how_hard_can_it_be.primes.App"

$classPathElements=$(cat classpath.txt | ss -NotMatch '^[ 	]*#|^[ 	]*$')
write-debug "classPathElements = $classPathElements"
$classPath=""
foreach ($elt in $classPathElements)
{
	$elt = $elt.ToString().Replace( "~", $env:USERPROFILE)
    if ($(Test-Path $elt))
	{
        if ( "$classPath" -eq "" ) {}
        else
		{
            $classPath="$classPath;"
		}
        $classPath="$classPath$elt"
	}
    else
	{
        Write-Warning ("File not readable: {0}" -f $elt)
    }
}

java -cp $classPath $mainClass $Args


$root = (split-path -parent $PSScriptRoot)

Write-Host "ROOT - " + $root -ForegroundColor Magenta

$version = [System.Reflection.Assembly]::LoadFile("$root\Haarlemmertrekvaart\bin\Release\Haarlemmertrekvaart.dll").GetName().Version
$versionStr = "{0}.{1}.{2}" -f ($version.Major, $version.Minor, $version.Build)

Write-Host "Setting .nuspec version tag to $versionStr" -ForegroundColor Magenta

$content = (Get-Content $root\NuGet\Haarlemmertrekvaart.nuspec)
$content = $content -replace '\$version\$',$versionStr

$content | Out-File $root\nuget\Haarlemmertrekvaart.compiled.nuspec

Write-Host PS C:\> pathtest $($root)\NuGet" -ForegroundColor Magenta

Revert "http - NuGet path test"

$root = (split-path -parent $PSScriptRoot)

Write-Host "ROOT - " + $root -ForegroundColor Magenta

$version = [System.Reflection.Assembly]::LoadFile("$root\Haarlemmertrekvaart\bin\Release\Haarlemmertrekvaart.dll").GetName().Version
$versionStr = "{0}.{1}.{2}" -f ($version.Major, $version.Minor, $version.Build)

Write-Host "Setting .nuspec version tag to $versionStr" -ForegroundColor Magenta

$content = (Get-Content $root\NuGet\Haarlemmertrekvaart.nuspec)
$content = $content -replace '\$version\$',$versionStr

$content | Out-File $root\nuget\Haarlemmertrekvaart.compiled.nuspec

Write-Host PS C:\> pathtest $($root)\NuGet" -ForegroundColor Magenta

# $file= "Haarlemmertrekvaart.compiled.nuspec"
# Invoke-Expression "$($root)\NuGet\NuGet.exe pack $($file) -Version $($version)"


Param(
    [string]$zipPath
)

function ZipFiles( $zipfilename, $sourcedir )
{
    Add-Type -Assembly System.IO.Compression.FileSystem
    $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
    [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir,
        $zipfilename, $compressionLevel, $false)
}

$npm = echo "C:\Program Files\nodejs\npm.cmd"
if (!(test-path "$npm")) {
    $npm = echo "C:\Program Files (x86)\nodejs\npm.cmd";
}

echo "Using npm at $npm"

echo "Installing base npm modules"
cmd /C "'$npm' i"

if (test-path bin/) {
    echo "Removing bin"
    remove-item -Recurse -Force bin/
}

echo "Copying sources"
cp -r src/ bin/src/

echo "Copying package.json"
cp package.json bin/

echo "Copying README"
cp README.md bin/

echo "Copying web.config"
cp web.config bin/

echo "Moving into bin/"
cd bin/

echo "Installing production modules"
cmd /C "'$npm' i --production"

echo "Moving out of bin/"
cd ..

if (test-path $zipPath) {
    echo "Deleting old zip"
    rm $zipPath
}

echo "Creating new zip"
ZipFiles $zipPath bin/

Fix npm installer command again

Param(
    [string]$zipPath
)

function ZipFiles( $zipfilename, $sourcedir )
{
    Add-Type -Assembly System.IO.Compression.FileSystem
    $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
    [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir,
        $zipfilename, $compressionLevel, $false)
}

$npm = echo "C:\Program Files\nodejs\npm.cmd"
if (!(test-path "$npm")) {
    $npm = echo "C:\Program Files (x86)\nodejs\npm.cmd";
}

echo "Using npm at $npm"

echo "Installing base npm modules"
cmd /C "$npm" i

if (test-path bin/) {
    echo "Removing bin"
    remove-item -Recurse -Force bin/
}

echo "Copying sources"
cp -r src/ bin/src/

echo "Copying package.json"
cp package.json bin/

echo "Copying README"
cp README.md bin/

echo "Copying web.config"
cp web.config bin/

echo "Moving into bin/"
cd bin/

echo "Installing production modules"
cmd /C "$npm" i --production

echo "Moving out of bin/"
cd ..

if (test-path $zipPath) {
    echo "Deleting old zip"
    rm $zipPath
}

echo "Creating new zip"
ZipFiles $zipPath bin/


echo "--- system details"
$Properties = 'Caption', 'CSName', 'Version', 'BuildType', 'OSArchitecture'
Get-CimInstance Win32_OperatingSystem | Select-Object $Properties | Format-Table -AutoSize

# Install winrm
winrm quickconfig -q

# Install cmake
choco install cmake
$Env:path += ";C:\Program Files\CMake\mingw64\bin;C:\Program Files\CMake\usr\bin"

echo $Env:path

which cmake

ruby -v
bundle --version

echo "--- bundle install"
bundle install

echo "+++ bundle exec rake"
bundle exec rake spec

exit $LASTEXITCODE

Add Windows path for cmake test bundle dependency

echo "--- system details"
$Properties = 'Caption', 'CSName', 'Version', 'BuildType', 'OSArchitecture'
Get-CimInstance Win32_OperatingSystem | Select-Object $Properties | Format-Table -AutoSize

# Install winrm
winrm quickconfig -q

# Install cmake
choco install cmake
$Env:path += ";C:\Program Files\CMake\bin"

echo $Env:path

which cmake

ruby -v
bundle --version

echo "--- bundle install"
bundle install

echo "+++ bundle exec rake"
bundle exec rake spec

exit $LASTEXITCODE


Add tests for `scoop reset scoop` command

set-alias scoop "$psscriptroot/../bin/scoop.ps1"

describe "'scoop reset scoop'" {
  beforeall {
    remove-item "~/.bashrc.scoop" -ea ignore
  }

  function alias_count {
    (gc "~/.bashrc" | where { $_ -eq 'alias scoop="powershell scoop.ps1"' } | measure).count
  }

  function backup_bashrc_if_exists {
    # back up .bashrc if it exists
    if(test-path "~/.bashrc") {
      move-item "~/.bashrc" "~/.bashrc.scoop"
    }
  }

  function restore_bashrc_if_exists {
    # restore backup
    if(test-path "~/.bashrc.scoop") {
      move-item "~/.bashrc.scoop" "~/.bashrc"

      "~/.bashrc.scoop" | should not exist
      "~/.bashrc" | should exist
    }
  }

  context "no .bashrc" {
    it "creates .bashrc when it doesn't exist" {
      backup_bashrc_if_exists

      "~/.bashrc" | should not exist
      scoop reset scoop
      "~/.bashrc" | should exist
      alias_count | should be 1

      # cleanup
      remove-item "~/.bashrc"

      restore_bashrc_if_exists
    }
  }

  context "bash scoop alias exists" {
    it "does not create another bash scoop alias" {
      # call it once to create it if it doesn't exist
      scoop reset scoop
      alias_count | should be 1

      scoop reset scoop
      alias_count | should be 1
    }
  }

  context "bash scoop alias doesn't exist" {
    it "creates bash scoop alias" {
      backup_bashrc_if_exists
      new-item -type file "~/.bashrc"

      alias_count | should be 0

      scoop reset scoop
      alias_count | should be 1

      remove-item "~/.bashrc"
      restore_bashrc_if_exists
    }
  }
}


# Global modules directory
$global:PsGetDestinationModulePath = $PSScriptRoot + "\..\vendor\psmodules"

# Push to modules location
Push-Location -Path ($PsGetDestinationModulePath)

# Load modules from current directory
Import-Module .\PsGet\PsGet
Get-ChildItem -Exclude "PsGet" -Directory -Name | Foreach-Object {
    Import-Module .\$_\$_
}

# Come back to PWD
Pop-Location

# Set up a Cmder prompt, adding the git prompt parts inside git repos
function global:prompt {
    $realLASTEXITCODE = $LASTEXITCODE
    $Host.UI.RawUI.ForegroundColor = "White"
    Write-Host("`n" + $pwd.ProviderPath) -NoNewLine -ForegroundColor Green
    if (Get-Module posh-git) {
        Write-VcsStatus
    }
    $global:LASTEXITCODE = $realLASTEXITCODE
    Write-Host "`nλ" -NoNewLine -ForegroundColor "DarkGray"
    return " "
}

# Load special features come from posh-git
if (Get-Module posh-git) {
    Enable-GitColors
    Start-SshAgent -Quiet
}

# Move to the wanted location
if (Test-Path Env:\CMDER_START) {
    Set-Location -Path $Env:CMDER_START
} elseif ($Env:CMDER_ROOT -and $Env:CMDER_ROOT.StartsWith($pwd)) {
    Set-Location -Path $Env:USERPROFILE
}

Revert new line from commit dc834cc28f

# Global modules directory
$global:PsGetDestinationModulePath = $PSScriptRoot + "\..\vendor\psmodules"

# Push to modules location
Push-Location -Path ($PsGetDestinationModulePath)

# Load modules from current directory
Import-Module .\PsGet\PsGet
Get-ChildItem -Exclude "PsGet" -Directory -Name | Foreach-Object {
    Import-Module .\$_\$_
}

# Come back to PWD
Pop-Location

# Set up a Cmder prompt, adding the git prompt parts inside git repos
function global:prompt {
    $realLASTEXITCODE = $LASTEXITCODE
    $Host.UI.RawUI.ForegroundColor = "White"
    Write-Host $pwd.ProviderPath -NoNewLine -ForegroundColor Green
    if (Get-Module posh-git) {
        Write-VcsStatus
    }
    $global:LASTEXITCODE = $realLASTEXITCODE
    Write-Host "`nλ" -NoNewLine -ForegroundColor "DarkGray"
    return " "
}

# Load special features come from posh-git
if (Get-Module posh-git) {
    Enable-GitColors
    Start-SshAgent -Quiet
}

# Move to the wanted location
if (Test-Path Env:\CMDER_START) {
    Set-Location -Path $Env:CMDER_START
} elseif ($Env:CMDER_ROOT -and $Env:CMDER_ROOT.StartsWith($pwd)) {
    Set-Location -Path $Env:USERPROFILE
}


Param(
    [string]$zipPath
)

function ZipFiles( $zipfilename, $sourcedir )
{
    Add-Type -Assembly System.IO.Compression.FileSystem
    $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
    [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir,
        $zipfilename, $compressionLevel, $false)
}

echo "Installing base npm modules"
cmd /C '"C:\Program Files\nodejs\npm.cmd"  i'

echo "Copying sources"
cp -r src/ bin/

echo "Copying package.json"
cp package.json bin/

echo "Copying README"
cp README.md bin/

echo "Moving into bin/"
cd bin/

echo "Installing production modules"
cmd /C '"C:\Program Files\nodejs\npm.cmd" i --production'

echo "Moving out of bin/"
cd ..

if (test-path $zipPath) {
    echo "Deleting old zip"
    rm $zipPath
}

echo "Creating new zip"
ZipFiles $zipPath bin/

Update build to include web.config and clean bin/ folder

Param(
    [string]$zipPath
)

function ZipFiles( $zipfilename, $sourcedir )
{
    Add-Type -Assembly System.IO.Compression.FileSystem
    $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
    [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir,
        $zipfilename, $compressionLevel, $false)
}

echo "Installing base npm modules"
cmd /C '"C:\Program Files\nodejs\npm.cmd"  i'

echo "Removing bin"
remove-item -Recurse -Force bin/

echo "Copying sources"
cp -r src/ bin/src/

echo "Copying package.json"
cp package.json bin/

echo "Copying README"
cp README.md bin/

echo "Copying web.config"
cp web.config bin/

echo "Moving into bin/"
cd bin/

echo "Installing production modules"
cmd /C '"C:\Program Files\nodejs\npm.cmd" i --production'

echo "Moving out of bin/"
cd ..

if (test-path $zipPath) {
    echo "Deleting old zip"
    rm $zipPath
}

echo "Creating new zip"
ZipFiles $zipPath bin/


function NugetPack([bool] $pre)
{
    $Version = gitversion /output json /showvariable MajorMinorPatch
    if ($pre)
    {
        echo "Creating pre-release package..."
        $VersionSuffix = "-ci$(gitversion /output json /showvariable BuildMetaData)"
    }
    else
    {
        echo "Creating stable package..."
    }

    Get-ChildItem $PSScriptRoot -Filter *.nuspec |
    Foreach-Object {
        (Get-Content $_) | ForEach-Object { $_ -replace "%%VERSION%%", "$($VERSION)$($VersionSuffix)" } | Set-Content $_
    }

    nuget pack Azuria.Core.nuspec -version "$($VERSION)$($VersionSuffix)"
    nuget pack Azuria.Api.nuspec -version "$($VERSION)$($VersionSuffix)"
}

function MygetPush
{
    if ($env:myget_key)
    {
        Get-ChildItem $PSScriptRoot -Filter *.nupkg |
        Foreach-Object {
            nuget push $_ $env:myget_key -Source https://www.myget.org/F/infinitesoul/api/v2/package
        }
    }
}

NugetPack $env:APPVEYOR_REPO_TAG
if ($env:APPVEYOR_REPO_BRANCH -eq "master") { MygetPush }

Use gitversion environment variables for script

function NugetPack([bool] $pre)
{
    $Version = $env:GitVersion_MajorMinorPatch
    if ($pre)
    {
        echo "Creating pre-release package..."
        $VersionSuffix = "-ci$($env:GitVersion_BuildMetaData)"
    }
    else
    {
        echo "Creating stable package..."
    }

    Get-ChildItem $PSScriptRoot -Filter *.nuspec |
    Foreach-Object {
        (Get-Content $_) | ForEach-Object { $_ -replace "%%VERSION%%", "$($VERSION)$($VersionSuffix)" } | Set-Content $_
    }

    nuget pack Azuria.Core.nuspec -version "$($VERSION)$($VersionSuffix)"
    nuget pack Azuria.Api.nuspec -version "$($VERSION)$($VersionSuffix)"
}

function MygetPush
{
    if ($env:myget_key)
    {
        Get-ChildItem $PSScriptRoot -Filter *.nupkg |
        Foreach-Object {
            nuget push $_ $env:myget_key -Source https://www.myget.org/F/infinitesoul/api/v2/package
        }
    }
}

NugetPack ($env:APPVEYOR_REPO_TAG -eq "true")
if ($env:APPVEYOR_REPO_BRANCH -eq "master") { MygetPush }


$proj = (Get-Content .\GitReview\GitReview.csproj) -as [Xml]
$url = $proj.Project.ProjectExtensions.VisualStudio.FlavorProperties.WebProjectProperties.IISUrl.TrimEnd('/') + '/new'
"Url: $url"

git config --global alias.cr "push $url @:refs/heads/source @{u}:refs/heads/destination"

Enhance the cr alias to allow specifying branches.

$proj = (Get-Content .\GitReview\GitReview.csproj) -as [Xml]
$url = $proj.Project.ProjectExtensions.VisualStudio.FlavorProperties.WebProjectProperties.IISUrl.TrimEnd('/') + '/new'
"Url: $url"

$command = "git push $url " + '${1:-HEAD}:refs/heads/source ${2:-$1@{u\}}:refs/heads/destination'
$quoted = "'" + ($command -replace '\$', '\$') + "'"
git config --global alias.cr "`"!sh -c '$command' --`""
Write-Host -n "Git alias.cr: "
git config --get alias.cr


Add configuration to support SPFx (SharePoint Framework) development

#Script Name: New-EasyDevWorkstation-SPFx.ps1
#Purpose: Quick and clean way to setup a simple developer workstation for building SPFx (SharePoint Framework) webparts. Tested only for Windows 10
#Author Nissan Dookeran
#Date 23-08-2016
#Version 0.01

#set the execution policy to allow chocolatey to install and chocolatey scripts to install software
Set-ExecutionPolicy RemoteSigned

#install chocolatey
iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex
refreshenv

#Install the basics - Git, Chrome browser, updated Powershell (if running on older Windows like Win Server 2008R2)
# Visual Studio Code (which is free), and latest SQL Server Management Studio (also free)
# Utilities like Microsoft Azure Storage Explorer, Postman and Fiddler are handy to have
# nodejs is essential for building SPFx webparts, as required components installed via npm (Node Package Manager)
choco install -y --allow-empty-checksums git GoogleChrome powershell visualstudiocode sql-server-management-studio postman fiddler4 microsoftazurestorageexplorer nodejs

refreshenv
#note if these do not work, close and reopen PowerShell window as PATH hasn't updated to recognize node and npm commands

npm install -g yo gulp
npm install -g @microsoft/generator-sharepoint


## Download Chocolatey Package Manager
if(-not $env:ChocolateyInstall -or -not (Test-Path "$env:ChocolateyInstall"))
{
	iex ((new-object net.webclient).DownloadString('http://chocolatey.org/install.ps1'))
}

## Development Tools - .NET

cinst DotNet4.0

cinst DotNet4.5

cinst webpi

cinst webpicommandline

## cinst VisualStudio2013ExpressWeb

cinst VisualStudio2013Professional -InstallArguments "WebTools"

## IIS Configuration

cwindowsfeatures  IIS-WebServerRole

## cwebpi IIS7
## cwebpi IISManagementConsole
## cwebpi ASPNET
## cwebpi UrlRewrite2
## cwebpi ASPNET_REGIIS_NET4

## System Configuration

## cinst openssh

## cwindowsfeatures Microsoft-Hyper-V-All

Move DotNet install after VS, probably taken care of

## Download Chocolatey Package Manager
if(-not $env:ChocolateyInstall -or -not (Test-Path "$env:ChocolateyInstall"))
{
	iex ((new-object net.webclient).DownloadString('http://chocolatey.org/install.ps1'))
}

## Development Tools - .NET

## cinst VisualStudio2013ExpressWeb

cinst VisualStudio2013Professional -InstallArguments "WebTools"

cinst DotNet4.0

cinst DotNet4.5

cinst webpi

cinst webpicommandline

## IIS Configuration

cwindowsfeatures  IIS-WebServerRole

## cwebpi IIS7
## cwebpi IISManagementConsole
## cwebpi ASPNET
## cwebpi UrlRewrite2
## cwebpi ASPNET_REGIIS_NET4

## System Configuration

## cinst openssh

## cwindowsfeatures Microsoft-Hyper-V-All


Add attempt at a PowerShell script (not working)

$vimInstallDir = "~\vimfiles\bundle\fsharpbinding-vim"

$local = Get-Location
$vimBinDir = Join-Path $local "ftplugin\bin"
$ftpluginDir = Join-Path $local "ftplugin"
$autoloadDir = Join-Path $local "autoload"
$syntaxDir = Join-Path $local "syntax"
$ftdetectDir = Join-Path $local "ftdetect"
$syntaxCheckersDir = Join-Path $local "syntax_checkers"

$acArchive = "fsautocomplete.zip"
$acVersion = "0.15.0"

# Building

if ((Test-Path $vimBinDir) -eq 0)
{
    md $vimBinDir
}
$url = "https://github.com/fsharp/FSharp.AutoComplete/releases/downloads/" + $acVersion + "/" + $acArchive
$file = Join-Path $vimBinDir $acArchive
Write-Output $file
$client = New-Object System.Net.WebClient
# TODO: get this working
#$client.DownloadFile($url, $file)
$client.Dispose()

# Installing

rm -r $vimInstallDir
md $vimInstallDir
cp -r (Join-Path $vimInstallDir "ftplugin") $ftpluginDir
cp -r (Join-Path $vimInstallDir "autoload") $autoloadDir
cp -r (Join-Path $vimInstallDir "syntax") $syntaxDir
cp -r (Join-Path $vimInstallDir "syntax_checkers") $syntax_checkersDir
cp -r (Join-Path $vimInstallDir "ftdetect") $ftdetectDir

# TODO: test for errors and only print the following if no errors occurred.
Write-Output ("Installed to " + $vimInstallDir)


$removeAliasList = @("ac","compare","cpp","diff","sleep","sort","start","cat","cp","ls","man","mount","mv","ps","rm","rmdir")
$keepAliasList = @{cd="Set-Location"},@{dir="Get-ChildItem"},@{echo="Write-output"},@{fc="format-custom"},@{kill="stop-process"},@{clear="clear-host"}
Describe "Windows aliases do not conflict with Linux commands" {
    foreach ($alias in $removeAliasList) {
        It "Should not have certain aliases on Linux" -Skip:$IsWindows {
            Test-Path Alias:$alias | Should Be $false
        }
    }

    foreach ($alias in $keepAliasList) {
        It "Should have aliases that are Bash built-ins on Linux" {
            (Get-Alias $alias.Keys).Definition | Should Be $alias.Values
        }
    }

    It "Should have more as a function" {
        Test-Path Function:more | Should Be $true
    }
}


$vbox = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' `
    -Name "VBOX_MSI_INSTALL_PATH").VBOX_MSI_INSTALL_PATH + "VBoxManage.exe"

if (-not (Test-Path $vbox)) {
    throw "VBoxManage.exe not found!"
}

$version = (& "$vbox" --version).Split('r')[0]

$url = "https://download.virtualbox.org/virtualbox/$version/" `
    + "Oracle_VM_VirtualBox_Extension_Pack-$version.vbox-extpack"
$file = "$env:TEMP\Oracle_VM_VirtualBox_Extension_Pack-$version.vbox-extpack"

(New-Object System.Net.WebClient).DownloadFile("$url", $file)

"y" | & $vbox extpack install --replace $file

if ($LastExitCode -ne 0) {
    throw "Extension pack installation failed with exit code '$LastExitCode'"
}

Change the default machine folder for virtualbox VMs

$vbox = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' `
    -Name "VBOX_MSI_INSTALL_PATH").VBOX_MSI_INSTALL_PATH + "VBoxManage.exe"

if (-not (Test-Path $vbox)) {
    throw "VBoxManage.exe not found!"
}

$version = (& "$vbox" --version).Split('r')[0]

$url = "https://download.virtualbox.org/virtualbox/$version/" `
    + "Oracle_VM_VirtualBox_Extension_Pack-$version.vbox-extpack"
$file = "$env:TEMP\Oracle_VM_VirtualBox_Extension_Pack-$version.vbox-extpack"

(New-Object System.Net.WebClient).DownloadFile("$url", $file)

"y" | & $vbox extpack install --replace $file

if ($LastExitCode -ne 0) {
    throw "Extension pack installation failed with exit code '$LastExitCode'"
}

Write-Output "Changing default VM location..."

if (-not (Test-Path "$env:SystemDrive\Virtual Machines\VirtualBox")) {
    New-Item -Path "$env:SystemDrive\Virtual Machines\VirtualBox" -ItemType Directory | Out-Null
}

vboxmanage setproperty machinefolder "$env:SystemDrive\Virtual Machines\VirtualBox"


$BUILD_DIR = "./dist"
$BUNDLE_DIR = "$BUILD_DIR/improviz-win"
mkdir -p $BUILD_DIR

git clone --depth=1 --branch=master https://github.com/rumblesan/improviz-performance.git $BUNDLE_DIR
rm -rf $BUNDLE_DIR/.git
rm -r $BUNDLE_DIR/README.md

cp -r ./assets $BUNDLE_DIR
cp -r ./examples $BUNDLE_DIR

$DOCUMENTATION_DIR = "$BUNDLE_DIR/documentation"
mkdir -p $DOCUMENTATION_DIR
cp ./docs/getting-started.md $BUNDLE_DIR/getting-started.txt
cp ./docs/language.md $DOCUMENTATION_DIR/language.txt
cp ./docs/interacting.md $DOCUMENTATION_DIR/interacting.txt
cp ./docs/reference.md $DOCUMENTATION_DIR/reference.txt
cp ./docs/textures.md $DOCUMENTATION_DIR/textures.txt
cp ./docs/configuration.md $DOCUMENTATION_DIR/configuration.txt
./stack.exe install --local-bin-path $BUNDLE_DIR

7z a "improviz-win-${ENV:APPVEYOR_REPO_TAG_NAME}.zip" $BUNDLE_DIR

Fix bug with windows built script

$BUILD_DIR = "./dist"
$BUNDLE_DIR = "$BUILD_DIR/improviz-win"
mkdir -p $BUILD_DIR

git clone --depth=1 --branch=master https://github.com/rumblesan/improviz-performance.git $BUNDLE_DIR
rm -r -fo $BUNDLE_DIR/.git
rm -r $BUNDLE_DIR/README.md

cp -r ./assets $BUNDLE_DIR
cp -r ./examples $BUNDLE_DIR

$DOCUMENTATION_DIR = "$BUNDLE_DIR/documentation"
mkdir -p $DOCUMENTATION_DIR
cp ./docs/getting-started.md $BUNDLE_DIR/getting-started.txt
cp ./docs/language.md $DOCUMENTATION_DIR/language.txt
cp ./docs/interacting.md $DOCUMENTATION_DIR/interacting.txt
cp ./docs/reference.md $DOCUMENTATION_DIR/reference.txt
cp ./docs/textures.md $DOCUMENTATION_DIR/textures.txt
cp ./docs/configuration.md $DOCUMENTATION_DIR/configuration.txt
./stack.exe install --local-bin-path $BUNDLE_DIR

7z a "improviz-win-${ENV:APPVEYOR_REPO_TAG_NAME}.zip" $BUNDLE_DIR


write-host "Present working directory: $($pwd)"

$testsuites = [xml](get-content .\test-results\*.xml)
$anyFailures = $FALSE

foreach ($testsuite in $testsuites.testsuite) {

    write-host " $($testsuite.name)"

    foreach ($testcase in $testsuite.testcase){
        $failed = $testcase.failure
        $time = [long]$testsuite.time * 1000 # from seconds to milliseconds
        $testName = "$($testcase.classname) $($testcase.name)"

        if ($failed) {
            write-host "Failed   $($testcase.name) $($testcase.failure.message)"
            Add-AppveyorTest $testName -Outcome Failed -FileName $testsuite.name -ErrorMessage $testcase.failure.message -Duration $time
            $anyFailures = $TRUE
        }
        else {
            write-host "Passed   $($testcase.name)"
            Add-AppveyorTest $testName -Outcome Passed -FileName $testsuite.name -Duration $time
        }
    }
}

if ($anyFailures -eq $TRUE){
    write-host "Failing build as there are broken tests"
    $host.SetShouldExit(1)
}

Switch from long from double

write-host "Present working directory: $($pwd)"

$testsuites = [xml](get-content .\test-results\*.xml)
$anyFailures = $FALSE

foreach ($testsuite in $testsuites.testsuite) {

    write-host " $($testsuite.name)"

    foreach ($testcase in $testsuite.testcase){
        $failed = $testcase.failure
        $time = [double]$testsuite.time * 1000 # from seconds to milliseconds
        $testName = "$($testcase.classname) $($testcase.name)"

        if ($failed) {
            write-host "Failed   $($testcase.name) $($testcase.failure.message)"
            Add-AppveyorTest $testName -Outcome Failed -FileName $testsuite.name -ErrorMessage $testcase.failure.message -Duration $time
            $anyFailures = $TRUE
        }
        else {
            write-host "Passed   $($testcase.name)"
            Add-AppveyorTest $testName -Outcome Passed -FileName $testsuite.name -Duration $time
        }
    }
}

if ($anyFailures -eq $TRUE){
    write-host "Failing build as there are broken tests"
    $host.SetShouldExit(1)
}


$binPath = "..\src\RoslynPad\bin\Release"
$exclude =
@(
	"Xceed.Wpf.AvalonDock.Themes.Aero.dll",
	"Xceed.Wpf.AvalonDock.Themes.Metro.dll",
	"Xceed.Wpf.AvalonDock.Themes.VS2010.dll",
	"Xceed.Wpf.DataGrid.dll"
);
$files = get-childitem "$location\$binPath\*.dll" | select -ExpandProperty Name | where { $exclude -notcontains $_ }
$files +=
@(
	"RoslynPad.exe",
	"RoslynPad.Host32.exe",
	"RoslynPad.Host64.exe",
	"RoslynPad.exe.config"
)

Add config files to deployment

$binPath = "..\src\RoslynPad\bin\Release"
$exclude =
@(
	"Xceed.Wpf.AvalonDock.Themes.Aero.dll",
	"Xceed.Wpf.AvalonDock.Themes.Metro.dll",
	"Xceed.Wpf.AvalonDock.Themes.VS2010.dll",
	"Xceed.Wpf.DataGrid.dll"
);
$files = get-childitem "$location\$binPath\*.dll" | select -ExpandProperty Name | where { $exclude -notcontains $_ }
$files +=
@(
	"RoslynPad.exe",
	"RoslynPad.Host32.exe",
	"RoslynPad.Host64.exe",
	"RoslynPad.exe.config",
	"RoslynPad.Host32.exe.config",
	"RoslynPad.Host64.exe.config"
)


function GoodFunc
{
    param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Param1,
        [Parameter(Mandatory=$false)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Param2=$null
    )
    $Param1
}

function GoodFunc2($Param1 = $null)
{
    $Param1
}

Fix one other test file with trailing whitespace


$url = "https://download.microsoft.com/download/7/9/6/796EF2E4-801B-4FC4-AB28-B59FBF6D907B/VCForPython27.msi"
$output = "C:\nitor\VCForPython27.msi"
(New-Object System.Net.WebClient).DownloadFile($url, $output)
Start-Process msiexec -ArgumentList @("/i", "C:\nitor\VCForPython27.msi", "/passive", "/quiet") -NoNewWindow -Wait

pip install -U pip setuptools awscli boto3 nitor-deploy-tools

Change to be able to upgrade pip

$url = "https://download.microsoft.com/download/7/9/6/796EF2E4-801B-4FC4-AB28-B59FBF6D907B/VCForPython27.msi"
$output = "C:\nitor\VCForPython27.msi"
(New-Object System.Net.WebClient).DownloadFile($url, $output)
Start-Process msiexec -ArgumentList @("/i", "C:\nitor\VCForPython27.msi", "/passive", "/quiet") -NoNewWindow -Wait

C:\Python27\python.exe -m pip install -U pip setuptools awscli boto3 nitor-deploy-tools


Framework "4.0x86"

Task Build-Master {
	Invoke-Psake default.ps1 -properties @{autoVersion = $false; noAsync = $true}
}

Task Build-Develop {
	Invoke-Psake default.ps1 -properties @{noAsync = $true}
}


Add capacity test for initialsessionstate

Describe "InitialSessionState capacity" -Tags CI {
    BeforeAll {
        $iss = [initialsessionstate]::CreateDefault()

        for ($i = 0; $i -lt 5000; $i++)
        {
            $ssfe = [System.Management.Automation.Runspaces.SessionStateFunctionEntry]::new("f$i", "'fn f$i'")
            $iss.Commands.Add($ssfe)

            $ssve = [System.Management.Automation.Runspaces.SessionStateVariableEntry]::new("v$i", "var v$i", $null)
            $iss.Variables.Add($ssve)

            $ssae = [System.Management.Automation.Runspaces.SessionStateAliasEntry]::new("a$i", "f$i")
            $iss.Commands.Add($ssae)
        }

        $ps = [PowerShell]::Create($iss)
    }

    AfterAll {
        $ps.Dispose()
    }

    BeforeEach {
        $ps.Commands.Clear()
    }

    It "function capacity in initial session state should not be limited" {
        $ps.AddCommand('f4999').Invoke() | Should Be "fn f4999"
        $ps.Streams.Error | Should Be $null
    }

    It "alias capacity in initial session state should not be limited" {
        $ps.AddCommand('a4999').Invoke() | Should Be "fn f4999"
        $ps.Streams.Error | Should Be $null
    }

    It "variable capacity in initial session state should not be limited" {
        $ps.AddScript('$v4999').Invoke() | Should Be "var v4999"
        $ps.Streams.Error | Should Be $null
    }

    It "function capacity should not be limited after runspace is opened" {
        $ps.AddScript('function f5000 { "in f5000" } f5000').Invoke() | Should Be "in f5000"
        $ps.Streams.Error | Should Be $null
    }

    It "variable capacity should not be limited after runspace is opened" {
        $ps.AddScript('$v5000 = "var v5000"; $v5000').Invoke() | Should Be "var v5000"
        $ps.Streams.Error | Should Be $null
    }

    It "alias capacity should not be limited after runspace is opened" {
        $ps.AddScript('New-Alias -Name a5000 -Value f1; a5000').Invoke() | Should Be "fn f1"
        $ps.Streams.Error | Should Be $null
    }
}


Add script to download and run Windows Console ColorTool

# Configure the default color scheme for all Windows consoles
Write-Host -ForegroundColor DarkGreen "Downloading Windows Console ColorTool..."
$colorurl =  "https://github.com/Microsoft/console/releases/download/1810.02002/ColorTool.zip"
$colorscheme = "OneHalfDark"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest $colorurl -OutFile "ColorTool.zip"
Expand-Archive -Path "ColorTool.zip" -DestinationPath "ColorTool"
Write-Host -ForegroundColor DarkGreen "Changing color scheme to $colorscheme"
.\ColorTool\ColorTool.exe --quiet --defaults $colorscheme
Remove-Item -Path ColorTool.zip -Force

# Enable downloads for older TLS versions: https://stackoverflow.com/a/48030563/2214380
# [Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"


Add script to push nuget package to nuget

param([string]$apikey)
$pkg = ls .\XUnitRemote\bin\Debug\*.nupkg | sort-object | select-object -last 1
./nuget.exe push $pkg.FullName  -ApiKey $apikey


# Use the Git and posh-git from GitHub for Windows.
# See <http://stackoverflow.com/a/12524788>
. (Resolve-Path "$env:LOCALAPPDATA\GitHub\shell.ps1")
. $env:github_posh_git\profile.example.ps1

Import-Module PSReadLine
Set-PSReadlineOption -EditMode Emacs

# Shortcut for running chef-client. '-A' makes chef-client fail out if
# not run as administrator.
function converge {
	chef-client -A
}

function which ([string]$cmd) {
	# Use Definition instead of Path to work better with Cmdlets
	(Get-Command $cmd).Definition
}

# Matches aliases in dotfiles
New-Alias ccopy clip
New-Alias cpaste paste

Add some new PowerShell aliases.

# Use the Git and posh-git from GitHub for Windows.
# See <http://stackoverflow.com/a/12524788>
. (Resolve-Path "$env:LOCALAPPDATA\GitHub\shell.ps1")
. $env:github_posh_git\profile.example.ps1

Import-Module PSReadLine
Set-PSReadlineOption -EditMode Emacs

# Shortcut for running chef-client. '-A' makes chef-client fail out if
# not run as administrator.
function converge {
	chef-client -A
}

function which ([string]$cmd) {
	# Use Definition instead of Path to work better with Cmdlets
	(Get-Command $cmd).Definition
}

# Matches aliases in dotfiles
New-Alias ccopy clip
New-Alias cpaste paste
New-Alias c Set-Location
New-Alias l Get-ChildItem
function u () {
	 Set-Location ..
}
New-Alias py python
New-Alias ipy ipython


$es_version = "5.0.0"
If ($env:ES_VERSION) {
    $es_version = $env:ES_VERSION
}

If ($env:JAVA_HOME -eq $null -or !(Test-Path -Path $env:JAVA_HOME)) {
    Write-Error "Please ensure the latest version of java is installed and the JAVA_HOME environmental variable has been set."
    Return
}

Push-Location $PSScriptRoot

If (!(Test-Path -Path "elasticsearch-$es_version") -And !(Test-Path -Path "elasticsearch-$es_version.zip")) {
    Invoke-WebRequest "https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-$es_version.zip" -OutFile "elasticsearch-$es_version.zip"
}

If ((Test-Path -Path "elasticsearch-$es_version.zip") -And !(Test-Path -Path "elasticsearch-$es_version")) {
    Add-Type -assembly "system.io.compression.filesystem"
    [io.compression.zipfile]::ExtractToDirectory("$PSScriptRoot\elasticsearch-$es_version.zip", $PSScriptRoot)
    cp .\elasticsearch.yml .\elasticsearch-$es_version\config -Force
    rm elasticsearch-$es_version.zip
}

&"$(Get-Location)\elasticsearch-$es_version\bin\elasticsearch.bat"

Pop-Location

Revert changes to es start script

$es_version = "5.0.0"
If ($env:ES_VERSION) {
    $es_version = $env:ES_VERSION
}

If ($env:JAVA_HOME -eq $null -or !(Test-Path -Path $env:JAVA_HOME)) {
    Write-Error "Please ensure the latest version of java is installed and the JAVA_HOME environmental variable has been set."
    Return
}

Push-Location $PSScriptRoot

If (!(Test-Path -Path "elasticsearch-$es_version") -And !(Test-Path -Path "elasticsearch-$es_version.zip")) {
    Invoke-WebRequest "https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-$es_version.zip" -OutFile "elasticsearch-$es_version.zip"
}

If ((Test-Path -Path "elasticsearch-$es_version.zip") -And !(Test-Path -Path "elasticsearch-$es_version")) {
    Add-Type -assembly "system.io.compression.filesystem"
    [io.compression.zipfile]::ExtractToDirectory("$PSScriptRoot\elasticsearch-$es_version.zip", $PSScriptRoot)
    cp .\elasticsearch.yml .\elasticsearch-$es_version\config -Force
    rm elasticsearch-$es_version.zip
}

Start-Process -NoNewWindow "$(Get-Location)\elasticsearch-$es_version\bin\elasticsearch.bat"

Pop-Location


Include-PluginScripts

task SetVersion

task Pack {
	New-Item $artifactsPath -Type directory -Force | Out-Null
	Get-ChildItem $basePath\$projectName\*.nuspec -Recurse | %{ exec { & NuGet pack $_.FullName -OutputDirectory $artifactsPath } }
}

task . Clean, Compile, Test, Pack

Allow packaging only recently modified Quarks

Include-PluginScripts

function Pack-Nuspecs ($dateModified) {
	New-Item $artifactsPath -Type directory -Force | Out-Null
	$nuspecs = Get-ChildItem $basePath\$projectName\*.nuspec -Recurse
	if ($dateModified) {
		$nuspecs = $nuspecs | Where { $_.LastWriteTime -gt $dateModified }
	}
	$nuspecs | %{ exec { & NuGet pack $_.FullName -OutputDirectory $artifactsPath } }
}

task Pack {
	Pack-Nuspecs
}

task PackRecentlyModified {
	Pack-Nuspecs (Get-Date).AddDays(-1)
}

task . Clean, Compile, Test, PackRecentlyModified


# Import all scripts as functions
$Scripts = Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath 'Scripts') -File
foreach ($Script in $Scripts) {
    New-Item -Path ('Function:\{0}' -f $Script.BaseName) -Value (Get-Content -Path $Script.FullName -Raw)
}

Enable strict mode for the module

# See the help for Set-StrictMode for the full details on what this enables.
Set-StrictMode -Version 2.0

# Import all scripts as functions
$Scripts = Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath 'Scripts') -File
foreach ($Script in $Scripts) {
    New-Item -Path ('Function:\{0}' -f $Script.BaseName) -Value (Get-Content -Path $Script.FullName -Raw)
}


@{
GUID="A94C8C7E-9810-47C0-B8AF-65089C13A35A"
Author="Microsoft Corporation"
CompanyName="Microsoft Corporation"
Copyright=" Microsoft Corporation. All rights reserved."
ModuleVersion="3.0.0.0"
PowerShellVersion="3.0"
AliasesToExport = @()
FunctionsToExport = @()
CmdletsToExport="Get-Credential", "ConvertFrom-SecureString", "ConvertTo-SecureString"
NestedModules="Microsoft.PowerShell.Security.dll"
HelpInfoURI = 'http://go.microsoft.com/fwlink/?linkid=390786'
}

Add Get/Set ExecutionPolicy cmdlets back to module

@{
GUID="A94C8C7E-9810-47C0-B8AF-65089C13A35A"
Author="Microsoft Corporation"
CompanyName="Microsoft Corporation"
Copyright=" Microsoft Corporation. All rights reserved."
ModuleVersion="3.0.0.0"
PowerShellVersion="3.0"
AliasesToExport = @()
FunctionsToExport = @()
CmdletsToExport="Get-Credential", "Get-ExecutionPolicy", "Set-ExecutionPolicy", "ConvertFrom-SecureString", "ConvertTo-SecureString"
NestedModules="Microsoft.PowerShell.Security.dll"
HelpInfoURI = 'http://go.microsoft.com/fwlink/?linkid=390786'
}


# Retrieve files with a minimum number of hard links
Function Get-MultipleHardLinks {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory)]
        [IO.DirectoryInfo]$Path,

        [ValidateScript({$_ -gt 1})]
        [Int]$MinimumHardLinks=2,

        [Switch]$Recurse
    )

    $Files = Get-ChildItem -Path $Path -File -Recurse:$Recurse | Where-Object {
        $_.LinkType -eq 'HardLink' -and $_.Target.Count -ge ($MinimumHardLinks - 1)
    } | Add-Member -MemberType ScriptProperty -Name LinkCount -Value { $this.Target.Count + 1 } -Force

    return $Files
}

Function Get-NonInheritedACLs {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [String]$Path,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [String]$User
    )

    $ACLMatches = @()
    $Directories = Get-ChildItem -Path $Path -Directory -Recurse

    foreach ($Directory in $Directories) {
        $ACL = Get-ACL -Path $Directory.FullName
        $ACLNonInherited = $ACL.Access | Where-Object { $_.IsInherited -eq $false }

        if ($ACLNonInherited.IdentityReference -contains $User) {
            $ACLMatches += $Directory
        }
    }

    return $ACLMatches
}

Make User parameter optional in Get-NonInheritedACLs

# Retrieve files with a minimum number of hard links
Function Get-MultipleHardLinks {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory)]
        [IO.DirectoryInfo]$Path,

        [ValidateScript({$_ -gt 1})]
        [Int]$MinimumHardLinks=2,

        [Switch]$Recurse
    )

    $Files = Get-ChildItem -Path $Path -File -Recurse:$Recurse | Where-Object {
        $_.LinkType -eq 'HardLink' -and $_.Target.Count -ge ($MinimumHardLinks - 1)
    } | Add-Member -MemberType ScriptProperty -Name LinkCount -Value { $this.Target.Count + 1 } -Force

    return $Files
}

# Retrieve directories with non-inherited ACLs
Function Get-NonInheritedACLs {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory)]
        [IO.DirectoryInfo]$Path,

        [ValidateNotNullOrEmpty()]
        [String]$User,

        [Switch]$Recurse
    )

    $Directories = Get-ChildItem -Path $Path -Directory -Recurse:$Recurse

    $ACLMatches = @()
    foreach ($Directory in $Directories) {
        $ACL = Get-ACL -Path $Directory.FullName
        $ACLNonInherited = $ACL.Access | Where-Object { $_.IsInherited -eq $false }

        if (!$ACLNonInherited) {
            continue
        }

        if ($PSBoundParameters.ContainsKey('User')) {
            if ($ACLNonInherited.IdentityReference -notcontains $User) {
                continue
            }
        }

        $ACLMatches += $Directory
    }

    return $ACLMatches
}


Add an Appveyor forwarding script, still waiting to see if it can be improved

$VAR=Invoke-WebRequest https://raw.github.com/ndmitchell/neil/master/misc/appveyor.ps1
$TEMP=New-TemporaryFile
$FILE=$TEMP.FullName + ".ps1"
$VAR.Content | Out-File $FILE
& $FILE weeder $args


$baseDir = Resolve-Path "$PSScriptRoot/.."
$outDir = "$baseDir\out"
$msbuildExe = "C:\Program Files (x86)\MSBuild\12.0\bin\MsBuild.exe"
$nugetExe = "$baseDir\.nuget\NuGet.exe"

$configsToBuild = {"Release", "MonoRelease"}

if ($env:APPVEYOR) {
  $testExe = "xunit.console.clr4"
  $testFlags = '/appveyor'
} else {
  $testExe = "$baseDir\tools\xunit\xunit.console.clr4.exe"
  $testFlags = ''
}

git clean -xdf
& "$nugetExe" restore "$baseDir\Bugsnag.sln"

foreach-object $configsToBuild | % { & $msbuildExe "$baseDir/Bugsnag.sln" "/p:Configuration=$_" }

$filesToTest = ls -r "$baseDir\test\bin\**\Bugsnag.Test.dll"
echo $filesToTest | % { & $testExe "$_" $testFlags }

mkdir -p $outDir

& $nugetExe pack $baseDir\Bugsnag.nuspec -OutputDirectory $outDir
& $nugetExe pack $baseDir\BugsnagMono.nuspec -OutputDirectory $outDir

Move our output files to out too

$baseDir = Resolve-Path "$PSScriptRoot"
$outDir = "$baseDir\out"
$msbuildExe = "C:\Program Files (x86)\MSBuild\12.0\bin\MsBuild.exe"
$nugetExe = "$baseDir\.nuget\NuGet.exe"

$configsToBuild = {"Release", "MonoRelease"}

if ($env:APPVEYOR) {
  $testExe = "xunit.console.clr4"
  $testFlags = '/appveyor'
} else {
  $testExe = "$baseDir\tools\xunit\xunit.console.clr4.exe"
  $testFlags = ''
}

git clean -xdf
& "$nugetExe" restore "$baseDir\Bugsnag.sln"

foreach-object $configsToBuild | % { & $msbuildExe "$baseDir/Bugsnag.sln" "/p:Configuration=$_" }

$filesToTest = ls -r "$baseDir\test\bin\**\Bugsnag.Test.dll"
echo $filesToTest | % { & $testExe "$_" $testFlags }

mkdir -Path $outDir

& "$nugetExe" pack $baseDir\Bugsnag.nuspec -OutputDirectory $outDir
& "$nugetExe" pack $baseDir\BugsnagMono.nuspec -OutputDirectory $outDir
mv "$baseDir\src\Bugsnag\bin\Release\*" $outDir
ls "$baseDir\src\Bugsnag\bin\MonoRelease\*" | %{
	$monoName = "mono-" + $_.Name
	mv $_ "$outDir\$monoName"
}


Push-Location $PSScriptRoot

if(Test-Path .\artifacts) { Remove-Item .\artifacts -Force -Recurse }

& dotnet restore --no-cache

$branch = $(git symbolic-ref --short -q HEAD)
$revision = @{ $true = $env:APPVEYOR_BUILD_NUMBER; $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL];
$suffix = @{ $true = ""; $false = "$branch-$revision"}[$branch -eq "master" -and $revision -ne "local"]

foreach ($src in ls src/Serilog.*) {
    Push-Location $src

    & dotnet pack -c Release -o ..\..\.\artifacts --version-suffix=$suffix
    if($LASTEXITCODE -ne 0) { exit 1 }

    Pop-Location
}

foreach ($test in ls test/Serilog.*.Tests) {
    Push-Location $test

    & dotnet test -c Release
    if($LASTEXITCODE -ne 0) { exit 2 }

    Pop-Location
}

Pop-Location

Correct branch detection in build script

Push-Location $PSScriptRoot

if(Test-Path .\artifacts) { Remove-Item .\artifacts -Force -Recurse }

& dotnet restore --no-cache

$branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$env:APPVEYOR_REPO_BRANCH -ne $NULL];
$revision = @{ $true = $env:APPVEYOR_BUILD_NUMBER; $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL];
$suffix = @{ $true = ""; $false = "$branch-$revision"}[$branch -eq "master" -and $revision -ne "local"]

foreach ($src in ls src/Serilog.*) {
    Push-Location $src

    & dotnet pack -c Release -o ..\..\.\artifacts --version-suffix=$suffix
    if($LASTEXITCODE -ne 0) { exit 1 }

    Pop-Location
}

foreach ($test in ls test/Serilog.*.Tests) {
    Push-Location $test

    & dotnet test -c Release
    if($LASTEXITCODE -ne 0) { exit 2 }

    Pop-Location
}

Pop-Location


Param(
    [Parameter(Mandatory=$true)]
    [string]$VmId
)

# Include the following modules
$Dir = Split-Path $script:MyInvocation.MyCommand.Path
. ([System.IO.Path]::Combine($Dir, "utils\write_messages.ps1"))

# Get the VM with the given name
try {
    $VM = Get-VM -Id $VmId -ErrorAction "Stop"
    $State = $VM.state
    $Status = $VM.status
} catch [Microsoft.HyperV.PowerShell.VirtualizationException] {
    $State = "not_created"
    $Status = $State
}

$resultHash = @{
    state = "$State"
    status = "$Status"
}
$result = ConvertTo-Json $resultHash
Write-Output-Message $result

Determine status behaviour based on PS version

Param(
    [Parameter(Mandatory=$true)]
    [string]$VmId
)

# Include the following modules
$Dir = Split-Path $script:MyInvocation.MyCommand.Path
. ([System.IO.Path]::Combine($Dir, "utils\write_messages.ps1"))

if($PSVersionTable.PSVersion.Major -le 4) {
  $ExceptionType = [Microsoft.HyperV.PowerShell.VirtualizationOperationFailedException]
} else {
  $ExceptionType = [Microsoft.HyperV.PowerShell.VirtualizationException]
}

try {
    $VM = Get-VM -Id $VmId -ErrorAction "Stop"
    $State = $VM.state
    $Status = $VM.status
} catch $ExceptionType {
    $State = "not_created"
    $Status = $State
}

$resultHash = @{
    state = "$State"
    status = "$Status"
}
$result = ConvertTo-Json $resultHash
Write-Output-Message $result


Create a script to restore the release files

New-Item Releases -type directory -force

$wc = New-Object System.Net.WebClient

$wc.DownloadFile("https://s3.amazonaws.com/espera/Releases/Dev/RELEASES", ".\Releases/RELEASES");

Get-Content ".\Releases\RELEASES" | ForEach-Object {
    $_ -match ".* (.*) .*" >$null
    $filename = $matches[1]

    $wc.DownloadFile("https://s3.amazonaws.com/espera/Releases/Dev/" + $filename, ".\Releases/" + $filename);

    "Downloaded " + $filename
}


# Powershell supports only TLS 1.0 by default. Add support for TLS 1.2 and TLS 1.3
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Tls12,Tls13'

# Define script root for PowerShell 2.0
$ScriptRoot = Split-Path $script:MyInvocation.MyCommand.Path

# Download the upstream bootstrap script
(New-Object System.Net.WebClient).DownloadFile('https://winbootstrap.saltproject.io', "${ScriptRoot}\bootstrap_salt_upstream.ps1")

# Run the upstream bootstrap script with passthrough arguments
& "${ScriptRoot}\bootstrap_salt_upstream.ps1" @args

Use more conservative TLS settings to work on older .NET versions

# Powershell supports only TLS 1.0 by default. Add support for TLS 1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Tls12'

# Define script root for PowerShell 2.0
$ScriptRoot = Split-Path $script:MyInvocation.MyCommand.Path

# Download the upstream bootstrap script
(New-Object System.Net.WebClient).DownloadFile('https://winbootstrap.saltproject.io', "${ScriptRoot}\bootstrap_salt_upstream.ps1")

# Run the upstream bootstrap script with passthrough arguments
& "${ScriptRoot}\bootstrap_salt_upstream.ps1" @args


###
### Install Visual Studio Code via Chocolatey and my preferred extensions
###

$Extensions = @(
    'ms-dotnettools.csharp',
    'github.codespaces',
    'ms-vscode.powershell',
    'ms-azuretools.vscode-docker',
    'eamodio.gitlens',
    'ms-mssql.mssql',
    'esbenp.prettier-vscode',
    'ms-azuretools.vscode-cosmosdb'
)

choco install vscode

foreach($Extension in $Extensions)
{
    Write-Output "Installing VSCode Extension $Extension"

    & "C:\Program Files\Microsoft VS Code\bin\code.cmd" --install-extension $Extension
}

Add another cosmos db tool for vscode

###
### Install Visual Studio Code via Chocolatey and my preferred extensions
###

$Extensions = @(
    'ms-dotnettools.csharp',
    'github.codespaces',
    'ms-vscode.powershell',
    'ms-azuretools.vscode-docker',
    'eamodio.gitlens',
    'ms-mssql.mssql',
    'esbenp.prettier-vscode',
    'ms-azuretools.vscode-cosmosdb',
    'savranweb.cosmosdbsqlapi'
)

choco install vscode

foreach($Extension in $Extensions)
{
    Write-Output "Installing VSCode Extension $Extension"

    & "C:\Program Files\Microsoft VS Code\bin\code.cmd" --install-extension $Extension
}


Add build script for release configuration

$solutionfile = "..\AppFabric.Admin.sln"
$msbuild = $env:windir + "\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe"
$msbuildargs = $solutionfile + " /t:rebuild /property:Configuration=Release /fl /flp:logfile=releasebuild.log"
Start-Process $msbuild $msbuildargs


trap { Write-Error $_; Exit 1 }

pip install twine
twine upload dist/*

Fix twine call on Appveyor

trap { Write-Error $_; Exit 1 }

python -m pip install --disable-pip-version-check twine
python -m twine upload --verbose dist/*


chcp 65001 | out-null

function prompt {
    '[' + $env:username + '@' + $env:computername + ' ' + $pwd + "]`r`n$ "
}

function .. {
    Set-Location ..
}
function ... {
    Set-Location ..\..
}
function .... {
    Set-Location ..\..\..
}

Set-Alias l Get-ChildItem
Set-Alias ll Get-ChildItem
Set-Alias open Invoke-Item

if (Test-Path 'C:\Program Files\Sublime Text 3') {
    Set-Alias edit 'C:\Program Files\Sublime Text 3\sublime_text'
}
if (Get-Command "atom" -ErrorAction SilentlyContinue) {
    Set-Alias edit atom
}
if (Get-Command "code" -ErrorAction SilentlyContinue) {
    Set-Alias edit code
}

[net.webrequest]::defaultwebproxy.credentials = [net.credentialcache]::defaultcredentials

Use elseif for edit command

chcp 65001 | out-null

function prompt {
    '[' + $env:username + '@' + $env:computername + ' ' + $pwd + "]`r`n$ "
}

function .. {
    Set-Location ..
}
function ... {
    Set-Location ..\..
}
function .... {
    Set-Location ..\..\..
}

Set-Alias l Get-ChildItem
Set-Alias ll Get-ChildItem
Set-Alias open Invoke-Item

if (Get-Command "code" -ErrorAction SilentlyContinue) {
    function edit {
        Start-Process code -WindowStyle Minimized $args
    }
} elseif (Get-Command "atom" -ErrorAction SilentlyContinue) {
    Set-Alias edit atom
} elseif (Test-Path 'C:\Program Files\Sublime Text 3') {
    Set-Alias edit 'C:\Program Files\Sublime Text 3\sublime_text'
}

[net.webrequest]::defaultwebproxy.credentials = [net.credentialcache]::defaultcredentials


Describe 'Get-WinEvent' -Tags "CI" {

    # Get-WinEvent works only on windows
    It 'can query a System log' -Skip:(-not $IsWindows) {
        Get-WinEvent -LogName System -MaxEvents 1 | Should Not Be $null
    }
}

Add new tests for Get-WinEvent

Describe 'Get-WinEvent' -Tags "CI" {
    BeforeAll {
        if ( ! $IsWindows )
        {
            $origDefaults = $PSDefaultParameterValues.Clone()
            $PSDefaultParameterValues['it:skip'] = $true
        }
    }
    AfterAll {
        if ( ! $IsWindows ){
            $global:PSDefaultParameterValues = $origDefaults
        }
    }
    Context "Get-WinEvent ListProvider parameter" {
        It 'Get-WinEvent can list the providers' {
            $result = Get-WinEvent -listprovider * -erroraction ignore
            $result | should not BeNullOrEmpty
        }
        It 'Get-WinEvent can get a provider by name' {
            $providers = Get-WinEvent -listprovider * -erroraction ignore
            $result = Get-WinEvent -listprovider ($providers[0].name)
            $result | should not BeNullOrEmpty
        }

    }
    Context "Get-WinEvent can retrieve events" {
        # for this set of tests we need to have a provider which has multiple events
        BeforeAll {
            $foundEvents = $false
            $providers = Get-WinEvent -listprovider * -erroraction ignore
            foreach($provider in $providers) {
                $events = Get-WinEvent -provider $provider.name -erroraction ignore
                if ( $events.Count -gt 2 ) {
                    $providerForTests = $provider
                    $foundEvents = $true
                    break
                }
            }
        }
        It 'Get-WinEvent can get events from a provider' {
            # we sample the first 20 results, as this could be very large
            $results = Get-WinEvent -provider $providerForTests.Name -max 20
            foreach($event in $results ) {
                $event.providername | should be $providerForTests.name
            }
        }
        It 'Get-WinEvent can get events via logname' {
            $results = get-winevent -logname $providerForTests.LogLinks.LogName -MaxEvents 10
            $results | should not BeNullOrEmpty
        }
        It 'Get-WinEvent can use the simplest of filters' {
            $filter = @{ ProviderName = $providerForTests.Name }
            $testEvents = Get-WinEvent -filterhashtable $filter
            $testEvents.Count | should be $events.Count
        }
        It 'Get-WinEvent can use a filter which includes two items' {
            $filter = @{ ProviderName = $providerForTests.Name; Id = $events[0].Id}
            $results = Get-WinEvent -filterHashtable $filter
            $results | Should not BeNullOrEmpty
        }
    }
    # Get-WinEvent works only on windows
    It 'can query a System log' {
        Get-WinEvent -LogName System -MaxEvents 1 | Should Not BeNullOrEmpty
    }
}


###############################################################################
##
## Description:
##   Check vm, because vm is already installed by iso, so only check vm exists
##   Return passed, case is passed; return failed, case is failed
##
###############################################################################
##
## Revision:
## v1.0 - hhei - 2/21/2017 - Check vm.
##
###############################################################################

<#
.Synopsis
    reboot in vm.

.Description
    Check reboot in vm.

.Parameter vmName
    Name of the test VM.

.Parameter testParams
    Semicolon separated list of test parameters.
#>

param([String] $vmName, [String] $hvServer, [String] $testParams)
#
# Checking the input arguments
#
if (-not $vmName)
{
    "Error: VM name cannot be null!"
    exit
}

if (-not $hvServer)
{
    "Error: hvServer cannot be null!"
    exit
}

if (-not $testParams)
{
    Throw "Error: No test parameters specified"
}

#
# Display the test parameters so they are captured in the log file
#
"TestParams : '${testParams}'"

#
# Parse the test parameters
#
$rootDir = $null
$sshKey = $null
$ipv4 = $null

$params = $testParams.Split(";")
foreach ($p in $params)
{
    $fields = $p.Split("=")
    switch ($fields[0].Trim())
    {
    "sshKey"       { $sshKey = $fields[1].Trim() }
    "rootDir"      { $rootDir = $fields[1].Trim() }
    "ipv4"         { $ipv4 = $fields[1].Trim() }
    default        {}
    }
}

if (-not $rootDir)
{
    "Warn : no rootdir was specified"
}
else
{
    if ( (Test-Path -Path "${rootDir}") )
    {
        cd $rootDir
    }
    else
    {
        "Warn : rootdir '${rootDir}' does not exist"
    }
}

#
# Source the tcutils.ps1 file
#
. .\setupscripts\tcutils.ps1

PowerCLIImport
ConnectToVIServer $env:ENVVISIPADDR `
                  $env:ENVVISUSERNAME `
                  $env:ENVVISPASSWORD `
                  $env:ENVVISPROTOCOL

$result = $Failed
$vmOut = Get-VMHost -Name $hvServer | Get-VM -Name $vmName
if (-not $vmOut)
{
    Write-Error -Message "go_vm_install_by_iso: Unable to create VM object for VM $vmName" -Category ObjectNotFound -ErrorAction SilentlyContinue
}
else
{
    "Info : Find $vmName"
    $result = $Passed
}

DisconnectWithVIServer
return $result