declare Variable in loops

Welcome Forums General PowerShell Q&A declare Variable in loops

This topic contains 3 replies, has 4 voices, and was last updated by

js
 
Participant
8 months, 3 weeks ago.

  • Author
    Posts
  • #94794

    Participant
    Points: 1
    Rank: Member

    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

  • #94806

    Keymaster
    Points: 1,638
    Helping HandTeam Member
    Rank: Community Hero

    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.

  • #94812

    Participant
    Points: 0
    Rank: Member

    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

  • #94848
    js

    Participant
    Points: 218
    Helping Hand
    Rank: Participant

    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                            
    

The topic ‘declare Variable in loops’ is closed to new replies.