I have a simple bit of code as follows:
foreach ($someFile in Get-ChildItem) {
if (($someFile.Name.Substring(0,1) -eq "R") -or ($someFile.Name.Substring(0,1) -eq "S") {
$foreach.MoveNext() | Out-Null
$someFile.Name
}
}
The idea of this simple example was to output all file names except for those that begin with the letter “R” or “S”.
When I run this in a directory with one file that begins with “R” and one that begins with “S” along with some other files it skips over the “S” file as intended, but the “R” file name still gets displayed.
I know that there are other ways that I can accomplish this, but this was an attempt to make sure that I was using the foreach correctly before using it in a more complicated bit of code.
Can anyone see something wrong with the code above? It seems like it should work to me. I’ve also confirmed that $someFile.Name.Substring(0,1) -eq "R" returns True for the “R” file as expected.
Thanks!
Currently you are returning
$someFile.Name, so that will giveSfile whenRoccurs and in the next iteration, it would go toT( or whatever is next ) and notS. Logic also breaks down when there are multiple R files etc.If you just want to skip the
RandSfiles, probably you want to just usecontinue:Also, you can use
String.StartsWithrather than the SubString. Or use-likeand combine it into a single check.