开发者

Unable to run Get-CASMailbox in Powershell using -filter clause with a pipeline variable

I'm having some trouble with the syntax of Exchange cmdlet Get-CASMailbox.

I'm running in a 2007 environment and I've tested in PowerGUI 2.4, 3.0, and the PS ISE 2.0.

Sample code for demonstration purposes:

[String[]] $MailServerList = @('IP-0A207B07')

$MailServerList | %{            
Get-CASMailbox -ResultSize:10 -Filter {ServerName -eq $_}   
}

In this example there is only a single mailserver. During the call to Get-CASMailbox the pipeline operator $_ is IP-0A207B07 and $_.GetType() confirms 开发者_运维知识库it is a string. If this line runs I get the following error:


Get-CASMailbox : Cannot bind parameter 'Filter' to the target. Exception setting "Filter": "Unable to cast object of type 'System.Management.Automa tion.PSObject' to type 'System.String'." At C:\Users\erawlins\Desktop\MailboxFilterBug.ps1:7 char:38 + Get-CASMailbox -ResultSize:10 -Filter <<<< {ServerName -eq $_} + CategoryInfo : WriteError: (:) [Get-CASMailbox], ParameterBindingException + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.Exchange.Management.RecipientTasks.GetCASMailbox


I'm really confused by this. I've tried every syntax I could find and in every case attempting to use $_ throws the same error. If I just any other variable, such as $test=$_, and substitute that in the query it works fine.

Thinking there could be some problems with using the pipeline operator (maybe once Get-CASMailbox starts running something else is in $_) I also tried using an object property (which is part of the original code). The following two lines were added before the get-casmailbox call

$ServerInfo = "" | Select-Object Name
$ServerInfo.Name = $_.ToString()

Get-CASMailbox -ResultSize:10 -Filter {ServerName -eq $ServerInfo.Name}

Fails as well, same error message. So I'm really confused why taking $_ or $ServerInfo.Name and assigning it to $test, then using $test works fine but the first two methods throw an error. It seems to me that each of these should work as they're all strings. What's the difference?


Try this:

$MailServerList | Foreach-Object { Get-CASMailbox -Filter "ServerName -eq  '$_'" }


You are passing a scriptblock to the filter parameter and you are referencing an automatic variable ($). By the time the scriptblock gets evaluated, it could be inside some other code that is defining $. Always be careful while using automatic variables with nested scopes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜