当我启动一个PSSession里面Powershell函数返回值的变化

我试图编写一个简单的函数,当我的Exchange服务器上存在一个邮箱时返回$ true,当它不存在时返回$ false。 该函数本身启动PSSesssion到Exchange服务器:

function Check-MyMailbox { Param ( [Parameter(Mandatory=$true)] [string] $Identity ) $ExchangeOnPremSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://exchange.domain.loc/PowerShell/ -Credential $MyCredentials -Authentication Kerberos Import-PSSession -Session $ExchangeOnPremSession -Verbose -AllowClobber -DisableNameChecking -ErrorAction Stop $CheckUserMailbox = Get-Mailbox -Identity $Identity -ErrorAction SilentlyContinue if ($CheckUserMailbox) { $ReturnUserMailbox = $true } else { $ReturnUserMailbox = $false } Write-Host 'My Variable In Function:' $ReturnUserMailbox return $ReturnUserMailbox } $MyVariableInScript = Check-MyMailbox -Identity [email protected] Write-Host 'My Variable In Script:' $MyVariableInScript 

我获得的输出是:

 MyVariableInFunction: True MyVariableInScript: tmp_kku2aeae.wyu True 

我同意由函数生成的“真”输出(其types为布尔 ),但我真的不明白为什么脚本级别的variables也具有“tmp_xxx”值,此外,它是一个数组 。 我花了一些时间在这里,我意识到删除Import-PSSession行 (并保持PSSession从脚本以前的执行),输出如预期:

 MyVariableInFunction: True MyVariableInScript: True 

我完全无法弄清楚它发生的原因。 有人可以build议吗?

从这里 ,Import-PSSession输出一个System.Management.Automation.PSModuleInfo对象。

要修复你的function,添加| Out-Null | Out-NullImport-PSSession行的末尾