Hiding Variable Content

by Aug 19, 2015

When you override the ToString() method of an object you control how this object is displayed. The object content stays untouched, though:

$a = 123
$a = $a | Add-Member -MemberType ScriptMethod -Name toString -Value { 'secret'} -Force -PassThru
$a
$a -eq 123
$a.GetType().FullName 

You can even retrieve the original variable value from inside your custom toString() method, and display it in megabyte, for example, when it really is a byte value:

$a = 2316782313
$a = $a | Add-Member -MemberType ScriptMethod -Name toString -Value { [Math]::Round($this / 1MB,1) } -Force -PassThru
$a
$a -eq 123
$a.GetType().FullName 

Twitter This Tip! ReTweet this Tip!