Hi All,
I have written a function, which simply resolve %XYZ% tags within strings with existing environment or powershell variables.
Using this function in a foreach loop causes the foreach loop to end after the first element completed.
Using this function in a while loop iterates correctly through the elements.
Why does the foreach loop end after the first element?
The powershell version I am using is as follows:
Name Value
---- -----
PSVersion 5.1.19041.1682
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.19041.1682
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
My code to verfiy / replicate the issue looks as follows:
Function Resolve-Variable{
PARAM([Parameter(Mandatory=$true,HelpMessage="Variable value to resolve")][string]$Value)
Get-ChildItem -Path ENV: | %{$Value=$($Value -replace $('%'+$($_.Name)+'%'),$_.Value)}
Get-Variable | Where-Object {$($_.Name.Length -gt 1) -and ($_.Name -ne 'Value')} | %{$Value=$($Value -replace $('%'+$($_.Name)+'%'),$_.Value)}
return $Value}
$MYVAR='TESTVariable'
$variables=@('%SYSTEMDRIVE%\Windows','%WINDIR%','%MYVAR%')
clear
#loops through all iterations
foreach($value in $variables){
Write-host "FOREACH LOOP: $value" -ForegroundColor Green}
#ends after first iteration
foreach($value in $variables){
$v=Resolve-Variable -Value $value
Write-host "FOREACH: $value -> $v" -ForegroundColor Red}
#loops through all iterations
$i=0;While($i -lt $variables.Length){$value=$variables[$i];$i++
$v=Resolve-Variable -Value $value
Write-host "WHILE: $value -> $v" -ForegroundColor Yellow}
The output is the following:
FOREACH LOOP: %SYSTEMDRIVE%\Windows
FOREACH LOOP: %WINDIR%
FOREACH LOOP: %MYVAR%
FOREACH: %SYSTEMDRIVE%\Windows -> C:\Windows
WHILE: %SYSTEMDRIVE%\Windows -> C:\Windows
WHILE: %WINDIR% -> C:\Windows
WHILE: %MYVAR% -> TESTVariable
Expected output would be:
FOREACH LOOP: %SYSTEMDRIVE%\Windows
FOREACH LOOP: %WINDIR%
FOREACH LOOP: %MYVAR%
FOREACH: %SYSTEMDRIVE%\Windows -> C:\Windows
FOREACH: %WINDIR% -> C:\Windows
FOREACH: %MYVAR% -> TESTVariable
WHILE: %SYSTEMDRIVE%\Windows -> C:\Windows
WHILE: %WINDIR% -> C:\Windows
WHILE: %MYVAR% -> TESTVariable
Thanks for your hints in advance ![]()