Creating Dynamic Variable Content

by Aug 16, 2016

PowerShell 2+

In the previous tip we introduced variables with read-only dynamic content that updated each time the variable was read. This required a little bit of C# code. With Add-Member, you can get a similar result using script properties:

$info = New-Object -TypeName PSObject
$info | Add-Member -Name Random -MemberType ScriptProperty -Value { Get-Random }
$info | Add-Member -Name Now -MemberType ScriptProperty -Value { Get-Date }

You can now call $info.Random or $info.Now to get a new random number or the current date.

Twitter This Tip! ReTweet this Tip!