MegaBites-AI/Windows-powershell
0372
1# Copyright (c) Microsoft Corporation.2# Licensed under the MIT License.3 4Describe "ForEach-Object" -Tags "CI" {5 BeforeAll {6 $testModulePsd1 = Join-Path $TestDrive "ForEachObjectTest.psd1"7 $testModulePsm1 = Join-Path $TestDrive "ForEachObjectTest.psm1"8 Set-Content -Path $testModulePsm1 -Value @'9 function Zoo { "ForEachObjectTest-Zoo" }10 function GetScriptBlock { return { Zoo } }11'@12 New-ModuleManifest -Path $testModulePsd1 -RootModule $testModulePsm1 -FunctionsToExport "GetScriptBlock"13 Import-Module $testModulePsd114 }15 16 AfterAll {17 Remove-Module -Name ForEachObjectTest18 }19 20 It "Foreach-Object should execute script block in caller scope" {21 $null = 1..2 | ForEach-Object { $bar = 100 }22 Get-Variable -Name bar -Scope 0 -ValueOnly | Should -BeExactly 10023 }24 25 It "Foreach-Object should execute script block in caller scope regardless of the invocation operator in use" {26 $null = 1..2 | . ForEach-Object { $bar = "bar" }27 $null = 1..2 | & ForEach-Object { $foo = "foo" }28 29 Get-Variable -Name bar -Scope 0 -ValueOnly | Should -BeExactly "bar"30 Get-Variable -Name foo -Scope 0 -ValueOnly | Should -BeExactly "foo"31 }32 33 It "Foreach-Object should execute script block in the module scope if specified" {34 { 1 | ForEach-Object { Zoo } } | Should -Throw -ErrorId "CommandNotFoundException"35 36 $m = Get-Module ForEachObjectTest37 1 | & $m ForEach-Object { Zoo } | Should -BeExactly "ForEachObjectTest-Zoo"38 }39 40 It "ForEach-Object should execute script block in the session state that the script block is associated with" {41 $sbToUse = GetScriptBlock42 1 | ForEach-Object $sbToUse | Should -BeExactly "ForEachObjectTest-Zoo"43 }44 45 It "ForEach-Object scriptblock should get the 'InvocationInfo' from the caller scope" {46 $file = New-Item TestDrive:\test.ps1 -ItemType File -Force47 Set-Content -Path $file -Value '1 | ForEach-Object { $MyInvocation.MyCommand.Name }'48 TestDrive:\test.ps1 | Should -BeExactly "test.ps1"49 }50}51 