Quantcast
Channel: PowerShell General
Viewing all articles
Browse latest Browse all 10624

strange results with $foreach.MoveNext()

$
0
0

Hello All

Can someone please help me with the following question please.

I am having a difficult time with $foreach.MoveNext()

If I do this

cls
$numbers = 1..10
foreach ($number in $numbers) {
if ($number %2 ) {[Void]$foreach.MoveNext()}
$number
}

it works as expected i.e. the output is all odd numbers

However if I do this

cls
$numbers = 1..10
foreach ($number in $numbers) {
if ($number -lt 5 ) {[Void]$foreach.MoveNext()}
$number
}

it prints all the numbers 1 through 10, rather than what I was expecting which was 5 through 10

Also on a related note

I have three files let's call them 1.txt , 2.txt and 3.txt in a directory called c:\test
file 2 is not accessible

if I do this

cls
$Files = Get-ChildItem "C:\test"| where {$_.Attributes -notmatch "Directory"}
foreach ($File in $Files) {
    get-content $($File.fullname) -ErrorAction SilentlyContinue | Out-Null
    if (!$?) {[Void]$foreach.movenext()}
$File.FullName
}

I would expect to see the following output
C:\test\1.txt
C:\test\3.txt

where as I see
C:\1.txt
C:\2.txt

What I cannot understand at the moment is all three examples of using $foreach.MoveNext() are acting differently, the only one that makes sense to me at the moment is the first example.

Basically my goal (apart from understanding what is going on here), is example 3, as I need to see if I can read the contents of a file and if not (as access is denied) move on and process the next readable file in the collection of files. At the moment rather than carrying on to the next file i.e. 3.txt in this example it appears to bombs out at 2.txt (event though I have -EA SilentlyContinue)

I would grateful for some assistance on this please, on the long road to understanding PosH Smile

Ernie

 

 

 


Viewing all articles
Browse latest Browse all 10624

Trending Articles