gpt4 book ai didi

powershell - 在Get-ADUser过滤器参数中传递字符串会导致错误-在pscustomobject中找不到属性

转载 作者:行者123 更新时间:2023-12-03 00:49:08 25 4
gpt4 key购买 nike

我正在尝试创建一个新的Active Directory用户,但首先我使用Get-ADUser验证该用户已经不存在。
我从人力资源部门导入用户数据并构建自定义属性:

$newUsers = Import-Csv $csvFile |
Select-Object -Property @{n='EmpNum';e={$_.'Employee Number'}},
@{n='UPN';e={$_.'Email Address'}},
@{n='Alias';e={$_.'Email Address'.Split("@")[0]}} #### etc

当我遍历CSV文件中的对象时,我使用UPN属性在Active Directory中搜索用户:
foreach ($newUser in $newUsers) {
$exists = Get-ADUser -Filter {UserPrincipalName -eq $newUser.UPN} -Properties * -Server $adServer -Credential $adCred
...
}

筛选器导致错误:

Get-ADUser : Property: 'UPN' not found in object of type:
'System.Management.Automation.PSCustomObject'. At
C:\Users\bphillips.NEWHOPEOFIN\Dropbox\Powershell\NewHire\AddNewDSP.ps1:50
char:15
+ $exists = Get-ADUser -Filter {UserPrincipalName -eq $newUser.UPN} -Propertie ...

我尝试这样做:-Filter {UserPrincipalName -eq $(“$ newUser.UPN”),但这没有帮助;我收到另一个错误

Get-ADUser : Cannot process argument because the value of argument
"path" is not valid. Change the value of the "path" argument and run
the operation again. At
C:\Users\bphillips.NEWHOPEOFIN\Dropbox\Powershell\NewHire\AddNewDSP.ps1:50
char:15
+ $exists = Get-ADUser -Filter {UserPrincipalName -eq $("$newUser.UPN")} -Prop ...
$newUser是一个字符串,所以我不明白为什么会导致问题。像“test@ourcompany.com”这样的UserPrincipalName进行硬编码有效,但是 $newUser.UPN无法使用。**

PS C:\> $newUser.UPN.GetType()

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object



PS C:\> $newUser.UPN | gm

TypeName: System.String
$newUser.UPN包含有效的字符串值

PS C:\> $newUser.UPN
ypope@ourcompany.net

我该怎么做才能将 $newUser.UPN识别为filter参数的字符串?我不明白发生了什么事?

最佳答案

BNF for filter query strings不允许将表达式作为比较中的第二个操作数,仅允许值(强调我的):

Syntax:
The following syntax uses Backus-Naur form to show how to use the PowerShell Expression Language for this parameter.

<filter> ::= "{" <FilterComponentList> "}"
<FilterComponentList> ::= <FilterComponent> | <FilterComponent> <JoinOperator> <FilterComponent> | <NotOperator> <FilterComponent>
<FilterComponent> ::= <attr> <FilterOperator> <value> | "(" <FilterComponent> ")"
<FilterOperator> ::= "-eq" | "-le" | "-ge" | "-ne" | "-lt" | "-gt"| "-approx" | "-bor" | "-band" | "-recursivematch" | "-like" | "-notlike"
<JoinOperator> ::= "-and" | "-or"
<NotOperator> ::= "-not"
<attr> ::= <PropertyName> | <LDAPDisplayName of the attribute>
<value>::= <compare this value with an <attr> by using the specified <FilterOperator>>



将要比较的属性的值放在变量中,然后在比较中使用该变量。您可能还想将过滤器定义为实际的字符串,如果只是为了清楚起见(尽管过滤器看起来不是脚本块)。
$upn = $newUser.UPN
$exists = Get-ADUser -Filter "UserPrincipalName -eq '$upn'" ...

关于powershell - 在Get-ADUser过滤器参数中传递字符串会导致错误-在pscustomobject中找不到属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34028164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com