# Create timer for window title
$count = 0
$timer = New-Object System.Timers.Timer
$timer.Interval = 1000
# Write runtime to window title
Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action {
  $count++
  $runtime = [timespan]::fromseconds($count).ToString("mm\:ss")
  $host.ui.RawUI.WindowTitle = "NESA PP Scraper - Runtime $runtime"
}
# Run crawler
scrapy crawl nesapp
# Stop timer
$timer.Stop()
# Print meta.json
write-host (Get-Content meta.json) -ForegroundColor Yellow
# Push to git
git add data.json
git add meta.json
git commit -S -m "Update data: %date% %time%"
git push

Remove timer from PowerScript - doesn't work

# Change title
$host.ui.RawUI.WindowTitle = "NESA PP Scraper - Started $(Get-Date -UFormat %T)"
# Run crawler
scrapy crawl nesapp
# Print meta.json
write-host (Get-Content meta.json) -ForegroundColor Yellow
# Push to git
git add data.json
git add meta.json
git commit -S -m "Update data: $(Get-Date -Format g)"
git push
# Prompt
Read-Host -Prompt "Press Enter to exit"


$root = (split-path -parent $MyInvocation.MyCommand.Definition)
$lib = "$root\.package\lib\45\"
if (Test-Path $lib)
{
	Remove-Item $lib -recurse
}
new-item -Path $lib -ItemType directory
new-item -Path $root\.nupkg -ItemType directory -force
Copy-Item $root\Idunn.SqlServer.Console\bin\Debug\* $lib

$version = $env:GitVersion_NuGetVersion
if ($env:APPVEYOR_REPO_BRANCH -ne "master" -and $env:APPVEYOR_REPO_TAG)
{
    $version += '-pre'
}
Write-Host "Setting .nuspec version tag to $version"

$content = (Get-Content $root\Idunn.SqlServer.nuspec -Encoding UTF8)
$content = $content -replace '\$version\$',$version

$content | Out-File $root\.package\Idunn.SqlServer.compiled.nuspec -Encoding UTF8

& NuGet.exe pack $root\.package\Idunn.SqlServer.compiled.nuspec -Version $version -OutputDirectory $root\.nupkg

Remove pointless management -pre in package.ps1

$root = (split-path -parent $MyInvocation.MyCommand.Definition)
$lib = "$root\.package\lib\45\"
if (Test-Path $lib)
{
	Remove-Item $lib -recurse
}
new-item -Path $lib -ItemType directory
new-item -Path $root\.nupkg -ItemType directory -force
Copy-Item $root\Idunn.SqlServer.Console\bin\Debug\* $lib

$version = $env:GitVersion_NuGetVersion
Write-Host "Setting .nuspec version tag to $version"

$content = (Get-Content $root\Idunn.SqlServer.nuspec -Encoding UTF8)
$content = $content -replace '\$version\$',$version

$content | Out-File $root\.package\Idunn.SqlServer.compiled.nuspec -Encoding UTF8

& NuGet.exe pack $root\.package\Idunn.SqlServer.compiled.nuspec -Version $version -OutputDirectory $root\.nupkg


<#
  .DESCRIPTION
  Pull the latest from the projects that are git subtrees.
#>

git subtree pull --prefix lib/killrvideo-docker-common git@github.com:KillrVideo/killrvideo-docker-common.git master --squash
git subtree pull --prefix lib/killrvideo-service-protos git@github.com:KillrVideo/killrvideo-service-protos.git master --squash

Add killrvideo-data to subtree pull script

<#
  .DESCRIPTION
  Pull the latest from the projects that are git subtrees.
#>

git subtree pull --prefix lib/killrvideo-docker-common git@github.com:KillrVideo/killrvideo-docker-common.git master --squash
git subtree pull --prefix lib/killrvideo-service-protos git@github.com:KillrVideo/killrvideo-service-protos.git master --squash
git subtree pull --prefix lib/killrvideo-data git@github.com:KillrVideo/killrvideo-data.git master --squash


Add powershell script to build installer.

$launcherExe = "../RXL.WPFClient/bin/Release/RXL.exe"
$versionObj = [System.Reflection.Assembly]::LoadFrom($launcherExe).GetName().Version
$version = $versionObj.Major.ToString() + "." + $versionObj.Minor.ToString() + "." + $versionObj.Build.ToString()

"Building installer, setting version to " + $version + "."

Remove-Item -Force -Recurse "AnyCPU_ReleaseSetupFiles"
Remove-Item -Force -Recurse "out"
Remove-Item -Force -Recurse "setup-cache"

$advInstallerExe = "C:/Program Files (x86)/Caphyon/Advanced Installer 11.0/bin/x86/advinst.exe"

Start-Process -NoNewWindow -Wait $advInstallerExe ("/edit setup.aip /SetVersion " + $version.ToString())
Start-Process -NoNewWindow -Wait $advInstallerExe "/rebuild setup.aip"


# Minishell is a powershell concept.
# It's primare use-case is when somebody executes a scriptblock in the new powershell process.
# The objects are automatically marshelled back to the parent session, so users can avoid custom
# serialization to pass objects between two processes.

Describe 'minishell for native executables' -Tag 'CI' {

    BeforeAll {
        $powershell = Join-Path -Path $PsHome -ChildPath "powershell"
    }

    It 'gets a hashtable object from minishell' {
        $output = & powershell { @{'a' = 'b'} }
        ($output | measure).Count | Should Be 1
        ($output.GetType().Name) | Should Be 'Hashtable'
        $output['a'] | Should Be 'b'
    }
}

Add error stream and information stream tests

# Minishell is a powershell concept.
# It's primare use-case is when somebody executes a scriptblock in the new powershell process.
# The objects are automatically marshelled back to the parent session, so users can avoid custom
# serialization to pass objects between two processes.

Describe 'minishell for native executables' -Tag 'CI' {

    BeforeAll {
        $powershell = Join-Path -Path $PsHome -ChildPath "powershell"
    }

    It 'gets a hashtable object from minishell' {
        $output = & $powershell { @{'a' = 'b'} }
        ($output | measure).Count | Should Be 1
        ($output.GetType().Name) | Should Be 'Hashtable'
        $output['a'] | Should Be 'b'
    }

    It 'gets the error stream from minishell' {
        $output = & $powershell { Write-Error 'foo' } 2>&1
        ($output | measure).Count | Should Be 1
        ($output.GetType().Name) | Should Be 'ErrorRecord'
        $output.FullyQualifiedErrorId | Should Be 'Microsoft.PowerShell.Commands.WriteErrorException'
    }

    It 'gets the information stream from minishell' {
        $output = & $powershell { Write-Information 'foo' } 6>&1
        ($output.GetType().Name) | Should Be 'InformationRecord'
        $output | Should Be 'foo'
    }
}


Describe "Get-DbaDatabase Integration Tests" -Tags "Integrationtests" {

    Context "Count system databases on localhost" {
        $results = Get-DbaDatabase -SqlInstance localhost -NoUserDb
        It "Should report the right number of databases" {
            $results.Count | Should Be 4
        }
    }

    Context "Check that master database is in Simple recovery mode" {
            $results = Get-DbaDatabase -SqlInstance localhost -Database master
            It "Should say the recovery mode of master is Simple" {
                $results.RecoveryModel | Should Be "Simple"
            }
        }
}

Add test validate the IsAccessible property

Describe "Get-DbaDatabase Integration Tests" -Tags "Integrationtests" {

	Context "Count system databases on localhost" {
		$results = Get-DbaDatabase -SqlInstance localhost -NoUserDb
		It "Should report the right number of databases" {
			$results.Count | Should Be 4
		}
	}

	Context "Check that master database is in Simple recovery mode" {
		$results = Get-DbaDatabase -SqlInstance localhost -Database master
		It "Should say the recovery mode of master is Simple" {
			$results.RecoveryModel | Should Be "Simple"
		}
	}

	Context "Check that master database is accessible" {
		$results = Get-DbaDatabase -SqlInstance localhost -Database master
		It "Should return true that master is accessible" {
			$results.IsAccessible | Should Be $true
		}
	}
}


param(
    [string] $Configuration,
    [string] $ExtensionProjectRoot,
    [string] $ExtensionOutputRoot)

"Publishing all extensions under $ExtensionProjectRoot to $ExtensionOutputRoot using the $Configuration configuration."

$outputDir = New-Item $ExtensionOutputRoot -ItemType Directory -Force
foreach ($projectDir in Get-ChildItem $ExtensionProjectRoot -Directory)
{
    $extensionName = $projectDir.Name -replace "AudioWorks.Extensions.", ""
    $projectOutputDir = $outputDir.CreateSubdirectory($extensionName)
    Start-Process "dotnet" -ArgumentList "publish -c $Configuration -o ""$($projectOutputDir.FullName)""" -WorkingDirectory $projectDir.FullName -Wait
}

Hide dotnet utility output on build.

param(
    [string] $Configuration,
    [string] $ExtensionProjectRoot,
    [string] $ExtensionOutputRoot)

"Publishing all extensions under $ExtensionProjectRoot to $ExtensionOutputRoot using the $Configuration configuration."

$outputDir = New-Item $ExtensionOutputRoot -ItemType Directory -Force
foreach ($projectDir in Get-ChildItem $ExtensionProjectRoot -Directory)
{
    $extensionName = $projectDir.Name -replace "AudioWorks.Extensions.", ""
    $projectOutputDir = $outputDir.CreateSubdirectory($extensionName)
    Start-Process "dotnet" -ArgumentList "publish -v quiet -c $Configuration -o ""$($projectOutputDir.FullName)""" -WorkingDirectory $projectDir.FullName -Wait -WindowStyle Hidden
}


<#
VS.psm1 - Visual Studio utilities.

Copyright (c) 2013 Precision Mojo, LLC.
Copyright (c) 2017 Marcus R. Brown <me@igetgam.es>

This file is part of the Unity3D.DLLs project (http://precisionmojo.github.io/Unity3D.DLLs/) which is distributed
under the MIT License. Refer to the LICENSE.MIT.md document located in the project directory for licensing terms.

Some functions are based on code 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 Resolve-ProjectName
{
	param
	(
		[Parameter(ValueFromPipelineByPropertyName=$true)]
		[String[]] $ProjectName
	)

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

	$projects
}

Export-ModuleMember Resolve-ProjectName

Fix an issue with accessing projects within a solution folder.

<#
VS.psm1 - Visual Studio utilities.

Copyright (c) 2013 Precision Mojo, LLC.
Copyright (c) 2017 Marcus R. Brown <me@igetgam.es>

This file is part of the Unity3D.DLLs project (http://precisionmojo.github.io/Unity3D.DLLs/) which is distributed
under the MIT License. Refer to the LICENSE.MIT.md document located in the project directory for licensing terms.

Some functions are based on code 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 Resolve-ProjectName
{
	param
	(
		[Parameter(ValueFromPipelineByPropertyName=$true)]
		[String[]] $ProjectName
	)

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

	$projects
}

Export-ModuleMember Resolve-ProjectName


mkdir NuGet
nuget pack ".\Domain\Domain.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"
nuget pack ".\Domain.Api\Domain.Api.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"
nuget pack ".\Domain.EventStore\Domain.EventStore.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"
nuget pack ".\Domain.Sql\Domain.Sql.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"
nuget pack ".\Domain.Testing\Domain.Testing.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"
nuget pack ".\EventStore\EventStore.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"
nuget pack ".\Recipes\Recipes.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"

Update nuget packaging script to remove EventStore

rm -Force -Recurse .\NuGet
mkdir NuGet
nuget pack ".\Domain\Domain.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"
nuget pack ".\Domain.Api\Domain.Api.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"
nuget pack ".\Domain.Sql\Domain.Sql.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"
nuget pack ".\Domain.Testing\Domain.Testing.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"
nuget pack ".\Recipes\Recipes.csproj" -Properties "Configuration=Release;Platform=AnyCPU" -OutputDirectory ".\NuGet"


if (($env:appveyor_repo_tag -eq "True") -and ($env:appveyor_repo_branch.StartsWith("v"))) {
    Invoke-Expression "$env:PYTHON/Scripts/twine upload -u landlab -p $env:PYPI_PASS dist/*"
}

Call twine command without full path.

if (($env:appveyor_repo_tag -eq "True") -and ($env:appveyor_repo_branch.StartsWith("v"))) {
    Invoke-Expression "twine upload -u landlab -p $env:PYPI_PASS dist/*"
}


$CommandName = $MyInvocation.MyCommand.Name.Replace(".ps1", "")
Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan
. "$PSScriptRoot\constants.ps1"

Describe "$CommandName Integration Tests" -Tags "IntegrationTests" {
	Context "Verifying output" {
		BeforeAll {
			$tfs = 3226,3604
			Write-Host "Quick check on current global TFs enabled"
			$server = Connect-DbaSqlServer -SqlInstance $script:instance1
			$checkResults = $server.Query("DBCC TRACESTATUS(-1)")
			if ($checkResults.Count -gt 0) {
				Write-Host "Found $($checkResults.Count) global TFs enabled, need to disable them" -ForegroundColor Cyan
				foreach ($result in $checkResults) {
					$tf = $result.TraceFlag
					$sql = "DBCC TRACEOFF($tf,-1);"
					$server.Query($sql)
				}
			}
			Write-Host "Enabling global TFs for testing"
			foreach ($tf in $tfs) {
				$sql = "DBCC TRACEON($tf,-1) WITH NO_INFOMSGS;"
				$server.Query($sql)
				Write-Host "$tf enabled"
			}
			$checkResults = $server.Query("DBCC TRACESTATUS(-1)")
			Write-Host "$($CheckResults.Count) TFs enabled."
		}
		AfterAll {
			Write-Host "Cleaning up TFs enabled"
			$server = Connect-DbaSqlServer -SqlInstance $script:instance1
			foreach ($tf in $tfs) {
				$sql = "DBCC TRACEOFF($tf,-1) WITH NO_INFOMSGS;"
				$server.Query($sql)
			}
		}

		It "Has the right default properties" {
			$expectedProps = 'ComputerName,InstanceName,SqlInstance,TraceFlag,Global,Status'.Split(',')
			$results = Get-DbaTraceFlag -SqlInstance $script:instance1
			($results[0].PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames | Sort-Object) | Should Be ($expectedProps | Sort-Object)
		}
		It "Returns filtered results" {
			$tf = $tfs[0]
			Write-Host "Checking for TF $tf"
			$fResults = Get-DbaTraceFlag -SqlInstance $script:instance1 -TraceFlag $tf
			($fResults | Measure-Object).Count | Should Be 1
		}
		It "Returns following number of TFs: $($tfs.Count)" {
			$results = Get-DbaTraceFlag -SqlInstance $script:instance1
			($results | Measure-Object).Count | Should Be 2
		}
	}
}


$location = 'Australia East'
$loc = 'aue'
$rg = 'hellovnetrouteall-rg'
$plan = "hellovnetrouteall-$loc-plan"
$tags = 'project=private-paas'
$app = "hellovnetrouteall-$loc"
$vnet = "hellovnetrouteall-$loc-vnet"
$planSubnet = 'asp'
$nsg = 'deny-all-internet-out'

# Create resource group
az group create -n $rg --location $location --tags $tags

# Create App Service Plan
az appservice plan create -n $plan -g $rg --location $location --sku S1 --tags $tags

# Create App and deploy test app from Github
az webapp create -n $app --plan $plan -g $rg --tags $tags `
    --deployment-source-url 'https://github.com/DanielLarsenNZ/HelloAspDotNetCore'

# Create a VNet
az network vnet create -n $vnet -g $rg --location $location --subnet-name $planSubnet --tags $tags

# APP SERVICE PLAN Regional VNET Integration
az webapp vnet-integration add --name $app -g $rg --subnet $planSubnet --vnet $vnet

# Set Website VNET Route all and configure app to try to connect to Dropbox.com
az webapp config appsettings set -n $app -g $rg --settings "WEBSITE_VNET_ROUTE_ALL=1" "GetUrls=https://www.dropbox.com/"

# Create an NSG to deny all internet outbound
az network nsg create -g $rg -n $nsg --tags $tags
az network nsg rule create -g $rg --nsg-name $nsg -n 'DenyInternetOutbound' --priority 100 `
    --direction 'Outbound' --source-address-prefixes '*' --source-port-ranges '*' `
    --destination-address-prefixes 'Internet' --destination-port-ranges '*' --access Deny `
    --protocol '*' --description "Deny any outbound to internet"

# Assign to subnet
az network vnet subnet update -g $rg -n $planSubnet --vnet-name $vnet --network-security-group $nsg

# Open the app in the browser
start "https://$app.azurewebsites.net"

# Tear down
# & az group delete -n $rg --yes


$temp_directory = "$env:APPVEYOR_BUILD_FOLDER\Deploy\Portable\~TEMP"
New-Item "$temp_directory" -type directory

$zip_archive = "$env:APPVEYOR_BUILD_FOLDER\Deploy\Portable\Tabster $env:APPVEYOR_BUILD_VERSION Portable.exe"

# build using portable configuration
& msbuild.exe "$env:APPVEYOR_BUILD_FOLDER\Tabster.sln" /p:Configuration=Portable

$output_directory = "$env:APPVEYOR_BUILD_FOLDER\Tabster\bin\Portable"

# copy .exe, .dll, .config files
Copy-Item "$output_directory\*.exe" "$temp_directory"
Copy-Item "$output_directory\*.dll" "$temp_directory"
Copy-Item "$output_directory\*.config" "$temp_directory"

# copy subfolders recursively
Get-ChildItem -Path "$output_directory" -Recurse | ?{ $_.PSIsContainer } | Copy-Item -Destination "$temp_directory" -Force -Container

# zip contents in self-extracting archive
& 7z a -r -mmt -mx5 -sfx7z.sfx "$zip_archive" "$temp_directory\*.*"

# move executable to project directory for clean AppVeyor artifact name
Move-Item "$zip_archive" "$env:APPVEYOR_BUILD_FOLDER"

Use absolute path for 7z

$temp_directory = "$env:APPVEYOR_BUILD_FOLDER\Deploy\Portable\~TEMP"
New-Item "$temp_directory" -type directory

$zip_archive = "$env:APPVEYOR_BUILD_FOLDER\Deploy\Portable\Tabster $env:APPVEYOR_BUILD_VERSION Portable.exe"

# build using portable configuration
& msbuild.exe "$env:APPVEYOR_BUILD_FOLDER\Tabster.sln" /p:Configuration=Portable

$output_directory = "$env:APPVEYOR_BUILD_FOLDER\Tabster\bin\Portable"

# copy .exe, .dll, .config files
Copy-Item "$output_directory\*.exe" "$temp_directory"
Copy-Item "$output_directory\*.dll" "$temp_directory"
Copy-Item "$output_directory\*.config" "$temp_directory"

# copy subfolders recursively
Get-ChildItem -Path "$output_directory" -Recurse | ?{ $_.PSIsContainer } | Copy-Item -Destination "$temp_directory" -Force -Container

# zip contents in self-extracting archive
& "C:\ProgramData\chocolatey\lib\7zip.commandline\7z.exe" a -r -mmt -mx5 -sfx7z.sfx "$zip_archive" "$temp_directory\*.*"

# move executable to project directory for clean AppVeyor artifact name
Move-Item "$zip_archive" "$env:APPVEYOR_BUILD_FOLDER"


Describe "Add-Type" {
    It "Should not throw given a simple class definition" {
        { Add-Type -TypeDefinition "public static class foo { }" } | Should Not Throw
    }
}

Make Add-Type test -Pending until it passes on Windows

Describe "Add-Type" {
    It -Pending "Should not throw given a simple class definition" {
        { Add-Type -TypeDefinition "public static class foo { }" } | Should Not Throw
    }
}


# Remove the default Windows Apps from the image
#
# Seriously, who uses these dumb things?
#
# To get the name of the packages:
# - Dism.exe /online /get-ProvisionedAppxPackages
#
# Alternately, on a live machine, you can run:
# - Dism.exe /online /Remove-ProvisionedAppxPackage /PackageName:microsoft.windowsphotos_16.4.4396.311_x64__8wekyb3d8bbwe
# - Dism.exe /online /Remove-ProvisionedAppxPackage /PackageName:Microsoft.ZuneVideo_1.5.802.0_x64__8wekyb3d8bbwe
#
$AppList = "Microsoft.Reader",
           "Microsoft.WindowsScan",
           "microsoft.windowscommunicationsapps",
           "Microsoft.WindowsReadingList",
           "Microsoft.XboxLIVEGames",
           "Microsoft.ZuneMusic",
           "microsoft.windowsphotos",
           "Microsoft.bingTravel",
           "Microsoft.bingMaps",
           "Microsoft.bingFinance",
           "Microsoft.bingFoodAndDrink",
           "Microsoft.bingHealthAndFitness",
           "Microsoft.ZuneVideo"

ForEach ($App in $AppList) {
   $AppxPackage = Get-AppxProvisionedPackage -online | Where {$_.DisplayName -eq $App}
   Remove-AppxProvisionedPackage -online -packagename ($AppxPackage.PackageName) -ErrorAction SilentlyContinue
   Remove-AppxPackage ($AppxPackage.PackageName) -ErrorAction SilentlyContinue
}


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

if (Get-Command Import-Module -ErrorAction SilentlyContinue) {
    Import-Module PSReadLine

    Set-PSReadlineKeyHandler -Key Ctrl+d -Function DeleteCharOrExit

    $ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
    if (Test-Path($ChocolateyProfile)) {
        Import-Module "$ChocolateyProfile"
    }

}

Remove exit & duplicates from powershell history

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

if (Get-Command Import-Module -ErrorAction SilentlyContinue) {
    Import-Module PSReadLine

    Set-PSReadlineKeyHandler -Key Ctrl+d -Function DeleteCharOrExit

    $PSReadLineOptions = @{
        HistoryNoDuplicates = $true
        AddToHistoryHandler = {
            param($line)
            if ($line -eq 'exit') {
                return $false
            }
            $true
        }
    }
    Set-PSReadLineOption @PSReadLineOptions

    $ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
    if (Test-Path($ChocolateyProfile)) {
        Import-Module "$ChocolateyProfile"
    }

}


Set-ExecutionPolicy Bypass -scope Process
New-Item -Type Directory -Path "$($env:ProgramFiles)\docker"
wget -outfile $env:TEMP\docker-1.12.0.zip https://get.docker.com/builds/Windows/x86_64/docker-1.12.0.zip
Expand-Archive -Path $env:TEMP\docker-1.12.0.zip -DestinationPath $env:TEMP -Force
copy $env:TEMP\docker\*.exe $env:ProgramFiles\docker
Remove-Item $env:TEMP\docker-1.12.0.zip
[Environment]::SetEnvironmentVariable("Path", $env:Path + ";$($env:ProgramFiles)\docker", [EnvironmentVariableTarget]::Machine)
$env:Path = $env:Path + ";$($env:ProgramFiles)\docker"
. dockerd --register-service -H npipe:// -H 0.0.0.0:2375 -G docker

Start-Service Docker

Write-Host "Installing WindowsServerCore docker image..."
docker pull microsoft/windowsservercore:10.0.14300.1030
docker pull microsoft/windowsservercore

if ((get-windowsfeature Hyper-V | where installed).count) {
  Write-Host "Installing NanoServer docker image..."
  docker pull microsoft/nanoserver:10.0.14300.1030
  docker pull microsoft/nanoserver
} else {
  Write-Host "Skipping NanoServer docker image"
}

Update to latest working Docker 1.12.1 with TP5

Set-ExecutionPolicy Bypass -scope Process
New-Item -Type Directory -Path "$($env:ProgramFiles)\docker"
wget -outfile $env:TEMP\docker-1.12.1.zip https://get.docker.com/builds/Windows/x86_64/docker-1.12.1.zip
Expand-Archive -Path $env:TEMP\docker-1.12.1.zip -DestinationPath $env:TEMP -Force
copy $env:TEMP\docker\*.exe $env:ProgramFiles\docker
Remove-Item $env:TEMP\docker-1.12.1.zip
[Environment]::SetEnvironmentVariable("Path", $env:Path + ";$($env:ProgramFiles)\docker", [EnvironmentVariableTarget]::Machine)
$env:Path = $env:Path + ";$($env:ProgramFiles)\docker"
. dockerd --register-service -H npipe:// -H 0.0.0.0:2375 -G docker

Start-Service Docker

Write-Host "Installing WindowsServerCore docker image..."
docker pull microsoft/windowsservercore:10.0.14300.1030
docker pull microsoft/windowsservercore

if ((get-windowsfeature Hyper-V | where installed).count) {
  Write-Host "Installing NanoServer docker image..."
  docker pull microsoft/nanoserver:10.0.14300.1030
  docker pull microsoft/nanoserver
} else {
  Write-Host "Skipping NanoServer docker image"
}


function New-Guid {
    [System.Guid]::NewGuid().ToString("d").Substring(0, 6).Replace("-", "")
}

Change test framework to use 4 chars of guid for random names.

function New-Guid {
    [System.Guid]::NewGuid().ToString("d").Substring(0, 4).Replace("-", "")
}


Test sql connect-ability from power shell script

##Use this to test connections and firewalls to an SQL database when no sql client is installed on a computer.

$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=tcp:cidatabaseserver.database.windows.net,1433;Database=******;User ID=*****;Password=*****);Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
$conn.open()
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.connection = $conn
$cmd.commandtext = "select * from sys.databases"
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter

$SqlAdapter.SelectCommand = $cmd

$DataSet = New-Object System.Data.DataSet

$SqlAdapter.Fill($DataSet)

foreach ($row in $DataSet.Tables[0].Rows){

write-Host ($row[1].ToString().Trim())

write-Host  ($row[2].ToString())

Write-Host  ($row[3].ToString().Trim())

}

$conn.Close()


MSBuild.SonarQube.Runner.exe end /d:"sonar.login=$env:SONARQUBE_TOKEN"

Add codecov to the build

MSBuild.SonarQube.Runner.exe end /d:"sonar.login=$env:SONARQUBE_TOKEN"

pip install codecov
codecov -f "coverage.xml" -t $env:CODECOV_TOKEN


<#
.Synopsis
   DSC Configuration Template for DSC Resource Integration tests.
.DESCRIPTION
   To Use:
     1. Copy to \Tests\Integration\ folder and rename MSFT_<ResourceName>.config.ps1 (e.g. MSFT_xFirewall.config.ps1)
     2. Customize TODO sections.

.NOTES
#>

# TODO: Modify ResourceName
configuration 'MSFT_<ResourceName>_config' {
    Import-DscResource -Name 'MSFT_<ResourceName>'
    node localhost {
       # TODO: Modify ResourceName
       '<ResourceName>' Integration_Test {
            # TODO: Fill Configuration Code Here
       }
    }
}

# TODO: (Optional): Add More Configuration Templates

Fix Integrtion Test Config template by removing quotes

<#
.Synopsis
   DSC Configuration Template for DSC Resource Integration tests.
.DESCRIPTION
   To Use:
     1. Copy to \Tests\Integration\ folder and rename MSFT_<ResourceName>.config.ps1 (e.g. MSFT_xFirewall.config.ps1)
     2. Customize TODO sections.

.NOTES
#>

# TODO: Modify ResourceName
configuration 'MSFT_<ResourceName>_config' {
    Import-DscResource -Name 'MSFT_<ResourceName>'
    node localhost {
       # TODO: Modify ResourceName
       <ResourceName> Integration_Test {
            # TODO: Fill Configuration Code Here
       }
    }
}

# TODO: (Optional): Add More Configuration Templates


$scripts = Get-ChildItem -Path $PSScriptRoot -Recurse -Filter *.ps1 |
                Where-Object FullName -NotMatch '.Tests.'

Describe -Tag 'Help' 'Help' {

    foreach ($script in $scripts) {

        Context "[$(($script.Name).TrimEnd('.ps1'))] Validate Comment Based Help" {
            # Dot Source script
            . .\$script.FullName

            $functionHelp = Get-Help ($script.Name).TrimEnd('.ps1') -Full

            It 'Contains Description' {
                $functionHelp.Description | Should Not BeNullOrEmpty
            }

            It 'Contains Synopsis' {
                $functionHelp.Synopsis | Should Not BeNullOrEmpty
            }

            It 'Contains Examples' {
                $functionHelp.Examples | Should Not BeNullOrEmpty
            }

            It 'Contains Parameters' {
                $functionHelp.Parameters | Should Not BeNullOrEmpty
            }
        }
    }
}

Use basename instead of trim

$scripts = Get-ChildItem -Path $PSScriptRoot -Recurse -Filter *.ps1 |
                Where-Object FullName -NotMatch '.Tests.'

Describe -Tag 'Help' 'Help' {

    foreach ($script in $scripts) {

        Context "[$($script.BaseName)] Validate Comment Based Help" {
            # Dot Source script
            . $($script.FullName)

            $functionHelp = Get-Help ($script.Name).TrimEnd('.ps1') -Full

            It 'Contains Description' {
                $functionHelp.Description | Should Not BeNullOrEmpty
            }

            It 'Contains Synopsis' {
                $functionHelp.Synopsis | Should Not BeNullOrEmpty
            }

            It 'Contains Examples' {
                $functionHelp.Examples | Should Not BeNullOrEmpty
            }

            It 'Contains Parameters' {
                $functionHelp.Parameters | Should Not BeNullOrEmpty
            }
        }
    }
}


param($installPath, $toolsPath, $package, $project)

$project.Properties.Item("PostBuildEvent").Value = "if `$(ConfigurationName) == Debug ""`$(ProjectDir)CupCake.Debug.exe"" Deploy `$(TargetDir)"

$asms = $package.AssemblyReferences | %{$_.Name}

foreach ($reference in $project.Object.References)
{
    if ($asms -contains $reference.Name + ".dll")
    {
        $reference.CopyLocal = $false;
    }
}

$project.Properties | where { $_.Name -eq "StartAction" } | foreach { $_.Value = "Program" }
$project.Properties | where { $_.Name -eq "StartProgram" } | foreach { $_.Value = "$(MSBuildProjectDirectory)\CupCake.Debug.exe" }
$project.Properties | where { $_.Name -eq "StartArguments" } | foreach { $_.Value = "Debug" }

Remove editing start action for now


##Looks through the entire src directory and runs nuget pack with dependencies added on each csproj found
##foreach file in src/*
foreach($f in Get-ChildItem ./src/)
{
    ##foreach file in the src/*/ directory that ends with the .csproj format
    foreach($ff in (Get-ChildItem (Join-Path ./src/ $f.Name) | Where-Object { $_.Name.EndsWith(".csproj") }))
    {
        ##Add the project path + the csproj name and add the include referenced projects argument which will
        ##force nuget dependencies
        $projectArgs = "pack " + (Join-Path (Join-Path src/ $f.Name) $ff.Name)## + "-c Release -IncludeReferencedProjects"
        Start-Process dotnet $projectArgs -Wait
    }
}

Start-Process ILRepack.exe "/out:.\src\Reinterpret.Net\bin\Release\net20\Reinterpret.Net.dll .\src\Reinterpret.Net\bin\Release\net20\Reinterpret.Net.dll  .\src\Reinterpret.Net\bin\Release\net20\UnsafeAs.Backport.dll" -Wait
Start-Process ILRepack.exe "/out:.\src\Reinterpret.Net\bin\Release\net30\Reinterpret.Net.dll .\src\Reinterpret.Net\bin\Release\net30\Reinterpret.Net.dll  .\src\Reinterpret.Net\bin\Release\net30\UnsafeAs.Backport.dll" -Wait
Start-Process ILRepack.exe "/out:.\src\Reinterpret.Net\bin\Release\net35\Reinterpret.Net.dll .\src\Reinterpret.Net\bin\Release\net35\Reinterpret.Net.dll  .\src\Reinterpret.Net\bin\Release\net35\UnsafeAs.Backport.dll" -Wait
Start-Process ILRepack.exe "/out:.\src\Reinterpret.Net\bin\Release\net40\Reinterpret.Net.dll .\src\Reinterpret.Net\bin\Release\net40\Reinterpret.Net.dll  .\src\Reinterpret.Net\bin\Release\net40\UnsafeAs.Backport.dll" -Wait

Remove ILRepacking from MyGet powershell script


Describe "Tee-Object" {

    Context "Validate Tee-Object is correctly forking output" {

	$testfile = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath assets) -ChildPath testfile.txt

	It "Should return the output to the screen and to the variable" {
	    $teefile = $testfile
	    echo teeobjecttest1 | Tee-Object -variable teeresults
	    $teeresults         | Should Be "teeobjecttest1"
	    Remove-Item $teefile -ErrorAction SilentlyContinue
	}

	It "Should tee the output to a file" {
	    $teefile = $testfile
	    echo teeobjecttest3  | Tee-Object $teefile
	    Get-Content $teefile | Should Be "teeobjecttest3"
	    Remove-Item $teefile -ErrorAction SilentlyContinue
	}
    }
}

Add Unit Test For Tee-Object

Describe "Tee-Object" {

    Context "Validate Tee-Object is correctly forking output" {

	$testfile = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath assets) -ChildPath testfile.txt

	    It "Should return the output to the screen and to the variable" {
	        $teefile = $testfile
	        echo teeobjecttest1 | Tee-Object -variable teeresults
	        $teeresults         | Should Be "teeobjecttest1"
	        Remove-Item $teefile -ErrorAction SilentlyContinue
	    }

	    It "Should tee the output to a file" {
	        $teefile = $testfile
	        echo teeobjecttest3  | Tee-Object $teefile
	        Get-Content $teefile | Should Be "teeobjecttest3"
	        Remove-Item $teefile -ErrorAction SilentlyContinue
	    }
    }
}

Describe "Tee-Object DRT Unit Tests" -Tags DRT {
    $tempDirectory = Join-Path $TestDrive -ChildPath "TeeObjectTestsTempDir"
    $tempFile = "TeeObjectTestsTempFile"
    New-Item $tempDirectory -ItemType Directory -Force

    It "Positive File Test" {
        $expected = "1", "2", "3"
        $filePath = Join-Path $tempDirectory -ChildPath $tempFile
        $results = $expected | Tee-Object -FilePath $filePath
        $results.Length | Should be 3
        $results | Should Be $expected
        $content = Get-Content $filePath
        $content | Should Be $expected
    }

    It "Positive Var Test" {
        $expected = "1", "2", "3"
        $varName = "teeObjectTestVar"
        $results = $expected | Tee-Object -Variable $varName
        $results.Length | Should be 3
        $results | Should Be $expected

        $results = Get-Variable -Name $varName -ValueOnly
        $results.Length | Should be 3
        $results | Should Be $expected
    }

}


Push-Location Equ

nuget pack -Build -Prop Configuration=Release -Output ..\..\..\LocalNugetFeed

Pop-Location

Build script updated to newest nuget.exe.

Push-Location Equ

nuget pack Equ.csproj -Build -Prop Configuration=Release -Output ..\..\..\LocalNugetFeed

Pop-Location


# Set versions for AssemblyInfo.cs
$version = ( Get-Content .\Version.txt );
$env:AssemblyBaseVersion = $version | foreach{ if( $_ -match "^\d+\.\d+" ){ $matches[0] } }
if ( $env:APPVEYOR_REPO_TAG -ne "True" )
{
	if ( ${env:APPVEYOR_BUILD_NUMBER} -eq $null )
	{
		$now = [DateTime]::UtcNow
		$daysSpan = $now - ( New-Object DateTime( $now.Year, 1, 1 ) )
		$env:PackageVersion = "${version}-{0:yy}{1:000}" -f @( $now, $daysSpan.Days )
	}
	else
	{
		$env:PackageVersion = "${version}-${env:APPVEYOR_BUILD_NUMBER}"
	}
}
else
{
	$env:PackageVersion = $version
}

Fix CI settings which causes private nupkg creation failure due to suffix.

# Set versions for AssemblyInfo.cs
$version = ( Get-Content .\Version.txt );
$env:AssemblyBaseVersion = $version | foreach{ if( $_ -match "^\d+\.\d+" ){ $matches[0] } }
if ( $env:APPVEYOR_REPO_TAG -ne "True" )
{
	if ( ${env:APPVEYOR_BUILD_NUMBER} -eq $null )
	{
		$now = [DateTime]::UtcNow
		$daysSpan = $now - ( New-Object DateTime( $now.Year, 1, 1 ) )
		$env:PackageVersion = "${version}-{0:yy}{1:000}" -f @( $now, $daysSpan.Days )
	}
	else if ( ${env:APPVEYOR_BUILD_NUMBER} -match "^[a-zA-Z].+" )
	{
		$env:PackageVersion = "${version}-${env:APPVEYOR_BUILD_NUMBER}"
	}
	else
	{
		$env:PackageVersion = "${version}-final-${env:APPVEYOR_BUILD_NUMBER}"
	}
}
else
{
	$env:PackageVersion = $version
}


$ErrorActionPreference = 'Stop'

$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$filePath = if ((Get-ProcessorBits 64) -and $env:chocolateyForceX86 -ne $true) {
       Write-Host "Installing 64 bit version" ; gi $toolsDir\*_x64.exe }
else { Write-Host "Installing 32 bit version" ; gi $toolsDir\*_x32.exe }

$packageArgs = @{
  packageName    = '7zip.install'
  fileType       = 'exe'
  softwareName   = '7-zip*'
  file           = $filePath
  silentArgs     = '/S'
  validExitCodes = @(0)
}
Install-ChocolateyInstallPackage @packageArgs
rm $toolsDir\*.exe -ea 0 -force

# 7z installer may close explorer
if (!(ps explorer -ea 0)) { start explorer.exe }

$installLocation = Get-AppInstallLocation $packageArgs.softwareName
if (!$installLocation)  { Write-Warning "Can't find 7zip install location"; return }
Write-Host "7zip installed to '$installLocation'"

Install-BinFile '7z' $installLocation\7z.exe

Add test for the existance of explorer.exe to guard against Server Core images

$ErrorActionPreference = 'Stop'

$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$filePath = if ((Get-ProcessorBits 64) -and $env:chocolateyForceX86 -ne $true) {
       Write-Host "Installing 64 bit version" ; gi $toolsDir\*_x64.exe }
else { Write-Host "Installing 32 bit version" ; gi $toolsDir\*_x32.exe }

$packageArgs = @{
  packageName    = '7zip.install'
  fileType       = 'exe'
  softwareName   = '7-zip*'
  file           = $filePath
  silentArgs     = '/S'
  validExitCodes = @(0)
}
Install-ChocolateyInstallPackage @packageArgs
rm $toolsDir\*.exe -ea 0 -force

# 7z installer may close explorer
if (!(ps explorer -ea 0)) {
    # Only start explorer if the file exists; Server Core installs do not have it.
    if (!(Test-Path "$env:windir\explorer.exe")) {
        start explorer.exe
    }
}

$installLocation = Get-AppInstallLocation $packageArgs.softwareName
if (!$installLocation)  { Write-Warning "Can't find 7zip install location"; return }
Write-Host "7zip installed to '$installLocation'"

Install-BinFile '7z' $installLocation\7z.exe


param([Switch]$Rebuild)

[string]$temp = '.\nugettmp'
[string]$builder = "$env:windir\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe"

[string]$sln = 'MsgPack.sln'
[string]$slnCompat = 'MsgPack.compats.sln'

[string]$nuspec = 'MsgPack.nuspec'

$buildOptions = @()
if( $Rebuild )
{
    $buildOptions += '/t:Rebuild'
}

$buildOptions += '/p:Configuration=Release'

&$builder $sln $buildOptions
&$builder $slnCompat $buildOptions

$winFile = New-Object IO.FileInfo( ".\bin\netcore45\MsgPack.dll" )
$xamarinFile = New-Object IO.FileInfo( ".\bin\monotouch\MsgPack.dll" )
if( ( $winFile.LastWriteTime - $xamarinFile.LastWriteTime ).Days -ne 0 )
{
	# It might that I forgot building in xamarin when winRT build and xamarin build last write time are differ more than 1day.
	Write-Error "Last write times between WinRT binary and Xamarin library are very differ. Do you forget to place latest Xamarin build (on Mac) or latest WinRT build (on Windows) on ./bin ?"
	return
}

.\.nuget\nuget.exe pack $nuspec

Fix check script because netcore45 becomes portable-windows8+wpa.

param([Switch]$Rebuild)

[string]$temp = '.\nugettmp'
[string]$builder = "$env:windir\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe"

[string]$sln = 'MsgPack.sln'
[string]$slnCompat = 'MsgPack.compats.sln'

[string]$nuspec = 'MsgPack.nuspec'

$buildOptions = @()
if( $Rebuild )
{
    $buildOptions += '/t:Rebuild'
}

$buildOptions += '/p:Configuration=Release'

&$builder $sln $buildOptions
&$builder $slnCompat $buildOptions

$winFile = New-Object IO.FileInfo( ".\bin\portable-windows8+wpa\MsgPack.dll" )
$xamarinFile = New-Object IO.FileInfo( ".\bin\monotouch\MsgPack.dll" )
if( ( $winFile.LastWriteTime - $xamarinFile.LastWriteTime ).Days -ne 0 )
{
	# It might that I forgot building in xamarin when winRT build and xamarin build last write time are differ more than 1day.
	Write-Error "Last write times between WinRT binary and Xamarin library are very differ. Do you forget to place latest Xamarin build (on Mac) or latest WinRT build (on Windows) on ./bin ?"
	return
}

.\.nuget\nuget.exe pack $nuspec


### 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
choco install -y 7zip
choco install -y dotnetcore-sdk
choco install -y git
#choco install -y github-desktop    # Github Desktop gets updates so often that it's hard for the Chocolatey package to keep up
choco install -y gitkraken
choco install -y googlechrome
choco install -y hyper
choco install -y keepass
choco install -y linqpad
choco install -y nodejs-lts
choco install -y notepadplusplus
choco install -y poshgit
choco install -y postman
choco install -y rdcman
choco install -y slack
choco install -y sql-server-management-studio
#choco install -y toggl             # The Toggl Desktop Chocolatey package is significantly behind as of May 2017, so I'll install it manually
#choco install -y visualstudiocode  # VS Code gets updates so often that it's hard for the Chocolatey package to keep up
RefreshEnv.cmd

Install Angular CLI and TypeScript with npm

### 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 github-desktop    # Github Desktop gets updates so often that it's hard for the Chocolatey package to keep up
choco install -y gitkraken
choco install -y googlechrome
choco install -y hyper
choco install -y keepass
choco install -y linqpad
choco install -y nodejs-lts
choco install -y notepadplusplus
choco install -y poshgit
choco install -y postman
choco install -y rdcman
choco install -y slack
choco install -y sql-server-management-studio
#choco install -y toggl             # The Toggl Desktop Chocolatey package is significantly behind as of May 2017, so I'll install it manually
#choco install -y visualstudiocode  # VS Code gets updates so often that it's hard for the Chocolatey package to keep up
RefreshEnv.cmd

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


$script:version = (property version "")

task Version {
	$script:version = Set-Version . $version
}

function script:Set-Version($projectPath, $version) {
	$assemblyInfoFile = "$projectPath\Properties\AssemblyInfo.cs"
	if ($version) {
		if ((Test-Path $assemblyInfoFile)) {
			Write-Host "Updating $assemblyInfoFile"
			$newAssemblyVersion = 'AssemblyVersion("' + $version + '")'
			$newAssemblyFileVersion = 'AssemblyFileVersion("' + $version + '")'
			$newFileContent = Get-Content $assemblyInfoFile |
				%{ $_ -replace 'AssemblyVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)', $newAssemblyVersion } |
				%{ $_ -replace 'AssemblyFileVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)', $newAssemblyFileVersion }
			Set-Content $assemblyInfoFile $newFileContent
		}
	}
	else {
		Write-Host "Getting version from $assemblyInfoFile"
		$version = Get-AssemblyFileVersion $assemblyInfoFile
	}
	return $version
}

Add possibility to create placeholders in the version

$script:version = (property version "")

task Version {
	$script:version = Set-Version . $version
}

function script:Set-Version($projectPath, $version) {
	$assemblyInfoFile = "$projectPath\Properties\AssemblyInfo.cs"
	if ($version) {

		$year = $(Get-date -f yyyy)
		$month = $(Get-date -f %M)
		$quarter = $([Math]::ceiling((Get-date -f MM)/3))
		$date = $(Get-date -f dd)

		$version = $version.Replace("{year}", $year).Replace("{month}", $month).Replace("{quarter}", $quarter).Replace("{date}", $date)

		if ((Test-Path $assemblyInfoFile)) {
			Write-Host "Updating $assemblyInfoFile"
			$newAssemblyVersion = 'AssemblyVersion("' + $version + '")'
			$newAssemblyFileVersion = 'AssemblyFileVersion("' + $version + '")'
			$newFileContent = Get-Content $assemblyInfoFile |
				%{ $_ -replace 'AssemblyVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)', $newAssemblyVersion } |
				%{ $_ -replace 'AssemblyFileVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)', $newAssemblyFileVersion }
			Set-Content $assemblyInfoFile $newFileContent
		}
	}
	else {
		Write-Host "Getting version from $assemblyInfoFile"
		$version = Get-AssemblyFileVersion $assemblyInfoFile
	}
	return $version
}


# Get and dot source all helper functions (private)
Split-Path -Path $PSScriptRoot |
    Join-Path -ChildPath 'Modules\SecurityFever\Helpers' |
        Get-ChildItem -Include '*.ps1' -Exclude '*.Tests.*' -Recurse |
            ForEach-Object { . $_.FullName }

# Get and dot source all external functions (public)
Split-Path -Path $PSScriptRoot |
    Join-Path -ChildPath 'Modules\SecurityFever\Functions' |
        Get-ChildItem -Include '*.ps1' -Exclude '*.Tests.*' -Recurse |
            ForEach-Object { . $_.FullName }

# Update format data
Update-FormatData "$PSScriptRoot\..\Modules\SecurityFever\Resources\SecurityFever.Formats.ps1xml"

# Update type data
Update-TypeData "$PSScriptRoot\..\Modules\SecurityFever\Resources\SecurityFever.Types.ps1xml"

# Execute deubg
# ToDo...

Fix stale module import reference

# Get and dot source all helper functions (private)
Split-Path -Path $PSScriptRoot |
    Join-Path -ChildPath 'Modules\DSCPullServerWeb\Helpers' |
        Get-ChildItem -Include '*.ps1' -Exclude '*.Tests.*' -Recurse |
            ForEach-Object { . $_.FullName }

# Get and dot source all external functions (public)
Split-Path -Path $PSScriptRoot |
    Join-Path -ChildPath 'Modules\DSCPullServerWeb\Functions' |
        Get-ChildItem -Include '*.ps1' -Exclude '*.Tests.*' -Recurse |
            ForEach-Object { . $_.FullName }

# Update format data
Update-FormatData "$PSScriptRoot\..\Modules\DSCPullServerWeb\Resources\DSCPullServerWeb.Formats.ps1xml"

# Update type data
Update-TypeData "$PSScriptRoot\..\Modules\DSCPullServerWeb\Resources\DSCPullServerWeb.Types.ps1xml"

# Execute deubg
# ToDo...


function Set-Project-Properties($version) {
    write-host "$version"

    set-regenerated-file "$pwd/Directory.Build.props" @"
<Project>
    <PropertyGroup>
        <Version>$version</Version>
        <Copyright>$(get-copyright)</Copyright>
    </PropertyGroup>
</Project>
"@
}

function Get-Copyright {
    $date = Get-Date
    $year = $date.Year
    $copyrightSpan = if ($year -eq $yearInitiated) { $year } else { "$yearInitiated-$year" }
    return "(c) $copyrightSpan $owner"
}

function Set-Regenerated-File($path, $newContent) {
    if (-not (test-path $path -PathType Leaf)) {
        $oldContent = $null
    } else {
        $oldContent = [IO.File]::ReadAllText($path)
    }

    if ($newContent -ne $oldContent) {
        write-host "Generating $path"
        [System.IO.File]::WriteAllText($path, $newContent, [System.Text.Encoding]::UTF8)
    }
}

function Remove-Directory-Silently($path) {
    if (test-path $path) {
        write-host "Deleting $path"
        Remove-Item $path -recurse -force -ErrorAction SilentlyContinue | out-null
    }
}

Replace (c) with unicode copyright symbol.

function Set-Project-Properties($version) {
    write-host "$version"

    set-regenerated-file "$pwd/Directory.Build.props" @"
<Project>
    <PropertyGroup>
        <Version>$version</Version>
        <Copyright>$(get-copyright)</Copyright>
    </PropertyGroup>
</Project>
"@
}

function Get-Copyright {
    $date = Get-Date
    $year = $date.Year
    $copyrightSpan = if ($year -eq $yearInitiated) { $year } else { "$yearInitiated-$year" }
    return " $copyrightSpan $owner"
}

function Set-Regenerated-File($path, $newContent) {
    if (-not (test-path $path -PathType Leaf)) {
        $oldContent = $null
    } else {
        $oldContent = [IO.File]::ReadAllText($path)
    }

    if ($newContent -ne $oldContent) {
        write-host "Generating $path"
        [System.IO.File]::WriteAllText($path, $newContent, [System.Text.Encoding]::UTF8)
    }
}

function Remove-Directory-Silently($path) {
    if (test-path $path) {
        write-host "Deleting $path"
        Remove-Item $path -recurse -force -ErrorAction SilentlyContinue | out-null
    }
}


$prefix = 'dotnet nuget push '
$suffix = ' API_KEY -Source https://api.nuget.org/v3/index.json'

Get-ChildItem .\*.nupkg | Select-Object { $prefix + $_.Name + $suffix }  | Out-File -width 1000 .\push.bat -Force

(gc .\push.bat | select -Skip 3) | sc .\push.bat

Use dotnet nuget options name.

$prefix = 'dotnet nuget push '
$suffix = ' --source https://api.nuget.org/v3/index.json --api-key API_KEY'

Get-ChildItem .\*.nupkg | Select-Object { $prefix + $_.Name + $suffix }  | Out-File -width 1000 .\push.bat -Force

(gc .\push.bat | select -Skip 3) | sc .\push.bat


Build script for the CI server (properties don't work there)

Framework "4.0x86"

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

Task Build-Develop {
	Invoke-Psake default.ps1
}


param([string]$buildFolder)

$outputPath = "..\output";
$sitePath = "$($buildFolder)\src\WebSite\bin"
$port = 58537
$delay = 5000

Write-Host "Running IIS Express from '$($sitePath)' at '$($port)'."
Start-Process "C:\Program Files (x86)\IIS Express\iisexpress.exe" -NoNewWindow -ArgumentList "/path:$($sitePath) /port:$($port)"

Write-Host "Waiting $($delay)."
Start-Sleep -Milliseconds $delay

Write-Host "Running StaticSiteCrawler."
#Start-Process "$($buildFolder)\Tools\StaticSiteCrawler.cmd" -Wait
.\Tools\StaticSiteCrawler.exe http://localhost:$($port)/ $outputPath /

Write-Host "Content of output:"
$items = Get-ChildItem -Path $outputPath
ForEach ($item in $items)
{
    $size = (Get-Item "$($outputPath)\$($item)").Length
    Write-Host "'$($item)' - $($size)B"
}

Write-Host "Stopping IIS Express."
Stop-Process -Name iisexpress

Revert bin folder for IIS. Test of process is running.

param([string]$buildFolder)

$outputPath = "..\output";
$sitePath = "$($buildFolder)\src\WebSite"
$port = 58537
$delay = 5000

Write-Host "Running IIS Express from '$($sitePath)' at '$($port)'."
$iis = Start-Process "C:\Program Files (x86)\IIS Express\iisexpress.exe" -NoNewWindow -ArgumentList "/path:$($sitePath) /port:$($port)"

Write-Host "Waiting $($delay)."
Start-Sleep -Milliseconds $delay

If ($iis.HasExited)
{
    Write-Host "IIS has exited";
}

Write-Host "Running StaticSiteCrawler."
#Start-Process "$($buildFolder)\Tools\StaticSiteCrawler.cmd" -Wait
.\Tools\StaticSiteCrawler.exe http://localhost:$($port)/ $outputPath /

Write-Host "Content of output:"
$items = Get-ChildItem -Path $outputPath
ForEach ($item in $items)
{
    $size = (Get-Item "$($outputPath)\$($item)").Length
    Write-Host "'$($item)' - $($size)B"
}

Write-Host "Stopping IIS Express."
Stop-Process -Name iisexpress


Describe "Add-Type" {
    It "Should not throw given a simple class definition" -Skip:$IsWindows {
	{ Add-Type -TypeDefinition "public static class foo { }" } | Should Not Throw
    }
}

Enable Add-Type test on Windows

Describe "Add-Type" {
    It "Should not throw given a simple class definition" {
	{ Add-Type -TypeDefinition "public static class foo { }" } | Should Not Throw
    }
}


sal gh help
function sl.. { sl .. }
function sl~ { sl ~ }

function prompt {
	$Host.UI.RawUI.WindowTitle = "PS $($ExecutionContext.SessionState.Path.CurrentLocation)$('>' * ($NestedPromptLevel + 1))"
	return 'PS> '
}

Add ll function as alias

sal gh help
function ll([string[]]$Path = '.') { gci $Path -Exclude .* }
function sl.. { sl .. }
function sl~ { sl ~ }

function prompt {
	$Host.UI.RawUI.WindowTitle = "PS $($ExecutionContext.SessionState.Path.CurrentLocation)$('>' * ($NestedPromptLevel + 1))"
	return 'PS> '
}


$here = $PSScriptRoot
$functionRootPath = "$here"
$functionContentParentPath = "$here\..\..\..\packaged-content"
$functionContentRootPath = "$functionContentParentPath\root\App_Data"

function GetScenarios() {
    Get-ChildItem $functionRootPath -Directory `
        | ForEach-Object { @{ "Group" = $PSItem} } `
        | ForEach-Object {
        $group = $PSItem.Group
        Get-ChildItem "$functionRootPath\$group" | ForEach-Object { [PSCustomObject]@{ "Group" = $group; "Name" = $PSItem}}
    }
}
function ResetOutputDirectory() {
    if (Test-Path $functionContentParentPath) {
        Remove-Item $functionContentParentPath -Recurse -Force
    }
    New-Item $functionContentRootPath -ItemType Directory | out-null
    Set-Content "$functionContentParentPath\.gitignore" "**/**" # avoid accidentally committing this build output to source control :-)
}
function CopyScenarios($scenariosToCopy) {
    $scenariosToCopy | ForEach-Object {
        $scenario = $PSItem
        Copy-Item "$functionRootPath\$($scenario.Group)\$($scenario.Name)" "$functionContentRootPath\$($scenario.Group)\$($scenario.Name)" -Recurse
    }
}
function CopyDeployScript() {
    Copy-Item "$functionRootPath\deploy.ps1" "$functionContentParentPath\root\deploy.ps1"
}
function CreateZip() {
    $zipPath = "$functionContentParentPath/nether-serverless.zip"
    if (Test-Path $zipPath) {
        Remove-Item $zipPath -Force
    }
    [Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" ) | out-null
    [System.IO.Compression.ZipFile]::CreateFromDirectory("$functionContentParentPath\root", "$zipPath", "Fastest", $false)
}

ResetOutputDirectory
$scenarios = GetScenarios
CopyScenarios $scenarios
CopyDeployScript

CreateZip


trap {
  write-error $_
  exit 1
}

$env:GOPATH = Join-Path -Path $PWD "gopath"
$env:PATH = $env:GOPATH + "/bin;C:/go/bin;" + $env:PATH

cd $env:GOPATH/src/github.com/cloudfoundry/bosh-agent

if ((Get-Command "go.exe" -ErrorAction SilentlyContinue) -eq $null)
{
  Write-Host "Installing Go 1.6.3!"
  Invoke-WebRequest https://storage.googleapis.com/golang/go1.6.3.windows-amd64.msi -OutFile go.msi

  $p = Start-Process -FilePath "msiexec" -ArgumentList "/passive /norestart /i go.msi" -Wait -PassThru

  if($p.ExitCode -ne 0)
  {
    throw "Golang MSI installation process returned error code: $($p.ExitCode)"
  }
  Write-Host "Go is installed!"
}

# Change constant for unit test process labels to prevent collisions with
# bosh deployed Job Supervisor
$file = Join-Path -Path $PWD jobsupervisor/windows_job_supervisor.go
(Get-Content $file).replace('serviceDescription = "vcap"', 'serviceDescription = "vcap_test"') | Set-Content $file

go.exe install github.com/cloudfoundry/bosh-agent/vendor/github.com/onsi/ginkgo/ginkgo
ginkgo.exe -r -keepGoing -skipPackage="integration,vendor"

Handle errors for windows unit test

trap {
  write-error $_
  exit 1
}

$env:GOPATH = Join-Path -Path $PWD "gopath"
$env:PATH = $env:GOPATH + "/bin;C:/go/bin;" + $env:PATH

cd $env:GOPATH/src/github.com/cloudfoundry/bosh-agent

if ((Get-Command "go.exe" -ErrorAction SilentlyContinue) -eq $null)
{
  Write-Host "Installing Go 1.6.3!"
  Invoke-WebRequest https://storage.googleapis.com/golang/go1.6.3.windows-amd64.msi -OutFile go.msi

  $p = Start-Process -FilePath "msiexec" -ArgumentList "/passive /norestart /i go.msi" -Wait -PassThru

  if($p.ExitCode -ne 0)
  {
    throw "Golang MSI installation process returned error code: $($p.ExitCode)"
  }
  Write-Host "Go is installed!"
}

# Change constant for unit test process labels to prevent collisions with
# bosh deployed Job Supervisor
$file = Join-Path -Path $PWD jobsupervisor/windows_job_supervisor.go
(Get-Content $file).replace('serviceDescription = "vcap"', 'serviceDescription = "vcap_test"') | Set-Content $file

go.exe install github.com/cloudfoundry/bosh-agent/vendor/github.com/onsi/ginkgo/ginkgo
ginkgo.exe -r -keepGoing -skipPackage="integration,vendor"
if ($LastExitCode -ne 0)
{
    Write-Error $_
    exit 1
}


$directory = Split-Path -Parent $MyInvocation.MyCommand.Path
$testRootDirectory = Split-Path -Parent $directory

Import-Module PSScriptAnalyzer
Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1")

$ruleConfiguration = @{
    Enable = $true
    AlignInHashtable = $true
    AlignInDSCConfiguration = $true
}

$settings = @{
    IncludeRules = @("PSAlignAssignmentStatement")
    Rules = @{
        PSAlignAssignmentStatement = $ruleConfiguration
    }
}

Describe "AlignAssignmentStatement" {
    Context "Hashtable" {
        It "Should align assignment statements in a hashtable" {
            $def = @'
$hashtable = @{
    property1 = "value"
    anotherProperty = "another value"
}
'@

# Expected output should be the following
# $hashtable = @{
#     property1       = "value"
#     anotherProperty = "another value"
# }

            $violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
            $violations.Count | Should Be 1
            Test-CorrectionExtentFromContent $def $violations 1 '' '      '
        }
    }
}

Fix option names in AlignAssignmentStatement rule test

$directory = Split-Path -Parent $MyInvocation.MyCommand.Path
$testRootDirectory = Split-Path -Parent $directory

Import-Module PSScriptAnalyzer
Import-Module (Join-Path $testRootDirectory "PSScriptAnalyzerTestHelper.psm1")

$ruleConfiguration = @{
    Enable = $true
    CheckHashtable = $true
    CheckDSCConfiguration = $true
}

$settings = @{
    IncludeRules = @("PSAlignAssignmentStatement")
    Rules = @{
        PSAlignAssignmentStatement = $ruleConfiguration
    }
}

Describe "AlignAssignmentStatement" {
    Context "Hashtable" {
        It "Should align assignment statements in a hashtable" {
            $def = @'
$hashtable = @{
    property1 = "value"
    anotherProperty = "another value"
}
'@

# Expected output should be the following
# $hashtable = @{
#     property1       = "value"
#     anotherProperty = "another value"
# }

            $violations = Invoke-ScriptAnalyzer -ScriptDefinition $def -Settings $settings
            $violations.Count | Should Be 1
            Test-CorrectionExtentFromContent $def $violations 1 ' ' '       '
        }
    }
}


$ErrorActionPreference = "Stop"

$rootFolder = ".."
$sourceFolder = "$rootFolder\Source"
$buildFolder = "$rootFolder\build"
$packageFolder = "$rootFolder\package"

function cleanup_package_folder()
{
    if (Test-Path $packageFolder)
    {
        Remove-Item $packageFolder -Recurse -Force
    }
    New-Item $packageFolder -Type Directory | Out-Null
}

function zip($sourceDir, $outputFileName)
{
   Add-Type -Assembly System.IO.Compression.FileSystem | Out-Null

   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
   [System.IO.Compression.ZipFile]::CreateFromDirectory($sourceDir, $outputFileName, $compressionLevel, $false)
}

function pack_nuget()
{
    Write-Host "Preparing NuGet package..."

    $nuget = "$sourceFolder\.nuget\nuget.exe"
    &$nuget pack FasterTests.nuspec -BasePath $buildFolder -OutputDirectory $packageFolder -Verbosity quiet
}

function pack_zip()
{
    Write-Host "Preparing zip package..."

    zip $buildFolder "$packageFolder\latest.zip"
}

cleanup_package_folder
pack_nuget
pack_zip

Write-Host "Package succeeded"

Package script modified to generate proper ZIP file name

$ErrorActionPreference = "Stop"

$rootFolder = ".."
$sourceFolder = "$rootFolder\Source"
$buildFolder = "$rootFolder\build"
$packageFolder = "$rootFolder\package"
$nuspecFile = "FasterTests.nuspec"

function cleanup_package_folder()
{
    if (Test-Path $packageFolder)
    {
        Remove-Item $packageFolder -Recurse -Force
    }
    New-Item $packageFolder -Type Directory | Out-Null
}

function zip($sourceDir, $outputFileName)
{
   Add-Type -Assembly System.IO.Compression.FileSystem | Out-Null

   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
   [System.IO.Compression.ZipFile]::CreateFromDirectory($sourceDir, $outputFileName, $compressionLevel, $false)
}

function pack_nuget()
{
    Write-Host "Preparing NuGet package..."

    $nuget = "$sourceFolder\.nuget\nuget.exe"
    &$nuget pack $nuspecFile -BasePath $buildFolder -OutputDirectory $packageFolder -Verbosity quiet
}

function pack_zip()
{
    Write-Host "Preparing zip package..."

    [xml]$nuspec = Get-Content $nuspecFile
    $version = $nuspec.package.metadata.version

    zip $buildFolder "$packageFolder\FasterTests-$version.zip"
}

cleanup_package_folder
pack_nuget
pack_zip

Write-Host "Package succeeded"


param([String]$key)

$span = New-TimeSpan -Start 2010/1/1 -End (Get-Date)
$version = "beta-" + $span.Days.ToString() + ($span.Hours * 60 + $span.Minutes).ToString("0000")
& dotnet restore
cd .\src\Folke.Mvc.Extensions
& dotnet pack --version-suffix $version
$file = Get-Item "bin\Debug\*-$version.nupkg"
nuget push $file.FullName $key
cd ..\..

Update nuget command line parameters

param([String]$key)

$span = New-TimeSpan -Start 2010/1/1 -End (Get-Date)
$version = "beta-" + $span.Days.ToString() + ($span.Hours * 60 + $span.Minutes).ToString("0000")
& dotnet restore
cd .\src\Folke.Mvc.Extensions
& dotnet pack --version-suffix $version
$file = Get-Item "bin\Debug\*-$version.nupkg"
nuget push $file.FullName $key -Source https://api.nuget.org/v3/index.json
cd ..\..


$ErrorActionPreference = "stop"
New-Item -ItemType Directory "$env:PKG_PATH/bin"
new-item -Path "c:\gopath\src\github.com\influxdata" -type directory
copy-item -recurse  -Path C:\pkg\src\telegraf -Destination c:\gopath\src\github.com\influxdata\
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest https://github.com/golang/dep/releases/download/v0.5.0/dep-windows-amd64.exe -OutFile C:\gopath\src\github.com\influxdata\telegraf\dep.exe
Set-Location C:\gopath\src\github.com\influxdata\telegraf
$Env:DEPCACHEDIR="C:\tmp"
$Env:TEMP="C:\tmp"
$Env:TMP="C:\tmp"
.\dep.exe ensure -vendor-only -v
Set-Location C:\gopath\src\github.com\influxdata\telegraf\
$env:GOOS="windows"
$env:GOARCH="386"
go build .\cmd\telegraf\
Copy-Item -Path "telegraf.exe" -Destination "$env:PKG_PATH\bin\"

Update go path on windows for telegraf

$ErrorActionPreference = "stop"
New-Item -ItemType Directory "$env:PKG_PATH/bin"
new-item -Path "c:\gopath\src\github.com\influxdata" -type directory
copy-item -recurse  -Path C:\pkg\src\telegraf -Destination c:\gopath\src\github.com\influxdata\
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest https://github.com/golang/dep/releases/download/v0.5.0/dep-windows-amd64.exe -OutFile C:\gopath\src\github.com\influxdata\telegraf\dep.exe
Set-Location C:\gopath\src\github.com\influxdata\telegraf
$Env:DEPCACHEDIR="C:\tmp"
$Env:TEMP="C:\tmp"
$Env:TMP="C:\tmp"
.\dep.exe ensure -vendor-only -v
Set-Location C:\gopath\src\github.com\influxdata\telegraf\
$env:GOOS="windows"
$env:GOARCH="386"
$env:GOPATH="c:\gopath"
go build .\cmd\telegraf\
Copy-Item -Path "telegraf.exe" -Destination "$env:PKG_PATH\bin\"


Write-Host "Installing chocolatey"
Set-ExecutionPolicy Unrestricted
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

Write-Host "Installing unzip"
choco install -y unzip

((New-Object System.Net.WebClient).DownloadFile('https://github.com/ctfhacker/windows-setup/archive/master.zip', 'C:\Windows\Temp\master.zip'))

cd C:\Windows\Temp\
unzip master.zip
cd windows-setup-master

Get-ChildItem | ForEach-Object {
    Write-Host "Executing " + $_.FullName
    & $_.FullName
}

# Write-Host "Rebooting.."
# shutdown /r /t 0

Revert rebooting to make sure registry changes take effect

Write-Host "Installing chocolatey"
Set-ExecutionPolicy Unrestricted
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

Write-Host "Installing unzip"
choco install -y unzip

((New-Object System.Net.WebClient).DownloadFile('https://github.com/ctfhacker/windows-setup/archive/master.zip', 'C:\Windows\Temp\master.zip'))

cd C:\Windows\Temp\
unzip master.zip
cd windows-setup-master

Get-ChildItem | ForEach-Object {
    Write-Host "Executing " + $_.FullName
    & $_.FullName
}

Write-Host "Rebooting.."
shutdown /r /t 0


$installedapps = get-AppxPackage
$invalidNames = '*ms-resource*', '*DisplayName*'
$aumidList = @()

foreach ($app in $installedapps)
{
    try {
            if(-not $app.IsFramework){
            foreach ($id in (Get-AppxPackageManifest $app).package.applications.application.id)
            {
                    $appx = Get-AppxPackageManifest $app;
                    $name = $appx.Package.Properties.DisplayName;

                    if($name -like '*DisplayName*' -or $name  -like '*ms-resource*')
                    {
                        $name = $appx.Package.Applications.Application.VisualElements.DisplayName;
                    }
                    if($name -like '*DisplayName*' -or $name  -like '*ms-resource*')
                    {
                        $name = "App name not found, double click here to edit it";
                    }

                    $logo = $app.InstallLocation + "\" + $appx.Package.Applications.Application.VisualElements.Square150x150Logo;

                    $aumidList += $name + "|" + $logo + "|" +
                    $app.packagefamilyname + "!" + $id+ ";"
                }
            }
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName
        }
}

$aumidList;

Update powershell script to add relative executable path from MS Config file

$installedapps = get-AppxPackage
$invalidNames = '*ms-resource*', '*DisplayName*'
$aumidList = @()

foreach ($app in $installedapps)
{
    try {
            if(-not $app.IsFramework){
            foreach ($id in (Get-AppxPackageManifest $app).package.applications.application.id)
            {
                    $appx = Get-AppxPackageManifest $app;
                    $name = $appx.Package.Properties.DisplayName;
                    $executable = (Select-Xml -Path ($app.InstallLocation + "\MicrosoftGame.Config") -XPath "/Game/ExecutableList/Executable/@Name").Node.Value
                    # Convert object to ensure is the String of execuble (cf Halo Master Chief Collection example below)
                    # mcclauncher.exe
                    # MCC\Binaries\Win64\MCCWinStore-Win64-Shipping.exe
                    if($executable -is [Object[]]) { $executable = $executable[1].ToString() }

                    if($name -like '*DisplayName*' -or $name  -like '*ms-resource*')
                    {
                        $name = $appx.Package.Applications.Application.VisualElements.DisplayName;
                    }
                    if($name -like '*DisplayName*' -or $name  -like '*ms-resource*')
                    {
                        $name = "App name not found, double click here to edit it";
                    }

                    $logo = $app.InstallLocation + "\" + $appx.Package.Applications.Application.VisualElements.Square150x150Logo;

                    $aumidList += $name + "|" + $logo + "|" + $app.packagefamilyname + "!" + $id + "|" + $executable + ";"
                }
            }
        }
        catch
        {
            $ErrorMessage = $_.Exception.Message
            $FailedItem = $_.Exception.ItemName
        }
}

$aumidList;


## Development Tools - Git

choco install git --package-parameters= "/GitAndUnixToolsOnPath /WindowsTerminal /NoShellIntegration /NoGuiHereIntegration /NoShellHereIntegration"
choco install TortoiseGit
choco install github-desktop

PowerShellGet\Install-Module posh-git -Scope CurrentUser -Force

Get-Service -Name ssh-agent | Set-Service -StartupType Manual

Tweak git, was hanging the build

## Development Tools - Git

choco install git --package-parameters= "/GitAndUnixToolsOnPath /WindowsTerminal /NoShellIntegration /NoGuiHereIntegration /NoShellHereIntegration"
choco install TortoiseGit
choco install github-desktop

Install-PackageProvider -Name NuGet -Force
Install-Module posh-git -Scope CurrentUser -Force

Get-Service -Name ssh-agent | Set-Service -StartupType Manual


Add script for clean release from VS project

Copy-Item .\Release\* .\Final\ -Recurse
rm .\Final\*vshost*
rm .\Final\*.pdb
Compress-Archive -Path .\Final\* -DestinationPath release.zip
Write-Host "SHA256 :"(Get-FileHash -Algorithm SHA256 .\release.zip).Hash
Write-Host "MD5 :"(Get-FileHash -Algorithm SHA256 .\release.zip).Hash
Remove-Item -Force -Recurse .\Final


Add script to automate pushing nuget packages.

# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
$pkg_source=$args[0]
$feed_path=$args[1]
$api_key=$args[2]

if(!$pkg_source -Or !$feed_path) {
	Write-Host ""
	Write-Host "Missing required input(s)" -foregroundcolor "red"
	Write-Host ""
	Write-Host ""
	Write-Host "Usage: push_nuget_packages <packages_path> <nuget_feed_path> [api_Key]"  -foregroundcolor "green"
	Write-Host ""
	Write-Host ""
	return
}

if (-Not (Test-Path 'NuGet.exe')) {
    Invoke-WebRequest 'https://nuget.org/nuget.exe' -OutFile 'NuGet.exe'
}

if(!$api_Key) {
	.\NuGet.exe push "$pkg_source\*.nupkg" -Source "$feed_path"
}
Else {
	.\NuGet.exe push "$pkg_source\*.nupkg" -Source "$feed_path" -ApiKey "$api_Key"
}


[CmdletBinding()]
Param(
    [Parameter(Mandatory=$True)]
    [string]$Platform,

    [Parameter(Mandatory=$True)]
    [string]$Configuration
)

$binStub = $Configuration

$zip = "colore.zip"

If ($Platform -eq "Any CPU")
{
    $zip = "colore_anycpu.zip"
}
Else
{
    $binStub = "$Platform\$binStub"
    If ($Platform -eq "x86")
    {
        $zip = "colore_x86.zip"
    }
    Else
    {
        $zip = "colore_x64.zip"
    }
}

Write-Host "Zipping artifacts for $Platform - $Configuration"

7z.exe a $zip .\Corale.Colore\bin\$binStub\*.dll
7z.exe a $zip .\Corale.Colore\bin\$binStub\*.xml
7z.exe a $zip .\Corale.Colore\bin\$binStub\*.pdb

# Create NuGet package if Release and Any CPU
if ($Configuration -eq "Release" -And $Platform -eq "Any CPU")
{
    Write-Host "Creating NuGet package"
    nuget.exe --% pack Corale.Colore\Corale.Colore.csproj -Prop Configuration=Release -Prop Platform=AnyCPU -Version "%APPVEYOR_BUILD_VERSION%"
    $name = "Corale.Colore.$Env:APPVEYOR_BUILD_VERSION"
    $file = "$name.nupkg"
    Push-AppveyorArtifact $file -FileName $name -DeploymentName "nuget_package"
}

Fix incorrect file ending for nuget package.

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$True)]
    [string]$Platform,

    [Parameter(Mandatory=$True)]
    [string]$Configuration
)

$binStub = $Configuration

$zip = "colore.zip"

If ($Platform -eq "Any CPU")
{
    $zip = "colore_anycpu.zip"
}
Else
{
    $binStub = "$Platform\$binStub"
    If ($Platform -eq "x86")
    {
        $zip = "colore_x86.zip"
    }
    Else
    {
        $zip = "colore_x64.zip"
    }
}

Write-Host "Zipping artifacts for $Platform - $Configuration"

7z.exe a $zip .\Corale.Colore\bin\$binStub\*.dll
7z.exe a $zip .\Corale.Colore\bin\$binStub\*.xml
7z.exe a $zip .\Corale.Colore\bin\$binStub\*.pdb

# Create NuGet package if Release and Any CPU
if ($Configuration -eq "Release" -And $Platform -eq "Any CPU")
{
    Write-Host "Creating NuGet package"
    nuget.exe --% pack Corale.Colore\Corale.Colore.csproj -Prop Configuration=Release -Prop Platform=AnyCPU -Version "%APPVEYOR_BUILD_VERSION%"
    $name = "Corale.Colore.$Env:APPVEYOR_BUILD_VERSION"
    $file = "$name.nupkg"
    Push-AppveyorArtifact $file -DeploymentName "nuget_package"
}


if (Get-Command -Name rustup -ErrorAction Stop) {
	# Enable rustup tab completion
	rustup completions powershell | Out-String | Invoke-Expression
}

function Get-Result([string]$Text, [int]$CursorPosition = $Text.Length, [hashtable]$Options) {
	[System.Management.Automation.CommandCompletion]::CompleteInput($Text, $CursorPosition, $Options).CompletionMatches
}

Describe 'rustup flags and subcommands' {
	$result = Get-Result 'rustup '
	$result.Count | Should Be 23
	$result[00].CompletionText | Should Be 'completions'
	$result[01].CompletionText | Should Be 'component'
	$result[02].CompletionText | Should Be 'default'
	$result[03].CompletionText | Should Be 'doc'
	$result[04].CompletionText | Should Be '-h'
	$result[05].CompletionText | Should Be 'help'
	$result[06].CompletionText | Should Be '--help'
	$result[07].CompletionText | Should Be 'install'
	$result[08].CompletionText | Should Be 'override'
	$result[09].CompletionText | Should Be 'run'
	$result[10].CompletionText | Should Be 'self'
	$result[11].CompletionText | Should Be 'set'
	$result[12].CompletionText | Should Be 'show'
	$result[13].CompletionText | Should Be 'target'
	$result[14].CompletionText | Should Be 'telemetry'
	$result[15].CompletionText | Should Be 'toolchain'
	$result[16].CompletionText | Should Be 'uninstall'
	$result[17].CompletionText | Should Be 'update'
	$result[18].CompletionText | Should Be '-V'
	$result[19].CompletionText | Should Be '-v'
	$result[20].CompletionText | Should Be '--verbose'
	$result[21].CompletionText | Should Be '--version'
	$result[22].CompletionText | Should Be 'which'
}

Update tab completion test for PowerShell

if (Get-Command -Name rustup -ErrorAction Stop) {
	# Enable rustup tab completion
	rustup completions powershell | Out-String | Invoke-Expression
}

function Get-Result([string]$Text, [int]$CursorPosition = $Text.Length, [hashtable]$Options) {
	[System.Management.Automation.CommandCompletion]::CompleteInput($Text, $CursorPosition, $Options).CompletionMatches
}

Describe 'rustup flags and subcommands' {
	$result = Get-Result 'rustup '

	# Keep it simple because over-specify testing might be risky
	$result.Count | Should -BeGreaterThan 10
	$result.CompletionText | Should -Contain 'completions'
	$result.CompletionText | Should -Contain 'install'
	$result.CompletionText | Should -Contain 'uninstall'
	$result.CompletionText | Should -Contain 'update'
	$result.CompletionText | Should -Contain '--help'
	$result.CompletionText | Should -Contain '--verbose'
}


Function UpdateVersionInFile
{
    Param ([string]$path, [string]$prefix, [string]$suffix, [int]$verNum)

    if ($env:BUILD_NUMBER)
    {

        $lines = Get-Content $path -Encoding UTF8

        $new_lines =  $lines | %{
            if ($_.StartsWith($prefix))
            {
                $num = $_.Substring($prefix.Length, $_.Length - $prefix.Length - $suffix.Length)
                $num_p = $num.Split('.')
                $new_num = [System.String]::Join('.', $num_p[0 .. ($verNum-2)] + $env:BUILD_NUMBER)
                return $prefix + $new_num + $suffix
            }
            else
            {
                return $_
            }
        }

        Set-Content -Path $path -Value $new_lines -Encoding UTF8
    }
}

UpdateVersionInFile ((Split-Path -Parent $PSCommandPath) + '\..\nupkg\Microsoft.Azure.Storage.DataMovement.nuspec') '    <version>' '</version>' 4

UpdateVersionInFile ((Split-Path -Parent $PSCommandPath) + '\..\AssemblyInfo\SharedAssemblyInfo.cs') '[assembly: AssemblyFileVersion("' '")]' 4

Change script to inject build number to DM library file for .Net Core platform.

Function UpdateVersionInFile
{
    Param ([string]$path, [string]$prefix, [string]$suffix, [int]$verNum)

    if ($env:BUILD_NUMBER)
    {

        $lines = Get-Content $path -Encoding UTF8

        $new_lines =  $lines | %{
            if ($_.StartsWith($prefix))
            {
                $num = $_.Substring($prefix.Length, $_.Length - $prefix.Length - $suffix.Length)
                $num_p = $num.Split('.')
                $new_num = [System.String]::Join('.', $num_p[0 .. ($verNum-2)] + $env:BUILD_NUMBER)
                return $prefix + $new_num + $suffix
            }
            else
            {
                return $_
            }
        }

        Set-Content -Path $path -Value $new_lines -Encoding UTF8
    }
}

UpdateVersionInFile ((Split-Path -Parent $PSCommandPath) + '\..\nupkg\Microsoft.Azure.Storage.DataMovement.nuspec') '    <version>' '</version>' 4

UpdateVersionInFile ((Split-Path -Parent $PSCommandPath) + '\..\AssemblyInfo\SharedAssemblyInfo.cs') '[assembly: AssemblyFileVersion("' '")]' 4

UpdateVersionInFile ((Split-Path -Parent $PSCommandPath) + '\..\..\netcore\Microsoft.Azure.Storage.DataMovement\Microsoft.Azure.Storage.DataMovement.csproj') '    <Version>' '</Version>' 4


$ErrorActionPreference = "Stop"
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
Push-Location $dir

sv version $env:APPVEYOR_BUILD_NUMBER
#sv version "1-debug"

sv version 9999.0.$version-nightly
sv key $env:myget_key

. ".\include.ps1"
.\build-version.ps1 $version

sv reponame $env:APPVEYOR_REPO_NAME
sv repobranch $env:APPVEYOR_REPO_BRANCH
sv pullreq $env:APPVEYOR_PULL_REQUEST_NUMBER

echo "Checking for publishing"
echo "$reponame $repobranch $pullreq"
if ([string]::IsNullOrWhiteSpace($pullreq))
{
    echo "Build is not a PR"
    if($repobranch -eq "master")
    {
        echo "Repo branch matched"
        foreach($pkg in $Packages)
        {
            nuget.exe push "$($pkg).$($version).nupkg" $key -Source https://www.myget.org/F/avalonia-ci/api/v2/package
        }
    }
}

Modify ci build versioning scheme

$ErrorActionPreference = "Stop"
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
Push-Location $dir

sv version $env:APPVEYOR_BUILD_NUMBER
#sv version "1-debug"

sv version 0.2.0.$version-nightly
sv key $env:myget_key

. ".\include.ps1"
.\build-version.ps1 $version

sv reponame $env:APPVEYOR_REPO_NAME
sv repobranch $env:APPVEYOR_REPO_BRANCH
sv pullreq $env:APPVEYOR_PULL_REQUEST_NUMBER

echo "Checking for publishing"
echo "$reponame $repobranch $pullreq"
if ([string]::IsNullOrWhiteSpace($pullreq))
{
    echo "Build is not a PR"
    if($repobranch -eq "master")
    {
        echo "Repo branch matched"
        foreach($pkg in $Packages)
        {
            nuget.exe push "$($pkg).$($version).nupkg" $key -Source https://www.myget.org/F/avalonia-ci/api/v2/package
        }
    }
}


Write-Host "Add Registry to hosts"
$ip = "192.168.38.100"
# I know this could be done with vagrant-hostmanager
Add-Content C:\Windows\system32\drivers\etc\hosts "`r`n$ip registry"

Write-Host "Add Docker Registry"
cp C:\ProgramData\docker\runDockerDaemon.cmd C:\ProgramData\docker\runDockerDaemon.cmd.bak
cat C:\ProgramData\docker\runDockerDaemon.cmd.bak | %{$_ -replace '^dockerd -G docker -H npipe:// -H 0.0.0.0:2375$','dockerd -G docker -H npipe:// -H 0.0.0.0:2375 --insecure-registry registry:5000'} | Set-Content C:\ProgramData\docker\runDockerDaemon.cmd

Write-Host "Restarting docker"
Restart-Service docker

Update to latest windows_2016_docker box

Write-Host "Add Registry to hosts"
$ip = "192.168.38.100"
# I know this could be done with vagrant-hostmanager
Add-Content C:\Windows\system32\drivers\etc\hosts "`r`n$ip registry"

Write-Host "Add Docker Registry"
$path = (Get-ItemProperty -Path HKLM:SYSTEM\CurrentControlSet\Services\docker -Name ImagePath).ImagePath
$path += ' --insecure-registry registry:5000'
Set-ItemProperty -Path HKLM:SYSTEM\CurrentControlSet\Services\docker -Name ImagePath -Value $path -Force

Write-Host "Restarting docker"
Restart-Service docker


Describe "Get-Culture" {

    It "Should return a type of CultureInfo for Get-Culture cmdlet" {

	(Get-Culture).GetType() | Should Be CultureInfo

    }

    It "Should have $ culture variable be equivalent to (Get-Culture).Name" {

	(Get-Culture).Name | Should Be $PsCulture

    }

}

Add Unit Test for Get-Culture

Describe "Get-Culture DRT Unit Tests" -Tags DRT{
    It "Should works proper with get-culture" {
        $results = get-Culture
        $results | Should Not BeNullOrEmpty
        $results[0].GetType() | Should Be CultureInfo
        $results[0].Name | Should Be $PSCulture
    }
}

Describe "Get-Culture" {

    It "Should return a type of CultureInfo for Get-Culture cmdlet" {

	(Get-Culture).GetType() | Should Be CultureInfo

    }

    It "Should have $ culture variable be equivalent to (Get-Culture).Name" {

	(Get-Culture).Name | Should Be $PsCulture

    }

}


Import-Module PSScriptAnalyzer
$violationMessage = "The Credential parameter in 'Credential' must be of type PSCredential. For PowerShell 4.0 and earlier, please define a credential transformation attribute, e.g. [System.Management.Automation.Credential()], after the PSCredential type attribute."
$violationName = "PSUsePSCredentialType"
$directory = Split-Path -Parent $MyInvocation.MyCommand.Path
$violations = Invoke-ScriptAnalyzer $directory\PSCredentialType.ps1 | Where-Object {$_.RuleName -eq $violationName}
$noViolations = Invoke-ScriptAnalyzer $directory\PSCredentialTypeNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName}

Describe "PSCredentialType" {
    Context "When there are violations" {
        It "has 2 PSCredential type violation" {
            $violations.Count | Should Be 2
        }

        It "has the correct description message" {
            $violations[0].Message | Should Be $violationMessage
        }
    }

    $expectedViolationCount = 0
    if ($PSVersionTable.PSVersion -lt [Version]'5.0.0')
    {
        $expectedViolationCount = 1
    }
    Context ("When there are {0} violations" -f $expectedViolationCount) {
        It ("returns {0} violations" -f $expectedViolationCount) {
            $noViolations.Count | Should Be $expectedViolationCount
        }
    }
}

Add failing test for UsePSCredentialType rule

Import-Module PSScriptAnalyzer
$violationMessage = "The Credential parameter in 'Credential' must be of type PSCredential. For PowerShell 4.0 and earlier, please define a credential transformation attribute, e.g. [System.Management.Automation.Credential()], after the PSCredential type attribute."
$violationName = "PSUsePSCredentialType"
$directory = Split-Path -Parent $MyInvocation.MyCommand.Path
$violations = Invoke-ScriptAnalyzer $directory\PSCredentialType.ps1 | Where-Object {$_.RuleName -eq $violationName}
$noViolations = Invoke-ScriptAnalyzer $directory\PSCredentialTypeNoViolations.ps1 | Where-Object {$_.RuleName -eq $violationName}

Describe "PSCredentialType" {
    Context "When there are violations" {
        It "has 2 PSCredential type violation" {
            $violations.Count | Should Be 2
        }

        It "has the correct description message" {
            $violations[0].Message | Should Be $violationMessage
        }

        It "detects attributes on the same line" {
            $scriptDef = @'
function Get-Credential
{
    param(
    [PSCredential][System.Management.Automation.Credential()]
    $Credential
    )
}
'@
            $violations = Invoke-ScriptAnalyzer -ScriptDefinition $scriptDef -IncludeRule $violationName
            $violations.Count | Should Be 0
        }

    }

    $expectedViolationCount = 0
    if ($PSVersionTable.PSVersion -lt [Version]'5.0.0')
    {
        $expectedViolationCount = 1
    }
    Context ("When there are {0} violations" -f $expectedViolationCount) {
        It ("returns {0} violations" -f $expectedViolationCount) {
            $noViolations.Count | Should Be $expectedViolationCount
        }
    }
}


param (
    $SolutionRoot = "$PSScriptRoot/..",
    $TestResultDirectory = "$SolutionRoot/src/WpfMath.Tests/TestResults"
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

Get-ChildItem $TestResultDirectory -Filter "*.received.txt" | ForEach-Object {
    $receivedTestResult = $_.FullName
    $approvedTestResult = $receivedTestResult.Replace('.received.txt', '.approved.txt')
    Move-Item -Force $receivedTestResult $approvedTestResult
}

Fix the approval script for paths with square brackets

param (
    $SolutionRoot = "$PSScriptRoot/..",
    $TestResultDirectory = "$SolutionRoot/src/WpfMath.Tests/TestResults"
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

Get-ChildItem $TestResultDirectory -Filter "*.received.txt" | ForEach-Object {
    $receivedTestResult = $_.FullName
    $approvedTestResult = $receivedTestResult.Replace('.received.txt', '.approved.txt')
    Move-Item -Force -LiteralPath $receivedTestResult $approvedTestResult
}


$projectRoot = Resolve-Path "$PSScriptRoot\.."
$script:ModuleName = 'MyModule'
$moduleRoot = "$projectRoot\$ModuleName"

Describe "PSScriptAnalyzer rule-sets" -Tag Build {

    $Rules = Get-ScriptAnalyzerRule
    $scripts = Get-ChildItem $moduleRoot -Include *.ps1, *.psm1, *.psd1 -Recurse | where fullname -notmatch 'classes'

    foreach ( $Script in $scripts )
    {
        Context "Script '$($script.FullName)'" {

            foreach ( $rule in $rules )
            {
                It "Rule [$rule]" {

                    (Invoke-ScriptAnalyzer -Path $script.FullName -IncludeRule $rule.RuleName ).Count | Should Be 0
                }
            }
        }
    }
}

Describe "General project validation: $moduleName" -Tags Build {

    It "Module '$moduleName' can import cleanly" {
        {Import-Module (Join-Path $moduleRoot "$moduleName.psm1") -force } | Should Not Throw
    }
}

Fix ModuleName for project tests

$projectRoot = Resolve-Path "$PSScriptRoot\.."
$script:ModuleName = 'CitrixImagingTools'
$moduleRoot = "$projectRoot\$ModuleName"

Describe "PSScriptAnalyzer rule-sets" -Tag Build {

    $Rules = Get-ScriptAnalyzerRule
    $scripts = Get-ChildItem $moduleRoot -Include *.ps1, *.psm1, *.psd1 -Recurse | where fullname -notmatch 'classes'

    foreach ( $Script in $scripts )
    {
        Context "Script '$($script.FullName)'" {

            foreach ( $rule in $rules )
            {
                It "Rule [$rule]" {

                    (Invoke-ScriptAnalyzer -Path $script.FullName -IncludeRule $rule.RuleName ).Count | Should Be 0
                }
            }
        }
    }
}

Describe "General project validation: $moduleName" -Tags Build {

    It "Module '$moduleName' can import cleanly" {
        {Import-Module (Join-Path $moduleRoot "$moduleName.psm1") -force } | Should Not Throw
    }
}


# The PowerShell Script Analyzer will generate a warning
# diagnostic record for this file due to a bug -
# https://github.com/PowerShell/PSScriptAnalyzer/issues/472
@{
    # Only diagnostic records of the specified severity will be generated.
    # Uncomment the following line if you only want Errors and Warnings but
    # not Information diagnostic records.
    #Severity = @('Error','Warning')

    # Analyze **only** the following rules. Use IncludeRules when you want
    # to invoke only a small subset of the defualt rules.
    IncludeRules = @('PSAvoidDefaultValueSwitchParameter',
                     'PSMissingModuleManifestField',
                     'PSReservedCmdletChar',
                     'PSReservedParams',
                     'PSShouldProcess',
                     'PSUseApprovedVerbs',
                     'PSUseDeclaredVarsMoreThanAssigments')

    # Do not analyze the following rules. Use ExcludeRules when you have
    # commented out the IncludeRules settings above and want to include all
    # the default rules except for those you exclude below.
    # Note: if a rule is in both IncludeRules and ExcludeRules, the rule
    # will be excluded.
    #ExcludeRules = @('PSAvoidUsingWriteHost')
}

Add PSMisleadingBacktick to PSSA settings file.

# The PowerShell Script Analyzer will generate a warning
# diagnostic record for this file due to a bug -
# https://github.com/PowerShell/PSScriptAnalyzer/issues/472
@{
    # Only diagnostic records of the specified severity will be generated.
    # Uncomment the following line if you only want Errors and Warnings but
    # not Information diagnostic records.
    #Severity = @('Error','Warning')

    # Analyze **only** the following rules. Use IncludeRules when you want
    # to invoke only a small subset of the defualt rules.
    IncludeRules = @('PSAvoidDefaultValueSwitchParameter',
                     'PSMisleadingBacktick',
                     'PSMissingModuleManifestField',
                     'PSReservedCmdletChar',
                     'PSReservedParams',
                     'PSShouldProcess',
                     'PSUseApprovedVerbs',
                     'PSUseDeclaredVarsMoreThanAssigments')

    # Do not analyze the following rules. Use ExcludeRules when you have
    # commented out the IncludeRules settings above and want to include all
    # the default rules except for those you exclude below.
    # Note: if a rule is in both IncludeRules and ExcludeRules, the rule
    # will be excluded.
    #ExcludeRules = @('PSAvoidUsingWriteHost')
}


$output = "$PSScriptRoot\coverage.xml"
If (Test-Path $output) {
	Remove-Item $output -Force
}

dotnet test -f netcoreapp2.0 /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:CoverletOutput=$output ../source/tusdotnet.sln
$key = Read-Host -Prompt 'Input Codecov key'
./codecov.sh -f "coverage.xml" -t $key

Exclude coverage of xunit from code coverage

$output = "$PSScriptRoot\coverage.xml"
If (Test-Path $output) {
	Remove-Item $output -Force
}

dotnet test -f netcoreapp2.0 /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:CoverletOutput=$output /p:Exclude="[xunit.*]*" ../source/tusdotnet.sln
$key = Read-Host -Prompt 'Input Codecov key'
./codecov.sh -f "coverage.xml" -t $key


# http://stackoverflow.com/a/10472358/2607840
Function Get-ProjectReferences ($rootFolder)
{
    $projectFiles = Get-ChildItem $rootFolder -Filter *.csproj -Recurse
    $ns = @{ defaultNamespace = "http://schemas.microsoft.com/developer/msbuild/2003" }

    $projectFiles | ForEach-Object {
        $projectFile = $_ | Select-Object -ExpandProperty FullName
        $projectName = $_ | Select-Object -ExpandProperty BaseName
        $projectXml = [xml](Get-Content $projectFile)

        $projectReferences = $projectXml | Select-Xml '//defaultNamespace:ProjectReference/defaultNamespace:Name' -Namespace $ns | Select-Object -ExpandProperty Node | Select-Object -ExpandProperty "#text"

        $projectReferences | ForEach-Object {
            "[" + $projectName + "] -> [" + $_ + "]"
        }
    }
}

Get-ProjectReferences $pwd | Out-File references.txt

Add include VB project files

# http://stackoverflow.com/a/10472358/2607840
Function Get-ProjectReferences ($rootFolder)
{
    $projectFiles = Get-ChildItem $rootFolder\* -Include *.csproj, *.vbproj -Recurse
    $ns = @{ defaultNamespace = "http://schemas.microsoft.com/developer/msbuild/2003" }

    $projectFiles | ForEach-Object {
        $projectFile = $_ | Select-Object -ExpandProperty FullName
        $projectName = $_ | Select-Object -ExpandProperty BaseName
        $projectXml = [xml](Get-Content $projectFile)

        $projectReferences = $projectXml | Select-Xml '//defaultNamespace:ProjectReference/defaultNamespace:Name' -Namespace $ns | Select-Object -ExpandProperty Node | Select-Object -ExpandProperty "#text"

        $projectReferences | ForEach-Object {
            "[" + $projectName + "] -> [" + $_ + "]"
        }
    }
}

Get-ProjectReferences $pwd | Out-File references.txt


function ExecuteCommand($command, $command_args)
{
  Write-Host $command $command_args
  Start-Process -FilePath $command -ArgumentList $command_args -Wait -Passthru
}

function InstallPrerequisites($work_dir, $install_dir)
{
  $old_dir = $pwd
  cd $work_dir

  $msi = "dart-prerequisites.msi"
  $uri = "https://github.com/dartsim/dart-prerequisites-windows/raw/bfb42e9e8271bc99f8b070715bd407cb5988c322/DART%205.0-prerequisites-msvc12-md-32bit.msi"
  Invoke-WebRequest $uri -OutFile $msi

  $install_command = "msiexec.exe"
  $install_args    = "/qn /log log.txt /i $msi TARGETDIR=$install_dir"
  ExecuteCommand $install_command $install_args

  cd $old_dir
}

function main()
{
  try
  {
    InstallPrerequisites "C:/projects" "C:/Golems"
  }
  catch
  {
    throw
  }
}

main

Update link to dart prerequisites installer

function ExecuteCommand($command, $command_args)
{
  Write-Host $command $command_args
  Start-Process -FilePath $command -ArgumentList $command_args -Wait -Passthru
}

function InstallPrerequisites($work_dir, $install_dir)
{
  $old_dir = $pwd
  cd $work_dir

  $msi = "dart-prerequisites.msi"
  $uri = "https://github.com/dartsim/dart-prerequisites-windows/raw/3e34167fd29fcc870ebed50bf318f3f31f491e6a/DART%205.0-prerequisites-msvc12-md-32bit.msi"
  Invoke-WebRequest $uri -OutFile $msi

  $install_command = "msiexec.exe"
  $install_args    = "/qn /log log.txt /i $msi TARGETDIR=$install_dir"
  ExecuteCommand $install_command $install_args

  cd $old_dir
}

function main()
{
  try
  {
    InstallPrerequisites "C:/projects" "C:/Golems"
  }
  catch
  {
    throw
  }
}

main


Describe "New-Object" {
    It "should create an object with 4 fields" {
	$o = New-Object psobject
	$val = $o.GetType()

	$val.IsPublic       | Should Not BeNullOrEmpty
	$val.Name           | Should Not BeNullOrEmpty
	$val.IsSerializable | Should Not BeNullOrEmpty
	$val.BaseType       | Should Not BeNullOrEmpty

	$val.IsPublic       | Should Be $true
	$val.IsSerializable | Should Be $false
	$val.Name           | Should Be 'PSCustomObject'
	$val.BaseType       | Should Be 'System.Object'
    }

    It "should create an object with using Property switch" {
    $hash = @{
        FirstVal = 'test1'
        SecondVal = 'test2'
    }
	$o = New-Object psobject -Property $hash

	$o.FirstVal     | Should Be 'test1'
	$o.SecondVal    | Should Be 'test2'
    }

    It "should create a .Net object with using ArgumentList switch" {
	$o = New-Object -TypeName System.Version -ArgumentList "1.2.3.4"
    $val = $o.GetType()

	$o.Major      | Should Be 1
	$o.Minor      | Should Be 2
    $o.Build      | Should Be 3
    $o.Revision   | Should Be 4

    $val.IsPublic       | Should Be $true
	$val.IsSerializable | Should Be $false
	$val.Name           | Should Be 'Version'
	$val.BaseType       | Should Be 'System.Object'
    }
}

Modify Pester test for New-Object

Describe "New-Object" {
    It "should create an object with 4 fields" {
	$o = New-Object psobject
	$val = $o.GetType()

	$val.IsPublic       | Should Not BeNullOrEmpty
	$val.Name           | Should Not BeNullOrEmpty
	$val.IsSerializable | Should Not BeNullOrEmpty
	$val.BaseType       | Should Not BeNullOrEmpty

	$val.IsPublic       | Should Be $true
	$val.IsSerializable | Should Be $false
	$val.Name           | Should Be 'PSCustomObject'
	$val.BaseType       | Should Be 'System.Object'
    }

    It "should create an object with using Property switch" {
    $hash = @{
        FirstVal = 'test1'
        SecondVal = 'test2'
    }
	$o = New-Object psobject -Property $hash

	$o.FirstVal     | Should Be 'test1'
	$o.SecondVal    | Should Be 'test2'
    }

    It "should create a .Net object with using ArgumentList switch" {
	$o = New-Object -TypeName System.Version -ArgumentList "1.2.3.4"
    $val = $o.GetType()

	$o      | Should Be "1.2.3.4"

    $val.IsPublic       | Should Be $true
	$val.IsSerializable | Should Be $false
	$val.Name           | Should Be 'Version'
	$val.BaseType       | Should Be 'System.Object'
    }
}


$location = Split-Path $MyInvocation.MyCommand.Path;

PowerShell -NoProfile -Command {
    param (
        [String] $location
    )

    $appRuntime = "netcoreapp1.0";
    $folder = "$location\bin\Debug\$appRuntime";
    Set-Location -Path $folder;

    # Copy-Item C:\sources\powershell-binaries-$appRuntime\* -Destination $folder -Force;

    Import-Module "$folder\TestHttpCompositionConsoleApp.dll";

    #Get-Help Write-Message;
    #Get-Help Enqueue-Message;

    #$message = Dequeue-Message -ServiceOrchestrator "orchestrator-X" -ServiceName "service-X" -ContextId "LALALA- queue-context";

    Write-Host "Message 1: '$message'";

    Write-Message -Data @{ Message = "Awesome instrumentation" } -PipeName "service-X.namedpipes-log-instrumentation-context";
    Write-Message -Data @{ Message = "Awesome instrumentation - again!" } -PipeName "service-X.namedpipes-log-instrumentation-context";

    Enqueue-Message @{ "Data" = "a message" } -ServiceOrchestrator "orchestrator-X" -ServiceName "service-X" -ContextId "queue-context";
    $message = Dequeue-Message -ServiceOrchestrator "orchestrator-X" -ServiceName "service-X" -ContextId "queue-context";

    Write-Host "Message 2: '$message'";

    Write-Host " --- Done --- ";
} -args $location;

Update the test with the optional copy for the 'System.Runtime 4.1.0' error requirement subsystem.

$ErrorActionPreference = "Stop"

$location = Split-Path $MyInvocation.MyCommand.Path;

PowerShell -NoProfile -Command {
    param (
        [String] $location
    )

    $appRuntime = "netcoreapp1.0";
    Set-Location -Path $location;
    #Copy-Item ..\..\..\powershell-binaries-$appRuntime\* -Destination . -Force;

    $folder = "$location\bin\Debug\$appRuntime";
    #$folder = "$location\bin\Release\$appRuntime\win-x64\publish";
    Set-Location -Path $folder;
    Move-Item "$location\*.dll" $folder -Force;

    Import-Module "$folder\TestHttpCompositionConsoleApp.dll";

    #Get-Help Write-Message;
    #Get-Help Enqueue-Message;

    # This is an error
    #$message = Dequeue-Message -ServiceOrchestrator "orchestrator-X" -ServiceName "service-X" -ContextId "LALALA- queue-context";

    Write-Host "Message 1: '$message'";

    Write-Message -Data @{ Message = "Awesome instrumentation" } -PipeName "service-X.namedpipes-log-instrumentation-context";
    Write-Message -Data @{ Message = "Awesome instrumentation - again!" } -PipeName "service-X.namedpipes-log-instrumentation-context";

    Enqueue-Message @{ "Data" = "a message" } -ServiceOrchestrator "orchestrator-X" -ServiceName "service-X" -ContextId "queue-context";
    $message = Dequeue-Message -ServiceOrchestrator "orchestrator-X" -ServiceName "service-X" -ContextId "queue-context";

    Write-Host "Message 2: '$message'";

    Write-Host " --- Done --- ";
} -args $location;


Describe "Set-PSDebug" {
    Context "Tracing can be used" {
        AfterEach {
            Set-PSDebug -Off
        }

        It "Should be able to go through the tracing options" {
            { Set-PSDebug -Trace 0 } | Should Not Throw
            { Set-PSDebug -Trace 1 } | Should Not Throw
            { Set-PSDebug -Trace 2 } | Should Not Throw
        }

        It "Should be able to set strict" {
            { Set-PSDebug -Strict } | Should Not Throw
        }
    }
}

Disable Set-PSDebug tests on AppVeyor

Describe "Set-PSDebug" {
    Context "Tracing can be used" {
        AfterEach {
            Set-PSDebug -Off
        }

        It "Should be able to go through the tracing options" -Skip:($env:APPVEYOR -eq "TRUE") {
            { Set-PSDebug -Trace 0 } | Should Not Throw
            { Set-PSDebug -Trace 1 } | Should Not Throw
            { Set-PSDebug -Trace 2 } | Should Not Throw
        }

        It "Should be able to set strict" -Skip:($env:APPVEYOR -eq "TRUE") {
            { Set-PSDebug -Strict } | Should Not Throw
        }
    }
}