Hi,
I want to declare the types of my variables. Is it possible to do this in loops too?
If I try I get a error (Missing variable name after foreach)
Example
foreach ( [String]$StrVar in $...)
Thx
Thomas
Hi,
I want to declare the types of my variables. Is it possible to do this in loops too?
If I try I get a error (Missing variable name after foreach)
Example
foreach ( [String]$StrVar in $...)
Thx
Thomas
I think that might be the one spot you can’t do that - I’ve never tried, but it’s possible the parser just doesn’t expect it there. Given that $StrVar is auto-populated, forcing coercion at that spot might be weird for it.
I tried it
PS> $things = @( 'Apples' 'Oranges' 'kettles' ) foreach ([string]$thing in $things){ Write-Host "This is a thing: $thing" } At line:7 char:10 + foreach ([string]$thing in $things){ + ~ Missing variable name after foreach. At line:7 char:25 + foreach ([string]$thing in $things){ + ~~ Unexpected token 'in' in expression or statement. At line:7 char:35 + foreach ([string]$thing in $things){ + ~ Unexpected token ')' in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingVariableNameAfterForeach PS>
Declaring a type doesn’t work with the way foreach works as you’re automatically defining the type of the item from the type of the collection
How about using the other foreach instead? (The one you can pipe from.)
PS /Users/js> 1..3 | foreach { $a = [string]$_; $a.gettype() } IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object True True String System.Object True True String System.Object