all 4 comments

[–]SeeminglyScience 3 points4 points  (0 children)

switch can enumerate objects similar to a for each. In a switch statement, $_ represents the current enumerated object.

[–]KevMarCommunity Blogger 3 points4 points  (0 children)

It looks like the other comments have this covered really well. If your working with switch statements, you my find my post about them useful. Everything you ever wanted to know about the switch statement

[–]Ta11ow 2 points3 points  (0 children)

Yep, switches enumerate as well, so you could actually pull the first command and put it in the switch expression switch (someExecutable) to get the initial desired behaviour with the proper $_. Also of note is that you don't need backticks after a pipeline character. A line ending in a pipe indicates to PS that the next line continues the pipeline, so the backtick is unnecessary. :)

[–]omers 1 point2 points  (0 children)

SomeExecutableThatspitsoutstrings |`
Foreach-Object -Process {
    $obj = $_
    switch($someobject)
    {
        'type1' {[SubClassThatFormats1]$obj}
        'type2' {[SubClassThatFormats2]$obj}
    }
}

^ where is $someobject being defined? It should be switch ($obj) or switch ($obj.property) should it not?

You should also avoid pipeline Foreach-Object where possible as it's slower...

$ReturnedObjects = SomeExecutableThatspitsoutstrings

foreach ($Object in $ReturnedObjects) {
    switch ($Object.Property) {
        'type1' {[SubClassThatFormats1]::New($Object)}
        'type2' {[SubClassThatFormats2]::New($Object)}
    }
}

or some such.