Skip to content

Instantly share code, notes, and snippets.

@ritalin
Last active December 11, 2018 09:01
Show Gist options
  • Save ritalin/84884c7d8fec4a4e34d83dba3edbf6ab to your computer and use it in GitHub Desktop.
Save ritalin/84884c7d8fec4a4e34d83dba3edbf6ab to your computer and use it in GitHub Desktop.
クリーンな環境でPesterによるテスト実行 (Original: Ensuring a Clean PowerShell Session for Your Pester Tests / https://mcpmag.com/articles/2018/02/01/clean-powershell-session-for-pester.aspx )
function InvokePowerShellCommand
{
[CmdletBinding()]
param
(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$Command
)
$Command | powershell.exe -NoProfile -NonInteractive -NoLogo -ExecutionPolicy Bypass -Command -
}
function ConvertTo-String
{
[OutputType([string])]
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[hashtable]$Hashtable
)
$arr = $Hashtable.GetEnumerator().foreach({
if ($_.Value -is 'hashtable') {
"'$($_.Key)' = $(ConvertTo-String -HashTable $_.Value)"
} else {
"'$($_.Key)' = '$($_.Value)'"
}
})
'@{{ {0} }}' -f ($arr -join ';')
}
function ConvertHashTableParametersToString
{
[OutputType([string])]
[CmdletBinding()]
param
(
[Parameter()]
[ValidateNotNullOrEmpty()]
[hashtable]$Parameters
)
$Parameters.GetEnumerator().foreach({
$paramName = $_.Key
if ($_.Value -is [System.Management.Automation.SwitchParameter]) {
if ($_.Value) {
'-{0}' -f $paramName
}
}
else {
if ($_.Value -is 'hashtable') {
$paramValue = ConvertTo-String -HashTable $_.Value
}
else {
$paramValue = '"{0}"' -f (@($_.Value) -join '","')
}
'-{0} {1}' -f $paramName,$paramValue
}
})
}
function Start-Pester
{
[CmdletBinding()]
param(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$Path,
[switch]$PassThru,
[switch]$Quiet
)
$invPesterParams = @{
Path = $Path
Show = if (-not $Quiet) { "All" } else { 'Fails' }
PassThru = $PassThru
}
## Can't splat here because we're passing to another powershell.exe process
$invPesterParamString = ConvertHashTableParametersToString -Parameters $invPesterParams
$command = "Invoke-Pester $invPesterParamString "
if (-not $PassThru) {
InvokePowerShellCommand -Command $command
}
else {
$log = New-TemporaryFile
try {
$output = InvokePowerShellCommand -Command ($command + " | Export-CliXml -Encoding utf8 $($log.FullName)")
Import-CliXml $log
}
finally {
Remove-Item $log
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment