Remove use of cmdlet aliases from .\test\powershell (#8546)

This commit is contained in:
xtqqczze 2018-12-28 08:48:23 +00:00 committed by Ilya
parent 767c13fca1
commit 70de294fea
33 changed files with 118 additions and 118 deletions

View file

@ -251,7 +251,7 @@ Describe 'ValidateSet support a dynamically generated set' -Tag "CI" {
} }
'@ '@
$cls = Add-Type -TypeDefinition $a -PassThru | select -First 1 $cls = Add-Type -TypeDefinition $a -PassThru | Select-Object -First 1
$testModule = Import-Module $cls.Assembly -PassThru $testModule = Import-Module $cls.Assembly -PassThru
} }

View file

@ -231,7 +231,7 @@ Describe "Exception error position" -Tags "CI" {
static f1() { [MSFT_3090412]::bar = 42 } static f1() { [MSFT_3090412]::bar = 42 }
static f2() { throw "an error in f2" } static f2() { throw "an error in f2" }
static f3() { "".Substring(0, 10) } static f3() { "".Substring(0, 10) }
static f4() { dir nosuchfile -ErrorAction Stop } static f4() { Get-ChildItem nosuchfile -ErrorAction Stop }
} }
It "Setting a property that doesn't exist" { It "Setting a property that doesn't exist" {
@ -251,7 +251,7 @@ Describe "Exception error position" -Tags "CI" {
It "Terminating error" { It "Terminating error" {
$e = { [MSFT_3090412]::f4() } | Should -Throw -PassThru -ErrorId 'PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand' $e = { [MSFT_3090412]::f4() } | Should -Throw -PassThru -ErrorId 'PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand'
$e.InvocationInfo.Line | Should -Match ([regex]::Escape('dir nosuchfile -ErrorAction Stop')) $e.InvocationInfo.Line | Should -Match ([regex]::Escape('Get-ChildItem nosuchfile -ErrorAction Stop'))
} }
} }

View file

@ -90,7 +90,7 @@ Describe "File redirection mixed with Out-Null" -Tags CI {
"some text" > $TestDrive\out.txt | Out-Null "some text" > $TestDrive\out.txt | Out-Null
Get-Content $TestDrive\out.txt | Should -BeExactly "some text" Get-Content $TestDrive\out.txt | Should -BeExactly "some text"
echo "some more text" > $TestDrive\out.txt | Out-Null Write-Output "some more text" > $TestDrive\out.txt | Out-Null
Get-Content $TestDrive\out.txt | Should -BeExactly "some more text" Get-Content $TestDrive\out.txt | Should -BeExactly "some more text"
} }
} }

View file

@ -5,7 +5,7 @@ Describe "Using assembly" -Tags "CI" {
try try
{ {
pushd $PSScriptRoot Push-Location $PSScriptRoot
$guid = [Guid]::NewGuid() $guid = [Guid]::NewGuid()
Add-Type -OutputAssembly $PSScriptRoot\UsingAssemblyTest$guid.dll -TypeDefinition @" Add-Type -OutputAssembly $PSScriptRoot\UsingAssemblyTest$guid.dll -TypeDefinition @"
@ -102,6 +102,6 @@ public class ABC {}
finally finally
{ {
Remove-Item .\UsingAssemblyTest$guid.dll Remove-Item .\UsingAssemblyTest$guid.dll
popd Pop-Location
} }
} }

View file

@ -76,7 +76,7 @@ Describe "Using Namespace" -Tags "CI" {
} }
foo | Should -Be OK foo | Should -Be OK
$cmdInfo = gcm foo $cmdInfo = Get-Commmand foo
$cmdInfo.ScriptBlock.Attributes[0] | Should -Be System.Diagnostics.DebuggerStepThroughAttribute $cmdInfo.ScriptBlock.Attributes[0] | Should -Be System.Diagnostics.DebuggerStepThroughAttribute
$cmdInfo.Parameters['a'].Attributes[1] | Should -Be System.Runtime.CompilerServices.CompilerGeneratedAttribute $cmdInfo.Parameters['a'].Attributes[1] | Should -Be System.Runtime.CompilerServices.CompilerGeneratedAttribute
$cmdInfo.Parameters['b'].Attributes[1] | Should -Be System.Runtime.CompilerServices.CompilerGeneratedAttribute $cmdInfo.Parameters['b'].Attributes[1] | Should -Be System.Runtime.CompilerServices.CompilerGeneratedAttribute

View file

@ -32,7 +32,7 @@ Describe "Breakpoints set on custom FileSystem provider files should work" -Tags
# #
# Verify that the breakpoint is hit when using the provider # Verify that the breakpoint is hit when using the provider
# #
pushd tmpTestA1:\ Push-Location tmpTestA1:\
$breakpoint = set-psbreakpoint .\$scriptName 1 -action { continue } $breakpoint = set-psbreakpoint .\$scriptName 1 -action { continue }
& .\$scriptName & .\$scriptName
@ -42,7 +42,7 @@ Describe "Breakpoints set on custom FileSystem provider files should work" -Tags
} }
finally finally
{ {
popd Pop-Location
if ($null -ne $breakpoint) { $breakpoint | remove-psbreakpoint } if ($null -ne $breakpoint) { $breakpoint | remove-psbreakpoint }
if (Test-Path $scriptFullName) { Remove-Item $scriptFullName -Force } if (Test-Path $scriptFullName) { Remove-Item $scriptFullName -Force }
@ -89,7 +89,7 @@ Describe "Tests line breakpoints on dot-sourced files" -Tags "CI" {
# #
# Set the breakpoint and verify it is hit # Set the breakpoint and verify it is hit
# #
$breakpoint = sbp $scriptFile 17 -action { continue; } $breakpoint = Set-PsBreakpoint $scriptFile 17 -action { continue; }
& $scriptFile & $scriptFile
@ -137,8 +137,8 @@ Describe "Function calls clear debugger cache too early" -Tags "CI" {
# #
# Set the breakpoints and verify they are hit # Set the breakpoints and verify they are hit
# #
$breakpoint1 = sbp $scriptFile 7 -action { continue; } $breakpoint1 = Set-PsBreakpoint $scriptFile 7 -action { continue; }
$breakpoint2 = sbp $scriptFile 9 -action { continue; } $breakpoint2 = Set-PsBreakpoint $scriptFile 9 -action { continue; }
& $scriptFile & $scriptFile
@ -180,7 +180,7 @@ Describe "Line breakpoints on commands in multi-line pipelines" -Tags "CI" {
get-unique get-unique
'@ '@
$breakpoints = sbp $script 1,2,3 -action { continue } $breakpoints = Set-PsBreakpoint $script 1,2,3 -action { continue }
$null = & $script $null = & $script
@ -201,7 +201,7 @@ Describe "Line breakpoints on commands in multi-line pipelines" -Tags "CI" {
if ($null -ne $breakpoints) { $breakpoints | remove-psbreakpoint } if ($null -ne $breakpoints) { $breakpoints | remove-psbreakpoint }
if (Test-Path $script) if (Test-Path $script)
{ {
del $script -Force Remove-Item $script -Force
} }
} }
@ -218,7 +218,7 @@ Describe "Line breakpoints on commands in multi-line pipelines" -Tags "CI" {
$f = $a.GetFile($scriptPath1) $f = $a.GetFile($scriptPath1)
$scriptPath2 = $f.ShortPath $scriptPath2 = $f.ShortPath
$breakpoints = sbp $scriptPath2 1,2,3 -action { continue } $breakpoints = Set-PsBreakpoint $scriptPath2 1,2,3 -action { continue }
$null = & $scriptPath2 $null = & $scriptPath2
} }
@ -290,7 +290,7 @@ Describe "Unit tests for various script breakpoints" -Tags "CI" {
# #
# Ensure there are no breakpoints at start of test # Ensure there are no breakpoints at start of test
# #
gbp | rbp Get-PsBreakpoint | Remove-PsBreakpoint
# #
# Create a couple of scripts # Create a couple of scripts
@ -304,16 +304,16 @@ Describe "Unit tests for various script breakpoints" -Tags "CI" {
# #
# Set several breakpoints of different types # Set several breakpoints of different types
# #
$line1 = sbp $scriptFile1 1 $line1 = Set-PsBreakpoint $scriptFile1 1
$line2 = sbp $scriptFile2 2 $line2 = Set-PsBreakpoint $scriptFile2 2
$cmd1 = sbp -c command1 -s $scriptFile1 $cmd1 = Set-PsBreakpoint -c command1 -s $scriptFile1
$cmd2 = sbp -c command2 -s $scriptFile2 $cmd2 = Set-PsBreakpoint -c command2 -s $scriptFile2
$cmd3 = sbp -c command3 $cmd3 = Set-PsBreakpoint -c command3
$var1 = sbp -v variable1 -s $scriptFile1 $var1 = Set-PsBreakpoint -v variable1 -s $scriptFile1
$var2 = sbp -v variable2 -s $scriptFile2 $var2 = Set-PsBreakpoint -v variable2 -s $scriptFile2
$var3 = sbp -v variable3 $var3 = Set-PsBreakpoint -v variable3
# #
# The default parameter set must return all breakpoints # The default parameter set must return all breakpoints
@ -344,9 +344,9 @@ Describe "Unit tests for various script breakpoints" -Tags "CI" {
$directoryName = [System.IO.Path]::GetDirectoryName($scriptFile1) $directoryName = [System.IO.Path]::GetDirectoryName($scriptFile1)
$fileName = [System.IO.Path]::GetFileName($scriptFile1) $fileName = [System.IO.Path]::GetFileName($scriptFile1)
pushd $directoryName Push-Location $directoryName
Verify { get-psbreakpoint -script $fileName } $line1,$cmd1,$var1 Verify { get-psbreakpoint -script $fileName } $line1,$cmd1,$var1
popd Pop-Location
# #
# Query by Type # Query by Type
@ -450,9 +450,9 @@ Describe "Unit tests for line breakpoints on dot-sourced files" -Tags "CI" {
# #
# Set a couple of line breakpoints on the file, dot-source it and verify that the breakpoints are hit # Set a couple of line breakpoints on the file, dot-source it and verify that the breakpoints are hit
# #
$breakpoint1 = sbp $scriptFile 4 -action { continue; } $breakpoint1 = Set-PsBreakpoint $scriptFile 4 -action { continue; }
$breakpoint2 = sbp $scriptFile 9 -action { continue; } $breakpoint2 = Set-PsBreakpoint $scriptFile 9 -action { continue; }
$breakpoint3 = sbp $scriptFile 24 -action { continue; } $breakpoint3 = Set-PsBreakpoint $scriptFile 24 -action { continue; }
. $scriptFile . $scriptFile
@ -547,10 +547,10 @@ Describe "Unit tests for line breakpoints on modules" -Tags "CI" {
# #
# Set a couple of line breakpoints on the module and verify that they are hit # Set a couple of line breakpoints on the module and verify that they are hit
# #
$breakpoint1 = sbp $moduleFile 4 -action { continue } $breakpoint1 = Set-PsBreakpoint $moduleFile 4 -action { continue }
$breakpoint2 = sbp $moduleFile 9 -action { continue } $breakpoint2 = Set-PsBreakpoint $moduleFile 9 -action { continue }
$breakpoint3 = sbp $moduleFile 24 -Action { continue } $breakpoint3 = Set-PsBreakpoint $moduleFile 24 -Action { continue }
$breakpoint4 = sbp $moduleFile 25 -Action { continue } $breakpoint4 = Set-PsBreakpoint $moduleFile 25 -Action { continue }
ModuleFunction1 ModuleFunction1

View file

@ -41,7 +41,7 @@ Describe "Tests Debugger GetCallStack() on runspaces when attached to a WinRM ho
$count = 0 $count = 0
while (($hostRS.RunspaceAvailability -ne 'Available') -and ($count++ -lt 60)) while (($hostRS.RunspaceAvailability -ne 'Available') -and ($count++ -lt 60))
{ {
sleep -Milliseconds 500 Start-Sleep -Milliseconds 500
} }
It "Verifies that the attached-to host runspace is available" { It "Verifies that the attached-to host runspace is available" {
($hostRS.RunspaceAvailability -eq 'Available') | Should -BeTrue ($hostRS.RunspaceAvailability -eq 'Available') | Should -BeTrue

View file

@ -113,7 +113,7 @@ Describe 'Line endings' -Tags "CI" {
# wrap the content in the specified begin and end quoting characters. # wrap the content in the specified begin and end quoting characters.
$content = "$($Begin)$($expected)$($End)" $content = "$($Begin)$($expected)$($End)"
$actual = iex $content $actual = Invoke-Expression $content
# $actual should be the content string ($expected) without the begin and end quoting characters. # $actual should be the content string ($expected) without the begin and end quoting characters.
$actual | Should -BeExactly $expected $actual | Should -BeExactly $expected

View file

@ -24,7 +24,7 @@ Describe "Native streams behavior with PowerShell" -Tags 'CI' {
} }
It 'uses ErrorRecord object to return stderr output' { It 'uses ErrorRecord object to return stderr output' {
($out | measure).Count | Should -BeGreaterThan 1 ($out | Measure-Object).Count | Should -BeGreaterThan 1
$out[0] | Should -BeOfType 'System.Management.Automation.ErrorRecord' $out[0] | Should -BeOfType 'System.Management.Automation.ErrorRecord'
$out[0].FullyQualifiedErrorId | Should -Be 'NativeCommandError' $out[0].FullyQualifiedErrorId | Should -Be 'NativeCommandError'
@ -36,7 +36,7 @@ Describe "Native streams behavior with PowerShell" -Tags 'CI' {
} }
It 'uses correct exception messages for error stream' { It 'uses correct exception messages for error stream' {
($out | measure).Count | Should -Be 9 ($out | Measure-Object).Count | Should -Be 9
$out[0].Exception.Message | Should -BeExactly 'foo' $out[0].Exception.Message | Should -BeExactly 'foo'
$out[1].Exception.Message | Should -BeExactly '' $out[1].Exception.Message | Should -BeExactly ''
$out[2].Exception.Message | Should -BeExactly 'bar' $out[2].Exception.Message | Should -BeExactly 'bar'

View file

@ -60,7 +60,7 @@ Describe 'Test for cmdlet to support Ordered Attribute on hash literal nodes' -T
$script:a = $null $script:a = $null
{$script:a = dir | select-object -property Name, ( {$script:a = Get-ChildItem | select-object -property Name, (
[ordered]@{Name="IsDirectory"; [ordered]@{Name="IsDirectory";
Expression ={$_.PSIsContainer}})} | Should -Not -Throw Expression ={$_.PSIsContainer}})} | Should -Not -Throw

View file

@ -159,7 +159,7 @@ Describe "Debug-job test" -tag "Feature" {
# we check this via implication. # we check this via implication.
# if we're debugging a job, then the debugger will have a callstack # if we're debugging a job, then the debugger will have a callstack
It "Debug-Job will break into debugger" -pending { It "Debug-Job will break into debugger" -pending {
$ps.AddScript('$job = start-job { 1..300 | ForEach-Object { sleep 1 } }').Invoke() $ps.AddScript('$job = start-job { 1..300 | ForEach-Object { Start-Sleep 1 } }').Invoke()
$ps.Commands.Clear() $ps.Commands.Clear()
$ps.Runspace.Debugger.GetCallStack() | Should -BeNullOrEmpty $ps.Runspace.Debugger.GetCallStack() | Should -BeNullOrEmpty
Start-Sleep 3 Start-Sleep 3

View file

@ -273,8 +273,8 @@ function CompareCounterSets
for ($i = 1; $i -lt $setA.Length; $i++) for ($i = 1; $i -lt $setA.Length; $i++)
{ {
$setA[$i].CounterSamples.Length | Should -Be $setB[$i].CounterSamples.Length $setA[$i].CounterSamples.Length | Should -Be $setB[$i].CounterSamples.Length
$samplesA = ($setA[$i].CounterSamples | sort -Property Path) $samplesA = ($setA[$i].CounterSamples | Sort-Object -Property Path)
$samplesB = ($setB[$i].CounterSamples | sort -Property Path) $samplesB = ($setB[$i].CounterSamples | Sort-Object -Property Path)
(DateTimesAreEqualish $setA[$i].TimeStamp $setB[$i].TimeStamp) | Should -BeTrue (DateTimesAreEqualish $setA[$i].TimeStamp $setB[$i].TimeStamp) | Should -BeTrue
for ($j = 0; $j -lt $samplesA.Length; $j++) for ($j = 0; $j -lt $samplesA.Length; $j++)
{ {

View file

@ -181,7 +181,7 @@ Describe "Get-ChildItem" -Tags "CI" {
$foobar = Get-Childitem env: | Where-Object {$_.Name -eq '__foobar'} $foobar = Get-Childitem env: | Where-Object {$_.Name -eq '__foobar'}
$count = if ($IsWindows) { 1 } else { 2 } $count = if ($IsWindows) { 1 } else { 2 }
($foobar | measure).Count | Should -Be $count ($foobar | Measure-Object).Count | Should -Be $count
} }
catch catch
{ {

View file

@ -1019,7 +1019,7 @@ try {
$computerInformation = Get-ComputerInfoForTest $computerInformation = Get-ComputerInfoForTest
$propertyNames = Get-PropertyNamesForComputerInfoTest $propertyNames = Get-PropertyNamesForComputerInfoTest
$Expected = New-ExpectedComputerInfo $propertyNames $Expected = New-ExpectedComputerInfo $propertyNames
$testCases = $propertyNames | %{ @{ "Property" = $_ } } $testCases = $propertyNames | ForEach-Object { @{ "Property" = $_ } }
} }
# #

View file

@ -3,11 +3,11 @@
Describe "Get-Location" -Tags "CI" { Describe "Get-Location" -Tags "CI" {
$currentDirectory=[System.IO.Directory]::GetCurrentDirectory() $currentDirectory=[System.IO.Directory]::GetCurrentDirectory()
BeforeEach { BeforeEach {
pushd $currentDirectory Push-Location $currentDirectory
} }
AfterEach { AfterEach {
popd Pop-location
} }
It "Should list the output of the current working directory" { It "Should list the output of the current working directory" {

View file

@ -3,7 +3,7 @@
Describe "Test-Push-Location" -Tags "CI" { Describe "Test-Push-Location" -Tags "CI" {
New-Variable -Name startDirectory -Value $(Get-Location).Path -Scope Global -Force New-Variable -Name startDirectory -Value $(Get-Location).Path -Scope Global -Force
BeforeEach { cd $startDirectory } BeforeEach { Set-Location $startDirectory }
It "Should be called without error" { It "Should be called without error" {
{ Push-Location } | Should -Not -Throw { Push-Location } | Should -Not -Throw
@ -41,7 +41,7 @@ Describe "Test-Push-Location" -Tags "CI" {
pushd .. pushd ..
$aliasDirectory = $(Get-Location).Path $aliasDirectory = $(Get-Location).Path
cd $startDirectory Set-Location $startDirectory
Push-Location .. Push-Location ..
$cmdletDirectory = $(Get-Location).Path $cmdletDirectory = $(Get-Location).Path
@ -53,5 +53,5 @@ Describe "Test-Push-Location" -Tags "CI" {
} }
# final cleanup # final cleanup
cd $startDirectory Set-Location $startDirectory
} }

View file

@ -20,7 +20,7 @@ try
$EICAR_STRING_B64 = "awZ8EmMWc3JjaAdvY2lrBgcbY20aBHBwGgROF3Z6cHJhHmBncn13cmF3HnJ9Z3plemFmYB5ndmBnHnV6f3YSF3sYexk= " $EICAR_STRING_B64 = "awZ8EmMWc3JjaAdvY2lrBgcbY20aBHBwGgROF3Z6cHJhHmBncn13cmF3HnJ9Z3plemFmYB5ndmBnHnV6f3YSF3sYexk= "
$bytes = [System.Convert]::FromBase64String($EICAR_STRING_B64) $bytes = [System.Convert]::FromBase64String($EICAR_STRING_B64)
$EICAR_STRING = -join ($bytes | % { [char]($_ -bxor 0x33) }) $EICAR_STRING = -join ($bytes | ForeEach-Object { [char]($_ -bxor 0x33) })
{ Invoke-Expression -Command "echo '$EICAR_STRING'" } | { Invoke-Expression -Command "echo '$EICAR_STRING'" } |
Should -Throw -ErrorId "ScriptContainedMaliciousContent,Microsoft.PowerShell.Commands.InvokeExpressionCommand" Should -Throw -ErrorId "ScriptContainedMaliciousContent,Microsoft.PowerShell.Commands.InvokeExpressionCommand"
} }

View file

@ -80,7 +80,7 @@ try
"@ "@
$command += @' $command += @'
$null = help NestedFn1 2>$null; $null = help NestedFn1 2>$null;
$result = Get-Command NestedFn1 2>$null; $result = Get-Command NestedFn1 2>$null;
return ($result -ne $null) return ($result -ne $null)
'@ '@
$isCommandAccessible = powershell.exe -noprofile -nologo -c $command $isCommandAccessible = powershell.exe -noprofile -nologo -c $command
@ -140,7 +140,7 @@ try
$mod = Import-Module -Name $moduleFilePath -Force -PassThru $mod = Import-Module -Name $moduleFilePath -Force -PassThru
# Running module function TestRestrictedSession should throw a 'script not allowed' error # Running module function TestRestrictedSession should throw a 'script not allowed' error
# because it runs in a 'no language' session. # because it runs in a 'no language' session.
try try
{ {
@ -667,7 +667,7 @@ try
{ {
$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"
$result = @(TabExpansion2 '(1234 -as [IntPtr]).' 20 | % CompletionMatches | ? CompletionText -Match Pointer) $result = @(TabExpansion2 '(1234 -as [IntPtr]).' 20 | ForEach-Object CompletionMatches | Where-Object CompletionText -Match Pointer)
} }
finally finally
{ {
@ -977,7 +977,7 @@ try
$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage" $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"
Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode Invoke-LanguageModeTestingSupportCmdlet -SetLockdownMode
$results = $sb | Start-ThreadJob -ScriptBlock { $input | foreach { & $_ } } | Wait-Job | Receive-Job $results = $sb | Start-ThreadJob -ScriptBlock { $input | ForEach-Object { & $_ } } | Wait-Job | Receive-Job
} }
finally finally
{ {

View file

@ -56,7 +56,7 @@ a,b,c
It "Should be able to have multiple columns" { It "Should be able to have multiple columns" {
$actualData = $testColumns | ConvertFrom-Csv $actualData = $testColumns | ConvertFrom-Csv
$actualLength = $($( $actualData | gm) | Where-Object {$_.MemberType -eq "NoteProperty" }).Length $actualLength = $($( $actualData | Get-Member) | Where-Object {$_.MemberType -eq "NoteProperty" }).Length
$actualLength | Should -Be 3 $actualLength | Should -Be 3
} }

View file

@ -115,7 +115,7 @@ Describe "Group-Object" -Tags "CI" {
It "User's scenario should work (see issue #6933 for link to stackoverflow question)" { It "User's scenario should work (see issue #6933 for link to stackoverflow question)" {
# Sort numbers into two groups even succeeded, odd failed. # Sort numbers into two groups even succeeded, odd failed.
$result = 1..9 | foreach {[PSCustomObject]@{ErrorMessage = if ($_ % 2) {'SomeError'} else {''}}} | $result = 1..9 | ForEach-Object {[PSCustomObject]@{ErrorMessage = if ($_ % 2) {'SomeError'} else {''}}} |
Group-Object -Property {if ($_.ErrorMessage) {'Failed'} else {'Successful'}} -AsHashTable Group-Object -Property {if ($_.ErrorMessage) {'Failed'} else {'Successful'}} -AsHashTable
$result['Failed'].ErrorMessage.Count | Should -Be 5 $result['Failed'].ErrorMessage.Count | Should -Be 5

View file

@ -855,7 +855,7 @@ try
$ipaddress $ipaddress
) )
"Bound parameter: $($myInvocation.BoundParameters.Keys | sort)" "Bound parameter: $($myInvocation.BoundParameters.Keys | Sort-Object)"
} }
} }
@ -937,7 +937,7 @@ try
$ipaddress $ipaddress
) )
"Bound parameter: $($myInvocation.BoundParameters.Keys | sort)" "Bound parameter: $($myInvocation.BoundParameters.Keys | Sort-Object)"
} }
} }
@ -988,14 +988,14 @@ try
$PriorityClass $PriorityClass
) )
"Bound parameter: $($myInvocation.BoundParameters.Keys | sort)" "Bound parameter: $($myInvocation.BoundParameters.Keys | Sort-Object)"
} }
} }
# Sanity checks. # Sanity checks.
Invoke-Command $session {gps -pid $pid | foo} | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime" Invoke-Command $session {Get-Process -pid $pid | foo} | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime"
Invoke-Command $session {gps -pid $pid | foo -Total 5} | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime" Invoke-Command $session {Get-Process -pid $pid | foo -Total 5} | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime"
Invoke-Command $session {gps -pid $pid | foo -Priority normal} | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime" Invoke-Command $session {Get-Process -pid $pid | foo -Priority normal} | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime"
$module = Import-PSSession $session foo -AllowClobber $module = Import-PSSession $session foo -AllowClobber
} }
@ -1006,15 +1006,15 @@ try
} }
It "Pipeline binding works by property name" { It "Pipeline binding works by property name" {
(gps -id $pid | foo) | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime" (Get-Process -id $pid | foo) | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime"
} }
It "Pipeline binding works by property name" { It "Pipeline binding works by property name" {
(gps -id $pid | foo -Total 5) | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime" (Get-Process -id $pid | foo -Total 5) | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime"
} }
It "Pipeline binding works by property name" { It "Pipeline binding works by property name" {
(gps -id $pid | foo -Priority normal) | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime" (Get-Process -id $pid | foo -Priority normal) | Should -BeExactly "Bound parameter: PriorityClass TotalProcessorTime"
} }
} }
@ -1034,7 +1034,7 @@ try
$ipaddress $ipaddress
) )
"Bound parameter: $($myInvocation.BoundParameters.Keys | sort)" "Bound parameter: $($myInvocation.BoundParameters.Keys | Sort-Object)"
} }
} }
@ -1625,7 +1625,7 @@ try
It "Strange parameter names should trigger an error" { It "Strange parameter names should trigger an error" {
try { try {
Invoke-Command $session { function attack(${foo="$(calc)"}){echo "It is done."}} Invoke-Command $session { function attack(${foo="$(calc)"}){Write-Output "It is done."}}
$module = Import-PSSession -Session $session -CommandName attack -ErrorAction SilentlyContinue -ErrorVariable expectedError -AllowClobber $module = Import-PSSession -Session $session -CommandName attack -ErrorAction SilentlyContinue -ErrorVariable expectedError -AllowClobber
$expectedError | Should -Not -BeNullOrEmpty $expectedError | Should -Not -BeNullOrEmpty
} finally { } finally {
@ -1864,7 +1864,7 @@ try
$oldNumberOfHandlers | Should -Be $newNumberOfHandlers $oldNumberOfHandlers | Should -Be $newNumberOfHandlers
## Private functions from the implicit remoting module shouldn't get imported into global scope ## Private functions from the implicit remoting module shouldn't get imported into global scope
@(dir function:*Implicit* -ErrorAction SilentlyContinue).Count | Should -Be 0 @(Get-ChildItem function:*Implicit* -ErrorAction SilentlyContinue).Count | Should -Be 0
} }
} }
@ -1945,9 +1945,9 @@ try
It "Should have a new session when the disconnected session cannot be re-connected" -Pending { It "Should have a new session when the disconnected session cannot be re-connected" -Pending {
## Disconnect session and make it un-connectable. ## Disconnect session and make it un-connectable.
Disconnect-PSSession $session Disconnect-PSSession $session
start powershell -arg 'Get-PSSession -cn localhost -name Session102 | Connect-PSSession' -Wait Start-Process powershell -arg 'Get-PSSession -cn localhost -name Session102 | Connect-PSSession' -Wait
sleep 3 Start-Sleep 3
## This time a new session is created because the old one is unavailable. ## This time a new session is created because the old one is unavailable.
$dSessionPid = Get-RemoteVariable pid $dSessionPid = Get-RemoteVariable pid
@ -1970,7 +1970,7 @@ try
if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue } if ($null -ne $session) { Remove-PSSession $session -ErrorAction SilentlyContinue }
} }
It "Select -First should work with implicit remoting" { It "Select-Object -First should work with implicit remoting" {
$bar = foo | Select-Object -First 2 $bar = foo | Select-Object -First 2
$bar | Should -Not -BeNullOrEmpty $bar | Should -Not -BeNullOrEmpty
$bar.Count | Should -Be 2 $bar.Count | Should -Be 2

View file

@ -69,7 +69,7 @@ Describe "Import-Csv File Format Tests" -Tags "CI" {
} }
# Test set is the same for all file formats # Test set is the same for all file formats
foreach ($testCsv in $testCSVfiles) { foreach ($testCsv in $testCSVfiles) {
$FileName = (dir $testCsv).Name $FileName = (Get-ChildItem $testCsv).Name
Context "Next test file: $FileName" { Context "Next test file: $FileName" {
BeforeAll { BeforeAll {
$CustomHeaderParams = @{Header = $customHeader; Delimiter = ","} $CustomHeaderParams = @{Header = $customHeader; Delimiter = ","}

View file

@ -12,13 +12,13 @@ Describe "Measure-Command" -Tags "CI" {
Context "Validate that it is executing commands correctly" { Context "Validate that it is executing commands correctly" {
It "Should return TimeSpan after executing a script" { It "Should return TimeSpan after executing a script" {
Measure-Command { echo hi } | Should -BeOfType timespan Measure-Command { Write-Output hi } | Should -BeOfType timespan
} }
It "Should return TimeSpan after executing a cmdlet" { It "Should return TimeSpan after executing a cmdlet" {
$pesterscript = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath assets) -ChildPath echoscript.ps1 $pesterscript = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath assets) -ChildPath echoscript.ps1
$testfile = $pesterscript $testfile = $pesterscript
$testcommand = "echo pestertestscript" $testcommand = "Write-Output pestertestscript"
$testcommand | Add-Content -Path $testfile $testcommand | Add-Content -Path $testfile
Measure-Command { $pesterscript } | Should -BeOfType timespan Measure-Command { $pesterscript } | Should -BeOfType timespan

View file

@ -4,7 +4,7 @@ Describe "Register-EngineEvent" -Tags "CI" {
Context "Check return type of Register-EngineEvent" { Context "Check return type of Register-EngineEvent" {
It "Should return System.Management.Automation.PSEventJob as return type of Register-EngineEvent" { It "Should return System.Management.Automation.PSEventJob as return type of Register-EngineEvent" {
Register-EngineEvent -SourceIdentifier PesterTestRegister -Action {echo registerengineevent} | Should -BeOfType System.Management.Automation.PSEventJob Register-EngineEvent -SourceIdentifier PesterTestRegister -Action {Write-Output registerengineevent} | Should -BeOfType System.Management.Automation.PSEventJob
Unregister-Event -sourceidentifier PesterTestRegister Unregister-Event -sourceidentifier PesterTestRegister
} }
} }

View file

@ -158,10 +158,10 @@ Describe "Select-String" -Tags "CI" {
It "Should return the fourth line in testfile1 when a relative path is used" { It "Should return the fourth line in testfile1 when a relative path is used" {
$expected = "testfile1.txt:5:No matches" $expected = "testfile1.txt:5:No matches"
pushd $testDirectory Push-Location $testDirectory
Select-String matches (Join-Path -Path $testDirectory -ChildPath testfile1.txt) | Should -Match $expected Select-String matches (Join-Path -Path $testDirectory -ChildPath testfile1.txt) | Should -Match $expected
popd Pop-Location
} }
It "Should return the fourth line in testfile1 when a regular expression is used" { It "Should return the fourth line in testfile1 when a regular expression is used" {

View file

@ -67,20 +67,20 @@ set-psbreakpoint -command foo
} }
It "-script and -line can take multiple items" { It "-script and -line can take multiple items" {
$brk = sbp -line 11,12,13 -column 1 -script $scriptFileName,$scriptFileName $brk = Set-PSBreakpoint -line 11,12,13 -column 1 -script $scriptFileName,$scriptFileName
$brk.Line | Should -BeIn 11,12,13 $brk.Line | Should -BeIn 11,12,13
$brk.Column | Should -BeIn 1 $brk.Column | Should -BeIn 1
Remove-PSBreakPoint -Id $brk.Id Remove-PSBreakPoint -Id $brk.Id
} }
It "-script and -line are positional" { It "-script and -line are positional" {
$brk = sbp $scriptFileName 13 $brk = Set-PSBreakpoint $scriptFileName 13
$brk.Line | Should -Be 13 $brk.Line | Should -Be 13
Remove-PSBreakPoint -Id $brk.Id Remove-PSBreakPoint -Id $brk.Id
} }
It "-script, -line and -column are positional" { It "-script, -line and -column are positional" {
$brk = sbp $scriptFileName 13 1 $brk = Set-PSBreakpoint $scriptFileName 13 1
$brk.Line | Should -Be 13 $brk.Line | Should -Be 13
$brk.Column | Should -Be 1 $brk.Column | Should -Be 1
Remove-PSBreakPoint -Id $brk.Id Remove-PSBreakPoint -Id $brk.Id

View file

@ -8,14 +8,14 @@ Describe "Tee-Object" -Tags "CI" {
It "Should return the output to the screen and to the variable" { It "Should return the output to the screen and to the variable" {
$teefile = $testfile $teefile = $testfile
echo teeobjecttest1 | Tee-Object -variable teeresults Write-Output teeobjecttest1 | Tee-Object -variable teeresults
$teeresults | Should -BeExactly "teeobjecttest1" $teeresults | Should -BeExactly "teeobjecttest1"
Remove-Item $teefile -ErrorAction SilentlyContinue Remove-Item $teefile -ErrorAction SilentlyContinue
} }
It "Should tee the output to a file" { It "Should tee the output to a file" {
$teefile = $testfile $teefile = $testfile
echo teeobjecttest3 | Tee-Object $teefile Write-Output teeobjecttest3 | Tee-Object $teefile
Get-Content $teefile | Should -BeExactly "teeobjecttest3" Get-Content $teefile | Should -BeExactly "teeobjecttest3"
Remove-Item $teefile -ErrorAction SilentlyContinue Remove-Item $teefile -ErrorAction SilentlyContinue
} }

View file

@ -21,7 +21,7 @@ Describe "Trace-Command" -tags "CI" {
$stack = [System.Diagnostics.Trace]::CorrelationManager.LogicalOperationStack $stack = [System.Diagnostics.Trace]::CorrelationManager.LogicalOperationStack
$stack.Push($keyword) $stack.Push($keyword)
Trace-Command -Name * -Expression {echo Foo} -ListenerOption LogicalOperationStack -FilePath $logfile Trace-Command -Name * -Expression {Write-Output Foo} -ListenerOption LogicalOperationStack -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*LogicalOperationStack=$keyword*"} $log = Get-Content $logfile | Where-Object {$_ -like "*LogicalOperationStack=$keyword*"}
$log.Count | Should -BeGreaterThan 0 $log.Count | Should -BeGreaterThan 0
@ -29,7 +29,7 @@ Describe "Trace-Command" -tags "CI" {
# GetStackTrace is not in .NET Core # GetStackTrace is not in .NET Core
It "Callstack works" -Skip:$IsCoreCLR { It "Callstack works" -Skip:$IsCoreCLR {
Trace-Command -Name * -Expression {echo Foo} -ListenerOption Callstack -FilePath $logfile Trace-Command -Name * -Expression {Write-Output Foo} -ListenerOption Callstack -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*Callstack= * System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)*"} $log = Get-Content $logfile | Where-Object {$_ -like "*Callstack= * System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)*"}
$log.Count | Should -BeGreaterThan 0 $log.Count | Should -BeGreaterThan 0
} }
@ -53,14 +53,14 @@ Describe "Trace-Command" -tags "CI" {
} }
It "None options has no effect" { It "None options has no effect" {
Trace-Command -Name * -Expression {echo Foo} -ListenerOption None -FilePath $actualLogfile Trace-Command -Name * -Expression {Write-Output Foo} -ListenerOption None -FilePath $actualLogfile
Trace-Command -name * -Expression {echo Foo} -FilePath $logfile Trace-Command -name * -Expression {Write-Output Foo} -FilePath $logfile
Compare-Object (Get-Content $actualLogfile) (Get-Content $logfile) | Should -BeNullOrEmpty Compare-Object (Get-Content $actualLogfile) (Get-Content $logfile) | Should -BeNullOrEmpty
} }
It "ThreadID works" { It "ThreadID works" {
Trace-Command -Name * -Expression {echo Foo} -ListenerOption ThreadId -FilePath $logfile Trace-Command -Name * -Expression {Write-Output Foo} -ListenerOption ThreadId -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*ThreadID=*"} $log = Get-Content $logfile | Where-Object {$_ -like "*ThreadID=*"}
$results = $log | ForEach-Object {$_.Split("=")[1]} $results = $log | ForEach-Object {$_.Split("=")[1]}
@ -68,7 +68,7 @@ Describe "Trace-Command" -tags "CI" {
} }
It "Timestamp creates logs in ascending order" { It "Timestamp creates logs in ascending order" {
Trace-Command -Name * -Expression {echo Foo} -ListenerOption Timestamp -FilePath $logfile Trace-Command -Name * -Expression {Write-Output Foo} -ListenerOption Timestamp -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*Timestamp=*"} $log = Get-Content $logfile | Where-Object {$_ -like "*Timestamp=*"}
$results = $log | ForEach-Object {$_.Split("=")[1]} $results = $log | ForEach-Object {$_.Split("=")[1]}
$sortedResults = $results | Sort-Object $sortedResults = $results | Sort-Object
@ -76,7 +76,7 @@ Describe "Trace-Command" -tags "CI" {
} }
It "ProcessId logs current process Id" { It "ProcessId logs current process Id" {
Trace-Command -Name * -Expression {echo Foo} -ListenerOption ProcessId -FilePath $logfile Trace-Command -Name * -Expression {Write-Output Foo} -ListenerOption ProcessId -FilePath $logfile
$log = Get-Content $logfile | Where-Object {$_ -like "*ProcessID=*"} $log = Get-Content $logfile | Where-Object {$_ -like "*ProcessID=*"}
$results = $log | ForEach-Object {$_.Split("=")[1]} $results = $log | ForEach-Object {$_.Split("=")[1]}

View file

@ -143,10 +143,10 @@ Describe "Update-FormatData with resources in CustomControls" -Tags "CI" {
$null = $ps.AddScript("Update-FormatData -PrependPath $formatFilePath") $null = $ps.AddScript("Update-FormatData -PrependPath $formatFilePath")
$ps.Streams.Error.Clear() $ps.Streams.Error.Clear()
$ps.Invoke() $ps.Invoke()
$sma = [appdomain]::CurrentDomain.GetAssemblies() | ? { if ($_.Location) {$_.Location.EndsWith("System.Management.Automation.dll")}} $sma = [appdomain]::CurrentDomain.GetAssemblies() | Where-Object { if ($_.Location) {$_.Location.EndsWith("System.Management.Automation.dll")}}
$smaLocation = $sma.Location $smaLocation = $sma.Location
$ps.Streams.Error | %{ $_.Exception.Message.Contains($smaLocation) | Should -BeTrue } $ps.Streams.Error | ForEach-Object { $_.Exception.Message.Contains($smaLocation) | Should -BeTrue }
$ps.Streams.Error | %{ $_.FullyQualifiedErrorId | Should -Match 'FormatXmlUpdateException' } $ps.Streams.Error | ForEach-Object { $_.FullyQualifiedErrorId | Should -Match 'FormatXmlUpdateException' }
} }
} }
} }

View file

@ -3160,7 +3160,7 @@ Describe "Web cmdlets tests using the cmdlet's aliases" -Tags "CI", "RequireAdmi
contenttype = 'text/plain' contenttype = 'text/plain'
} }
$uri = Get-WebListenerUrl -Test 'Response' -Query $query $uri = Get-WebListenerUrl -Test 'Response' -Query $query
$result = iwr $uri $result = Invoke-WebRequest $uri
$result.StatusCode | Should -Be "200" $result.StatusCode | Should -Be "200"
$result.Content | Should -Be "hello" $result.Content | Should -Be "hello"
} }
@ -3171,7 +3171,7 @@ Describe "Web cmdlets tests using the cmdlet's aliases" -Tags "CI", "RequireAdmi
body = @{Hello = "world"} | ConvertTo-Json -Compress body = @{Hello = "world"} | ConvertTo-Json -Compress
} }
$uri = Get-WebListenerUrl -Test 'Response' -Query $query $uri = Get-WebListenerUrl -Test 'Response' -Query $query
$result = irm $uri $result = Invoke-RestMethod $uri
$result.Hello | Should -Be "world" $result.Hello | Should -Be "world"
} }
} }

View file

@ -90,12 +90,12 @@ Describe "Object cmdlets" -Tags "CI" {
} }
It 'should return correct error for non-numeric input' { It 'should return correct error for non-numeric input' {
$gmi = "abc",[Datetime]::Now | measure -sum -max -ErrorVariable err -ErrorAction silentlycontinue $gmi = "abc",[Datetime]::Now | Measure-Object -sum -max -ErrorVariable err -ErrorAction silentlycontinue
$err | ForEach-Object { $_.FullyQualifiedErrorId | Should -Be 'NonNumericInputObject,Microsoft.PowerShell.Commands.MeasureObjectCommand' } $err | ForEach-Object { $_.FullyQualifiedErrorId | Should -Be 'NonNumericInputObject,Microsoft.PowerShell.Commands.MeasureObjectCommand' }
} }
It 'should have the correct count' { It 'should have the correct count' {
$gmi = "abc",[Datetime]::Now | measure -sum -max -ErrorVariable err -ErrorAction silentlycontinue $gmi = "abc",[Datetime]::Now | Measure-Object -sum -max -ErrorVariable err -ErrorAction silentlycontinue
$gmi.Count | Should -Be 2 $gmi.Count | Should -Be 2
} }
} }

View file

@ -83,7 +83,7 @@ Describe 'Basic ThreadJob Tests' -Tags 'CI' {
} }
It 'ThreadJob with ScriptBlock' { It 'ThreadJob with ScriptBlock' {
$job = Start-ThreadJob -ScriptBlock { "Hello" } $job = Start-ThreadJob -ScriptBlock { "Hello" }
$results = $job | Receive-Job -Wait $results = $job | Receive-Job -Wait
$results | Should -Be "Hello" $results | Should -Be "Hello"
@ -107,7 +107,7 @@ Describe 'Basic ThreadJob Tests' -Tags 'CI' {
It 'ThreadJob with ScriptBlock and piped input' { It 'ThreadJob with ScriptBlock and piped input' {
$job = "Hello","Goodbye" | Start-ThreadJob -ScriptBlock { $input | foreach { $_ } } $job = "Hello","Goodbye" | Start-ThreadJob -ScriptBlock { $input | ForEach-Object { $_ } }
$results = $job | Receive-Job -Wait $results = $job | Receive-Job -Wait
$results[0] | Should -Be "Hello" $results[0] | Should -Be "Hello"
$results[1] | Should -Be "Goodbye" $results[1] | Should -Be "Goodbye"
@ -225,13 +225,13 @@ Describe 'Basic ThreadJob Tests' -Tags 'CI' {
} }
It 'ThreadJob and Verbose stream output' { It 'ThreadJob and Verbose stream output' {
$job = Start-ThreadJob -ScriptBlock { $VerbosePreference = 'Continue'; Write-Verbose "VerboseOut" } | Wait-Job $job = Start-ThreadJob -ScriptBlock { $VerbosePreference = 'Continue'; Write-Verbose "VerboseOut" } | Wait-Job
$job.Verbose | Should Match "VerboseOut" $job.Verbose | Should Match "VerboseOut"
} }
It 'ThreadJob and Verbose stream output' { It 'ThreadJob and Verbose stream output' {
$job = Start-ThreadJob -ScriptBlock { $DebugPreference = 'Continue'; Write-Debug "DebugOut" } | Wait-Job $job = Start-ThreadJob -ScriptBlock { $DebugPreference = 'Continue'; Write-Debug "DebugOut" } | Wait-Job
$job.Debug | Should -Be "DebugOut" $job.Debug | Should -Be "DebugOut"
} }
@ -334,10 +334,10 @@ Describe 'Basic ThreadJob Tests' -Tags 'CI' {
Get-Job | Where-Object PSJobTypeName -eq "ThreadJob" | Remove-Job -Force Get-Job | Where-Object PSJobTypeName -eq "ThreadJob" | Remove-Job -Force
$job1 = Start-ThreadJob -ScriptBlock { 1..2 | foreach { Start-Sleep -Milliseconds 100; "Output $_" } } -ThrottleLimit 5 $job1 = Start-ThreadJob -ScriptBlock { 1..2 | ForEach-Object { Start-Sleep -Milliseconds 100; "Output $_" } } -ThrottleLimit 5
$job2 = Start-ThreadJob -ScriptBlock { 1..2 | foreach { Start-Sleep -Milliseconds 100; "Output $_" } } $job2 = Start-ThreadJob -ScriptBlock { 1..2 | ForEach-Object { Start-Sleep -Milliseconds 100; "Output $_" } }
$job3 = Start-ThreadJob -ScriptBlock { 1..2 | foreach { Start-Sleep -Milliseconds 100; "Output $_" } } $job3 = Start-ThreadJob -ScriptBlock { 1..2 | ForEach-Object { Start-Sleep -Milliseconds 100; "Output $_" } }
$job4 = Start-ThreadJob -ScriptBlock { 1..2 | foreach { Start-Sleep -Milliseconds 100; "Output $_" } } $job4 = Start-ThreadJob -ScriptBlock { 1..2 | ForEach-Object { Start-Sleep -Milliseconds 100; "Output $_" } }
$null = $job1,$job2,$job3,$job4 | Receive-Job -Wait -AutoRemoveJob $null = $job1,$job2,$job3,$job4 | Receive-Job -Wait -AutoRemoveJob

View file

@ -2,7 +2,7 @@
# Licensed under the MIT License. # Licensed under the MIT License.
Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' { Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
BeforeAll { BeforeAll {
$testModule = Join-Path $TestDrive "UntrustedDataModeTest.psm1" $testModule = Join-Path $TestDrive "UntrustedDataModeTest.psm1"
@ -42,11 +42,11 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
[Parameter()] [Parameter()]
[ValidateTrustedData()] [ValidateTrustedData()]
[string[]] $Name, [string[]] $Name,
[Parameter()] [Parameter()]
[ValidateTrustedData()] [ValidateTrustedData()]
[DateTime] $Date, [DateTime] $Date,
[Parameter()] [Parameter()]
[ValidateTrustedData()] [ValidateTrustedData()]
[System.IO.FileInfo] $File, [System.IO.FileInfo] $File,
@ -86,7 +86,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
## Use a different runspace ## Use a different runspace
$ps = [powershell]::Create() $ps = [powershell]::Create()
## Helper function to execute script ## Helper function to execute script
function Execute-Script function Execute-Script
{ {
@ -143,7 +143,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
Get-GlobalVar Get-GlobalVar
try { Test-WithGlobalVar } catch { $_.FullyQualifiedErrorId } try { Test-WithGlobalVar } catch { $_.FullyQualifiedErrorId }
'@ '@
$testCases = @( $testCases = @(
## Assignment in language ## Assignment in language
@{ @{
@ -173,7 +173,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
SetupScript = '& { New-Variable globalVar -Value "New-Variable in sub scope with [-Scope 1]" -Force -Scope 1 }' SetupScript = '& { New-Variable globalVar -Value "New-Variable in sub scope with [-Scope 1]" -Force -Scope 1 }'
ExpectedOutput = "New-Variable in sub scope with [-Scope 1];ParameterArgumentValidationError,Test-Untrusted" ExpectedOutput = "New-Variable in sub scope with [-Scope 1];ParameterArgumentValidationError,Test-Untrusted"
}, },
## Set-Variable ## Set-Variable
@{ @{
Name = 'Set-Variable in global scope' Name = 'Set-Variable in global scope'
@ -190,7 +190,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
SetupScript = '& { Set-Variable globalVar -Value "Set-Variable in sub scope with [-Scope 1]" -Scope 1 }' SetupScript = '& { Set-Variable globalVar -Value "Set-Variable in sub scope with [-Scope 1]" -Scope 1 }'
ExpectedOutput = "Set-Variable in sub scope with [-Scope 1];ParameterArgumentValidationError,Test-Untrusted" ExpectedOutput = "Set-Variable in sub scope with [-Scope 1];ParameterArgumentValidationError,Test-Untrusted"
}, },
## New-Item ## New-Item
@{ @{
Name = 'New-Item in global scope' Name = 'New-Item in global scope'
@ -203,7 +203,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
SetupScript = 'Set-GlobalVar; & { New-Item variable:\globalVar -Value "New-Item in sub scope" -Force }' SetupScript = 'Set-GlobalVar; & { New-Item variable:\globalVar -Value "New-Item in sub scope" -Force }'
ExpectedOutput = "Trusted-Global;Trusted-Global" ExpectedOutput = "Trusted-Global;Trusted-Global"
}, },
## Set-Item ## Set-Item
@{ @{
Name = 'Set-Item in global scope' Name = 'Set-Item in global scope'
@ -216,7 +216,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
SetupScript = 'Set-GlobalVar; & { Set-Item variable:\globalVar -Value "Set-Item in sub scope" -Force }' SetupScript = 'Set-GlobalVar; & { Set-Item variable:\globalVar -Value "Set-Item in sub scope" -Force }'
ExpectedOutput = "Trusted-Global;Trusted-Global" ExpectedOutput = "Trusted-Global;Trusted-Global"
}, },
## Error Variable ## Error Variable
@{ @{
Name = 'ErrorVariable in global scope' Name = 'ErrorVariable in global scope'
@ -294,7 +294,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
[scriptblock]::Create('data global:var { "data section" }') [scriptblock]::Create('data global:var { "data section" }')
throw "No Exception!" throw "No Exception!"
} catch { } catch {
## Syntax 'data global:var { }' is not supported at the time writting the tests here ## Syntax 'data global:var { }' is not supported at the time writting the tests here
## If this test fail, then maybe this syntax is supported now, and in that case, please ## If this test fail, then maybe this syntax is supported now, and in that case, please
## enable the test 'Data Section - "data global:var"' in $testCases above ## enable the test 'Data Section - "data global:var"' in $testCases above
@ -304,7 +304,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
} }
Context "Set variable in Import-LocalizedData" { Context "Set variable in Import-LocalizedData" {
BeforeAll { BeforeAll {
$localData = Join-Path $TestDrive "local.psd1" $localData = Join-Path $TestDrive "local.psd1"
Set-Content $localData -Value '"Localized-Data"' Set-Content $localData -Value '"Localized-Data"'
@ -323,7 +323,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
} }
Context "Exported variables by module loading" { Context "Exported variables by module loading" {
BeforeAll { BeforeAll {
## Create a module that exposes two variables ## Create a module that exposes two variables
$VarModule = Join-Path $TestDrive "Var.psm1" $VarModule = Join-Path $TestDrive "Var.psm1"
@ -393,7 +393,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
It "test 'ValidateTrustedDataAttribute' NOT take effect in non-FullLanguage [Invoke-Expression]" { It "test 'ValidateTrustedDataAttribute' NOT take effect in non-FullLanguage [Invoke-Expression]" {
## Run this in the global scope, so value of $globalVar will be marked as untrusted ## Run this in the global scope, so value of $globalVar will be marked as untrusted
$result = Execute-Script -Script @' $result = Execute-Script -Script @'
$globalVar = "gps -id $PID" $globalVar = "Get-Process -id $PID"
Invoke-Expression -Command $globalVar | ForEach-Object Id Invoke-Expression -Command $globalVar | ForEach-Object Id
'@ '@
$result | Should Be $PID $result | Should Be $PID
@ -529,7 +529,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
} }
Context "Validate trusted data for parameters of some built-in powershell cmdlets" { Context "Validate trusted data for parameters of some built-in powershell cmdlets" {
BeforeAll { BeforeAll {
$ScriptTemplate = @' $ScriptTemplate = @'
try {{ try {{
@ -548,7 +548,7 @@ Describe "UntrustedDataMode tests for variable assignments" -Tags 'CI' {
@{ Name = "test 'ValidateTrustedDataAttribute' on [Start-Job]"; Argument = '$globalVar = {1+1}; Test-StartJob $globalVar'; ExpectedErrorId = "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartJobCommand" } @{ Name = "test 'ValidateTrustedDataAttribute' on [Start-Job]"; Argument = '$globalVar = {1+1}; Test-StartJob $globalVar'; ExpectedErrorId = "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartJobCommand" }
) )
} }
It "<Name>" -TestCases $testCases { It "<Name>" -TestCases $testCases {
param ($Argument, $ExpectedErrorId) param ($Argument, $ExpectedErrorId)
## Run this in the global scope, so value of $globalVar will be marked as untrusted ## Run this in the global scope, so value of $globalVar will be marked as untrusted