从变量中提取单个对象/属性(Powershell)

时间:2016-02-23 14:21:41

标签: xml powershell variables

我目前正在为变量中的多个用户存储AD用户属性。然后,我需要能够提取单个属性以提供给XML文件。现在我有些卡住,因为我不知道我是否可以提取个人财产。我知道代码,因为我试图在XML中的每个变量中填充每个用户的所有属性,但是想要显示思考过程。有没有办法调用各个属性?

$base = 'ou=my users,dc=mydomain,dc=com'
$date = (Get-Date).AddDays(-1)

$people = get-aduser -SearchBase $base -Filter {whencreated -gt $date} -Properties * | select name,emailaddress,title -OutVariable results

foreach ($result in $results){

$name = $results.name
$email = $results.email
$title = $results.title

$xmlfile=[xml] @"
<users><user><name>$name</name><email>$email</email><title>$title</title</user></users>
"@

2 个答案:

答案 0 :(得分:0)

这样做会容易得多:

$base = 'ou=my users,dc=mydomain,dc=com'
$date = (Get-Date).AddDays(-1)

$people = get-aduser -SearchBase $base -Filter {whencreated -gt $date} -Properties * | select name,emailaddress,title -OutVariable results

$xmlfile= $people | ConvertTo-Xml

无论如何,你的foreach部分也是错误的,你正在调用不存在的foreach ($result in $results),你的数组名为$people,你的email定义也是错误的,应该是{{1 }}

emailaddress

获取InnerXml:

foreach ($result in $people){

$name = $result.name
$email = $result.emailaddress
$title = $result.title

[xml]$xmlfile...
}

答案 1 :(得分:0)

我试图在这里尽可能地找到一种方法来使用xml进程和方法,以便适应创建此文件的正确方法。希望有人有更好的方法,但它会得到我认为你想要的结果。

# Base XML
$xml = [xml]@"
<users>
</users>
"@

# Template for creating nodes. 
$userTemplate = @"
<user>
    <name>{0}</name>
    <email>{1}</email>
    <title>{2}</title>
</user>
"@

$base = 'ou=my users,dc=mydomain,dc=com'
$date = (Get-Date).AddDays(-1)

Get-ADUser -SearchBase $base -Filter {whencreated -gt $date} -Properties emailaddress,title | select name,emailaddress,title| ForEach-Object{
    # Create and append a child for each user
    $child = $xml.ImportNode(([xml]($userTemplate -f $_.Name,$_.emailaddress,$_.title)).DocumentElement,$true)
    $xml.documentelement.AppendChild($child) | Out-Null
}

# Should use your own path and a variable here. 
$xml.Save("c:\temp\text.xml")

您保存的文件现在应如下所示:

<users>
  <user>
    <name>Matt</name>
    <email>address@mail.com</email>
    <title>Awesome</title>
  </user>
  <user>
    <name>Michael</name>
    <email>address2@mail.com</email>
    <title>Guy</title>
  </user>
</users>