我正在尝试为我的Lotus Notes COM对象脚本创建一个通用的连接(和断开连接)功能,所以我不需要重复代码。
为了避免使用全局变量,我希望将引用传递给“可能的” COM对象变量,并加以利用,但是尽管在函数内部正确连接,但我发现它仍为null。
我确定对PoC中[REF]
的工作方式的理解是导致此问题的原因。
[编辑]-我假设这是New-Object
调用,导致函数内的变量不再引用输入变量,因为它现在需要内存中的其他地址?有没有办法实现这一点/更好的做法?
下面是我的代码的简化片段:
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()
输出:
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
预期输出:
PS C:\> $notes.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False __ComObject System.MarshalByRefObject
我不是100%熟悉Lotus Notes的东西,但是在运行函数之前,您似乎没有(1)$ Notes对象。然后在函数(2)中调用它。
$ notes = $ null
$ p =读取主机-AsSecureString
Connect-NotesSession [REF] $ notes $ p
$ notes.GetType()
尝试将对象初始化移动到函数调用的上方。
## Main
$notes = $null
$notes = New-Object -ComObject Lotus.NotesSession
$p = Read-Host -AsSecureString
Connect-NotesSession [REF]$notes $p
$notes.GetType()
然后将其从try语句中删除。另外,创建对象时,可能不需要将其归零,因为它会覆盖先前值中的任何内容。
干杯!