【问题标题】:String variable in an Active Directory path not workingActive Directory 路径中的字符串变量不起作用
【发布时间】:2015-12-15 13:10:44
【问题描述】:

我正在编写一个 PowerShell 脚本来创建一个新的 Active Directory 组并自动将其放入正确的 OU 中,具体取决于用户所在的部门。脚本从 Active Directory 中的用户那里获取部门,然后需要使用它作为活动目录中 OU 的名称。当我不使用 AD 路径中的变量时,此脚本有效。

[string]$department = Get-ADUser -identity johndoe -properties department | Select department

New-ADGroup -Name NewADGroup -GroupScope Global -path “OU=($department),OU=SubDepartment,OU=MainDepartment,DC=OrgName”

但是,当我尝试使用上述变量 $department 时,出现以下错误:

New-ADGroup : The object name has bad syntax
At C:\Users\JohnDoe\Desktop\CreateNewGroup.ps1:7 char:1
+ New-ADGroup -Name NewADGroup -GroupScope Global -path
"OU=($department ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo          : NotSpecified: (CN=NewADGroup,DC=OrgName
   :String) [New-ADGroup], ADException
  + FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirec
   tory.Management.Commands.NewADGroup

如何在 Active Directory 路径中调用该变量?

【问题讨论】:

  • ($department) 应该是 $($department) 或只是 $department

标签: powershell active-directory


【解决方案1】:

您实际上有 2 个问题是常见的陷阱。

  1. $department 本身不是字符串,而是具有 deparment 属性的对象的字符串表示形式。您需要将字符串断开。这就是-ExpandProperty 的用途。如果您现在查看department,您会看到类似@{Department="IT"}

  2. 您还遇到了字符串中的变量扩展问题。

[string]$department = Get-ADUser -identity johndoe -properties department | Select -Expandproperty department

New-ADGroup -Name NewADGroup -GroupScope Global -path "OU=$department,OU=SubDepartment,OU=MainDepartment,DC=OrgName"

如果您不调用属性或复杂对象,则删除括号就足够了。否则,您可以只使用子表达式"OU=$($department),OU=SubDepartment,OU=MainDepartment,DC=OrgName"。如果没有 $ 符号,括号被认为是字符串的一部分。

【讨论】:

    【解决方案2】:

    尝试在左括号前加一个美元符号,如下所示: "OU=$($department)..."

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-07
      • 2014-01-20
      • 2013-01-08
      • 2019-06-16
      • 1970-01-01
      • 2012-12-15
      • 2021-05-20
      • 2011-11-12
      相关资源
      最近更新 更多