Using PowerShell ISE on Windows 11
PS C:\Users\malcolm> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.22000.282
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.22000.282
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
I need to pass a class property as reference in PowerShell.
For example like this:
Function Add-Five
{
param([ref]$value)
$value.Value+=5
}
$a = 5
Add-Five -value ([ref]$a)
Write-Host "A = $a"
As expected this outputs 10
However, if I do this:
class MyClass
{
$a
}
Function Add-Five
{
param([ref]$value)
$value.Value+=5
}
$class = New-Object MyClass
$class.a = 5
Add-Five -value ([ref]$class.a)
Write-Host "A = $($class.a)"
The output is 5.
As a workaround I can do this :
Function Add-FiveSpecial
{
param($className,$propertyName)
(Get-Variable -Name $className).Value.$propertyName += 5
}
Add-FiveSpecial -className "class" -propertyName "a"
Write-Host "A = $($class.a)"
Which outputs 10
Is there a way to get [ref] to work with class properties?