Using a property value in a variable

Welcome Forums General PowerShell Q&A Using a property value in a variable

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

 
Participant
2 years, 8 months ago.

  • Author
    Posts
  • #34418

    Participant
    Points: 0
    Rank: Member

    Hi,

    A quick question for you experts.

    If I have an object with multiple properties, and I put that object into a variable, I can't always reuse a single property of the object using this format $variable.property

    Using $variable.property in a path for example results in the object type being used, rather than the property value. I've come across this problem in few different scenarios, I've copied in an example below. I've tried different combinations of double and single quotes, brackets etc, but the only way I can get it to work is by creating a new variable (as shown below).

    Is there a way to use $variable.property rather than making a new variable each time?

    
    PS D:\scripts\modules> get-item IIS:\AppPools\* | select -First 1
    
    Name                     State        Applications                                
    ----                     -----        ------------                                
    .NET v2.0                Started                                                  
    
    PS D:\scripts\modules> $pool = get-item IIS:\AppPools\* | select -First 1
    
    PS D:\scripts\modules> $pool.name
    .NET v2.0
    
    PS D:\scripts\modules> Get-ItemProperty IIS:\AppPools\$pool.name
    Get-ItemProperty : Cannot find path 'IIS:\AppPools\Microsoft.IIs.PowerShell.Framework.ConfigurationElement.name' because it does not 
    exist.
    At line:1 char:1
    + Get-ItemProperty IIS:\AppPools\$pool.name
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (IIS:\AppPools\M...ionElement.name:String) [Get-ItemProperty], ItemNotFoundException
        + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemPropertyCommand
     
    
    PS D:\scripts\modules> $name = $pool.name
    
    PS D:\scripts\modules> Get-ItemProperty IIS:\AppPools\$name
    
    Name                     State        Applications                                
    ----                     -----        ------------                                
    .NET v2.0                Started                                                  
    
  • #34419

    Participant
    Points: 10
    Published
    Rank: Member
    Get-ItemProperty $pool.FullName

    or use a sub-expression

    Get-ItemProperty IIS:\AppPools\$($pool.name)
  • #34459

    Participant
    Points: 0
    Rank: Member

    Thanks. the sub expression is exactly what I was looking for

The topic ‘Using a property value in a variable’ is closed to new replies.