PSReference parameters

Many of the object types used in PowerShell are reference types. When an object is passed to a function, any changes made to that object will be visible outside the function, irrespective of the output generated by the command. For example, the following function accepts an object as input, then changes the value of a property on that object:

function Set-Value {
[CmdletBinding()]
param (
[PSObject]$Object
)

$Object.Value = 2
}

When the function is passed an object, the change can be seen on any other variables that reference that object:

PS> $myObject = [PSCustomObject]@{ Value = 1 }
PS> Set-Value $myObject
PS> $myObject.Value
2

Strings, numeric values, and dates, on the other hand, are all examples of value types. Changes made to a value type inside a function will not be reflected in variables that reference that value elsewhere; a new value is created. Occasionally, it is desirable to make a function affect the content of a value type without either returning the value as output or changing the value of a property of an object. The PSReference type, [Ref]can be used to achieve this. The following function normally returns true or false depending on whether Get-Date successfully parsed the date string into a DateTime object:

function Test-Date {
[CmdletBinding()]
param (
[String]$Date,

[Ref]$DateTime
)

if ($value = Get-Date $Date -ErrorAction SilentlyContinue) {
if ($DateTime) {
$DateTime.Value = $value
}
$true
} else {
$false
}
}

When the function is run, a variable that holds an existing DateTime object might be passed as an optional reference. PowerShell can update the date via the reference, changing the value outside of the function:

PS> $dateTime = Get-Date
PS> Test-Date 01/01/2019 -DateTime ([Ref]$dateTime)
true
PS> $dateTime
01 January 2019 00:00:00

The same behavior can be seem with Boolean, string, and numeric types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.144.69