简体   繁体   English

在Get-AdUser中使用哈希表变量

[英]Using hash table variable in Get-AdUser

Consider the following code fragment 考虑以下代码片段

$User = @{Username = "fred.bloggs"}
$Username = $User.Username
Get-AdUser -Filter {SamAccountName -eq $Username}               # this works
Get-AdUser -Filter {SamAccountName -eq $User.Username}          # this throws an error

The first Get-User works but the second fails with: 第一个Get-User有效,但第二个失败,并具有:

Get-AdUser : Property: 'Username' not found in object of type: 'System.Collections.Hashtable'. Get-AdUser:属性:在类型为“ System.Collections.Hashtable”的对象中找不到“用户名”。

I'm aware of PowerShell's parsing quirks with objects and left-to-right parsing and would normally wrap this in $($User.Username) but that doesn't work either. 我知道PowerShell的对象解析和从左到右解析的怪癖,通常会将其包装在$($ User.Username)中,但这也不起作用。

I know the answer is simple! 我知道答案很简单!

Since -Filter is looking for a System.String , you can get around the parsing issue by using double quotes instead of a script block: 由于-Filter在寻找System.String ,因此可以通过使用双引号而不是脚本块来解决解析问题:

Get-ADUser -Filter "SamAccountName -eq '$($User.Username)'"

Get-ADUser will convert any script block passed to -Filter to a string for evaluation, so it can be helpful to use a string in the first place. Get-ADUser会将传递给-Filter任何脚本块转换为字符串以进行评估,因此首先使用字符串会有所帮助。

Sadly i cannot tell you why it fails but this could be a workaround for you: 遗憾的是,我无法告诉您它为什么失败,但这可能是您的一种解决方法:

$filter = [scriptblock]::create("SamAccountName -eq $($User.Username)")
Get-AdUser -filter $filter

If you find out the reason for the behaviour you experienced i would be happy to hear about it :) 如果您找到您所经历的行为的原因,我很乐意听到:)

Regards 问候

Update: 更新:

The probable reason this happens is because -Filter expects a String, if given the expression inside of {} it will interpret it as Advanced Filter, which do not support function invocation and stuff like this. 发生这种情况的可能原因是-Filter需要一个String,如果给定{}的表达式,它将把它解释为Advanced Filter,它不支持函数调用和类似的东西。 Source: MSDN (Thanks Kohlbrr) 来源: MSDN (感谢Kohlbrr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM