如何将值作为变量传递到带有 -identity 的 get-mailbox

问题描述

我有以下 powershell 脚本

$mailBox = "testmail"

$i=invoke-command -Session $session -ScriptBlock { get-mailBox -identity $mailBox  | get-mailBoxpermission | Select-Object Identity,User,AccessRights,ExtendedRights } -HideComputerName  | Where-Object {($_.User -like '*1023') -and ($_.AccessRights -like 'FullAccess*')}
write-host "The I values :"$i <br>

但我收到以下错误

  +  get-mailBox -identity $mailBox | get-mailBoxpermission | Select-Obje ...
+                        ~~~~~~~~
A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: $PSCulture,$PSUICulture,$true,$false,$null.

我在 get-mailBox 上测试了几种语法组合,其中包括以下内容

 get-mailBox -identity '$mailBox'
 get-mailBox -identity "'$mailBox'" 

他们都没有为我工作。如果我使用以下命令,我就能得到我想要的结果
 $i=invoke-command -Session $session -ScriptBlock { get-mailBox -identity testmail  | get-mailBoxpermission | Select-Object Identity,ExtendedRights } -HideComputerName  | Where-Object {($_.User -like '*1023') -and ($_.AccessRights -like 'FullAccess*')} <br>

但是我不能这样做,因为交换服务器中没有一个邮箱,所以我必须让它更灵活

解决方法

通过在 ScriptBlock 中将 $mailbox 更改为 $using:mailbox,您的 $using 范围。