milquetoastable
milquetoastable

Reputation: 176

Let-like abilities in PowerShell?

I'm a C# dev by trade, recently started doing PowerShell and I've been awed by the power (ho ho!) of it all. I'm pretty new to shell languages in general, so I think I may be approaching this question completely the wrong way and trying to write PowerShell as I may write some functional-like C#. Anyhow, say I have this block of code (it's a cheesy example, and may not be the best possible way to achieve the below, but you get the point hopefully):

Get-Website |
    ? { $_.State -eq 'Stopped' } |
        select Name, 
            @{ 
                n = "web.config path"; e = { "$($_.PhysicalPath)\Web.Config" } 
            }

I'm using extended properties to add new properties onto the object, but I'd also like reference said expanded properties like so, similar to a LINQ 'let' or a more complicated anonymous type creation.

Get-Website |
    ? { $_.State -eq 'Stopped' } |
        select Name, 
            @{ 
                n = "webconfigpath"; e = { "$($_.PhysicalPath)\Web.Config" } 
            },
            @{
                n = "webconfigexists; e = { Test-Path $_webconfigpath } 
            }

I know I can reference extended properties after the object has been selected, as it were, but is it possible to do it like the above?

Cheers Mike

Upvotes: 0

Views: 67

Answers (2)

Keith Hill
Keith Hill

Reputation: 201972

Not sure exactly what you're asking but if you stash the results in a variable you can access your extended properties after the fact:

$websites = Get-Website | ? {$_.State -eq 'Stopped'} |
    select Name, 
        @{n = "webconfigpath"; e = { "$($_.PhysicalPath)\Web.Config"}},
        @{n = "webconfigexists; e = { Test-Path $_webconfigpath }}
$websites[0].Name
$websites[0].WebConfigPath
$websites[0].WebConfigExists

Upvotes: 1

TheMadTechnician
TheMadTechnician

Reputation: 36332

I think you're looking to add members to the objects returned by your Get-Website cmdlet. If I'm reading your question correctly what you want is something like:

Get-Website | ?{$_.State -eq "Stopped"} | %{
    $_ | Add-Member "ConfigPath" "$($_.PhysicalPath)\Web.Config"
    $_ | Add-Member "ConfigPathExists" $(Test-Path "$($_.PhysicalPath)\Web.Config")
}

Or maybe I'm misreading the question.

Upvotes: 2

Related Questions