Powershell V3+:
I'm writing a module providing various Cmdlets suiteable for interactive use. What I try to achive is, that variables (objects) are getting destructed without having the user to use remove-variable.
Example:
$object = open-object -someparam
$object # returns something
close-object -reference $object
$object # is not defined anymore - similiar to remove-variable
I could not manage to get the above working, alternative approaches like the below have also failed.
$x = New-Object -TypeName PSCustomObject
$x | Add-Member -type NoteProperty -Name Justsomedata -Value Nomeaning
$x | Add-Member -type ScriptMethod -Name killme -Value { $this = $null }
$x
$x.killme()
$x # :-(
Any suggestions? I want to prevent that there are variables in the users runspace that are not useable anymore.
答案 0 :(得分:1)
最好以一种明确不应再使用的方式更改对象的状态。例如,您可以拥有一个名为IsOpen
或$references = Get-Variable | Where-Object { $this -eq $_.Value}
$references | ForEach-Object { Remove-Variable $_.Name }
的属性,然后如果他们尝试使用它就可以抛出异常。最好避免为用户实际删除变量,以防他们想要引用该对象,即使它不再有效。
但是,如果你真的想这样做,你可以试试这个:
department.job_titles << JobTitle.find_or_create_by(title: title)