I'm trying to create a generic connection (and disconnection) function for my Lotus Notes COM object scripts, so I don't need to repeat code.
To avoid using global variables I wanted to pass the reference to the "would-be" COM object variable, and utilize it, however I'm finding that it stays as null, despite connecting correctly inside the function.
I'm sure my understanding of how [REF] works in PoSh is what's causing this issue.
[EDIT] - I assume it's the New-Object call causing the variable within the function to no longer be referencing the input variable as it now requires a different address in memory? Is there a way to achieve this / a better practise ?
Below is a simplified snippet of my code:
function Connect-NotesSession {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
$obj,
[Parameter(Mandatory=$false)]
[System.Security.SecureString]$pw
)
try {
Write-Host "Initializing Lotus Notes COM Object... " -NoNewline
$obj = New-Object -ComObject Lotus.NotesSession
if($pw) {
$obj.Initialize([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw)))
} else {
$obj.Initialize()
}
Write-Host "Connected." -ForegroundColor Green
} catch {
Write-Host "Error! Failed to connect" -ForegroundColor Red
}
}
## Main
$notes = $null
$p = Read-Host -AsSecureString
Connect-NotesSession [REF]$notes $p
$notes.GetType()
Output:
Initializing Lotus Notes COM Object... Connected.
You cannot call a method on a null-valued expression.
At line:31 char:1
+ $notes.GetType()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Expected output:
PS C:\> $notes.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False __ComObject System.MarshalByRefObject