Author Posts

February 28, 2018 at 8:58 am

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

February 28, 2018 at 2:52 pm

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.

February 28, 2018 at 4:36 pm

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

March 1, 2018 at 4:34 am

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