header1   header
header
header Register : : Login header
header
connector   connector
menuleft menuright
submenu   submenu
left
foreach-object with () and {}
Last Post 11 Mar 2010 09:28 AM by EBGreen. 3 Replies.
Printer Friendly
  •  
  •  
  •  
  •  
  •  
Sort:
PrevPrev NextNext
You are not authorized to post a reply.
Author Messages
ddUser is Offline
New Member
New Member
Posts:1
Avatar

--
11 Mar 2010 06:41 AM
    helo,
    I'm annoyed with what seems to me a strange behaviour of the foreach-object block.
    When using the following code in the shell
    ".dir", $null, ".pdf" | Foreach-object (Write-host "Hello within ()") {"begin scriptblock within {}"} {"process scriptblock within {}"} {"end scriptblock within {}"} (write-host " last block in line within ()")

    I obtain this result:

    Hello within ()
     last block in line within ()
     begin scriptblock within {}
     process scriptblock within {}
     process scriptblock within {}
     process scriptblock within {}
     end scriptblock within {}

    I have no problems with everything in the {} scriptblocks.
    But I do not understand why the instructions in ( ) are not considered as errors and why the last block with ( )
    is executed before the scriptblocks.

    The question arises because I try to find out how to interpret correctly the syntax rules returned by the get-help.
    PowerShell JediUser is Offline
    Basic Member
    Basic Member
    Posts:410
    Avatar

    --
    11 Mar 2010 09:21 AM
    I am not familiar with the "within"...

    But the Syntax for ForEach-Object looks more like this...


    $array = ".dir", $null, ".pdf"
    $array | ForEach-Object{
    $_
    }


    ForEach-Object handles each object 1 at a time "$_" means "The current pipeline object".

    So, What ever your code ends up looking like you will have to use $_ inside of ForEach-Object also you need to use the "{}" brackets.
    PoSH is a Automation Technology surfaced as a scripting language, not a "spice" ;-)
    EBGreenUser is Offline
    Advanced Member
    Advanced Member
    Posts:854
    Avatar

    --
    11 Mar 2010 09:28 AM
    Just to followup on what Jedi had to say, essentially you are doing something contrary to how the documentation says to use the cmdlet.
    "Look Ma...no strings!"
    PowerShell JediUser is Offline
    Basic Member
    Basic Member
    Posts:410
    Avatar

    --
    11 Mar 2010 09:28 AM
    You might want to do a google/bing search for ForEach-Object Examples
    PoSH is a Automation Technology surfaced as a scripting language, not a "spice" ;-)
    You are not authorized to post a reply.


    Active Forums 4.3
    right
    footer   footer
    footer Sponsored by Quest Software • SAPIEN Technologies • Compellent • Microsoft Windows Server 2008 R2 footer
    footer   footer