我在尝试创建“子查询”时遇到了问题。我是Powershell的新手,但对SQL有一些经验,因此我遇到的问题。所以我在文件服务器中查询打印作业,我试图将用户名关联回AD,以获得每个用户的部门。最终目标是检索数据以分析每个部门的打印机使用情况,以便正确分配资金。我在下面的脚本输出每个打印作业的用户名:
$location4='\\roch-fs02\c$\Powershell_Printing_Logs\users.txt'
$pattern = '"(.+)","Document (.+), (.+) owned by (.+) on (.+) was printed on (.+) through port (.+). Size in bytes: (.+). Pages printed: ([^&])'
Select-String -Pattern $pattern -Path $location|ForEach {
new-object psobject -Property @{
TimeCreated=$_.matches[0].Groups[1]
DocumentNumber=$_.Matches[0].Groups[2]
Document=$_.Matches[0].Groups[3]
User=$_.Matches[0].Groups[4]
Machine=$_.Matches[0].Groups[5]
Printer=$_.Matches[0].Groups[6]
Port=$_.Matches[0].Groups[7]
Size=$_.Matches[0].Groups[8]
Pages=$_.Matches[0].Groups[9]
}
}|where {$_.printer -notmatch 'ne' }|
select user |
out-file $location4
这段代码输出每个用户的部门:
$users=Get-Content $location4 |select -Skip 3
$department=for ($i=0 ;$i -le $users.Length – 20; $i++)
{Get-qADUser $users[$i]|select department,samaccountname}
有没有办法在同一个.txt文件中获取这两个输出?感谢。
答案 0 :(得分:0)
假设打印日志中的用户是samaccountnames,我会构建一个用户和部门的哈希表:
$Department = @{}
$users=Get-Content $location4 |select -Skip 3
$department=for ($i=0 ;$i -le $users.Length – 20; $i++)
{Get-qADUser $users[$i]|select department,samaccountname} |
foreach {$Department[$_.samaccountname] = $_.department}
然后使用它在Department哈希表中使用user / samaccountname在对象中插入Department属性:
$location4='\\roch-fs02\c$\Powershell_Printing_Logs\users.txt'
$pattern = '"(.+)","Document (.+), (.+) owned by (.+) on (.+) was printed on (.+) through port (.+). Size in bytes: (.+). Pages printed: ([^&])'
Select-String -Pattern $pattern -Path $location|ForEach {
new-object psobject -Property @{
TimeCreated=$_.matches[0].Groups[1]
DocumentNumber=$_.Matches[0].Groups[2]
Document=$_.Matches[0].Groups[3]
User=$_.Matches[0].Groups[4]
Department = $Department[$_.Matches[0].Groups[4]]
Machine=$_.Matches[0].Groups[5]
Printer=$_.Matches[0].Groups[6]
Port=$_.Matches[0].Groups[7]
Size=$_.Matches[0].Groups[8]
Pages=$_.Matches[0].Groups[9]
}
}|where {$_.printer -notmatch 'ne' }|
select user |
out-file $location4