Dynamic Parameters in PowerShell 4.0

by Nov 4, 2013

In PowerShell, you can use variables in place of properties. This sample script defines the four property names that return profile paths, then queries the properties in a loop:

$list = 'AllUsersAllHosts','AllUsersCurrentHost','CurrentUserAllHosts','CurrentUserCurrentHost'
foreach ($property in $list)

You could also use this inside a pipeline:
'AllUsersAllHosts','AllUsersCurrentHost','CurrentUserAllHosts','CurrentUserCurrentHost' |
  ForEach-Object { $profile.$_ }  

This way, you could check and return all PowerShell profiles that are currently in use:

'AllUsersAllHosts','AllUsersCurrentHost','CurrentUserAllHosts','CurrentUserCurrentHost' |
  ForEach-Object { $profile.$_ } |
  Where-Object { Test-Path $_ } 

Likewise, you can use Get-Member to first retrieve all properties present in a given object. This would return all the properties found in PowerShell's "PrivateData" object that have "color" in their name:

$host.PrivateData | Get-Member -Name *color* | Select-Object -ExpandProperty Name 

Next, you could get all the color settings in one line:

$object = $host.PrivateData

$object | 
  Get-Member -Name *color* -MemberType *property | 
  ForEach-Object {
    $PropertyName = $_.Name
    $PropertyValue = $object.$PropertyName
    "$PropertyName = $PropertyValue"
    } |

Twitter This Tip! ReTweet this Tip!