【问题标题】:PowerShell - Use variable in another cmdletPowerShell - 在另一个 cmdlet 中使用变量
【发布时间】:2015-06-21 07:05:55
【问题描述】:

我想用 AD 用户的办公室电话号码创建一个变量,并在另一个 cmdlet 中使用这个变量。

$a = Get-AdUser -Filter "name -eq 'User1'" -Properties OfficePhone | FT OfficePhone | Out-String
Set-ADUser User2 -EmailAddress $a

我试过这个,但它不起作用。有人可以帮我吗?

最好的问候

【问题讨论】:

    标签: string variables powershell active-directory


    【解决方案1】:
    $a = (Get-ADuser User1 -Properties OfficePhone).OfficePhone
    Set-ADUser User2 -EmailAddress $a
    

    Get-ADUser 的 -Properties 参数告诉 cmdlet 包含您指定的属性除了它已经包含的其他属性,例如 DistinguishedName、Enabled、GivenName 等。

    因此,您必须通过将 cmdlet 括在括号中并使用句点后跟属性名称来指定要保存到 $a 变量的属性。这实际上与以下内容相同:

    $a = Get-ADUser User1 -Properties OfficePhone
    $b = $a.OfficePhone
    Set-ADUser User2 -EmailAddress $b
    

    【讨论】:

      【解决方案2】:

      您要选择 User1 对象的特定属性,在本例中为 OfficePhone。请尝试并告诉我它是否有效,因为我目前没有安装 Active Directory 模块。

      $a = Get-AdUser -Filter "name -eq 'User1'" -Properties OfficePhone | Select-Object OfficePhone
      Set-ADUser User2 -EmailAddress $a
      

      【讨论】:

      • 感谢您的回复。我试过你的代码,但它也不起作用。我收到以下错误。 Set-ADUser : "System.Object[]" kann nicht in den Typ "System.String" konvertiert werden, der für den 参数 "EmailAddress" erforderlich ist。 Die angegebene Methode wird nicht unterstützt。在 Zeile:2 Zeichen:37 + Set-ADUser User2 -EmailAddress $a + ~~ + CategoryInfo : InvalidArgument: (:) [Set-ADUser], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.SetADUser跨度>
      • 好的,所以它说 $a 是一个对象,因此无法将其转换为 -EmailAddress 参数所需的字符串。试试:Set-ADUser User2 -EmailAddress $a.OfficePhone
      • 你能用#注释第二行并写$a | Format-Table -Autosize 在第三行。这将有望提供存储在 $a 中的属性和值。还要注释掉 Select-Object OfficePhone,所以该行显示为 $a = ...。 # |选择对象等...
      • 现在我从 User1 得到:DistinguishedName、Enabled、GivenName、Name、ObjectClass、ObjectGUID 和 OfficePhone。
      • 你能做到$b = $a.OfficePhone $b | Format-Table -Autosize 我感觉OfficePhone属性是一个包含其他属性的对象。
      猜你喜欢
      • 1970-01-01
      • 2016-06-27
      • 2021-11-21
      • 2010-12-15
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多