运行Powershell脚本时排除空白结果

时间:2013-12-31 10:14:26

标签: powershell

我正在尝试创建一个Powershell脚本,该脚本根据存储在Active Directory中的信息创建电话目录。

我创建了以下脚本,它按预期运行;但它还包括没有相关电话号码的员工姓名。

有没有办法在脚本中添加过滤器,以便在没有电话号码时排除用户详细信息?

import-module activedirectory

$d = Get-Date 
    "Date: " +$d.ToShortDateString()
    "Time: " +$d.ToShortTimeString()

$a = "<style>"
$a = $a + "BODY{background-color:blue;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 10px;border-style: solid;border-color: black;background-color:thistle}"
$a = $a + "TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;background-color:PaleGoldenrod}"
$a = $a + "</style>"
$Pre = "<h2>Phone Directory</h2>"
$Post = "<br><br>Time / Date Generated $d"


Get-aduser -filter * -SearchBase 'OU=Test, DC=Domain, DC=net' -Properties sn, GivenName, OfficePhone, Department | Select-Object sn, GivenName, OfficePhone, Department | Sort-Object sn | ConvertTo-Html -head $a -PreContent $Pre -PostContent $Post | Out-File c:\temp\dir.html

Invoke-Expression C:\Temp\dir.html

非常感谢,

Peter D

2 个答案:

答案 0 :(得分:0)

减少流水线应该会有所帮助。获取所有用户的列表并在以后过滤。

# Save all the users into an array:
$users = Get-aduser -filter * -SearchBase 'OU=Test, DC=Domain, DC=net' -Properties sn, GivenName, OfficePhone, Department | Select-Object sn, GivenName, OfficePhone, Department
# Look for users that have at least one digit in their officephone. Adjust as needed
$usersWithPhones = $users | ? { $_.OfficePhone -match "\d+"}
# Pass the filtered results along the pipeline
$usersWithPhones | Sort-Object sn | ConvertTo-Html -head $a -PreContent $Pre -PostContent $Post | Out-File c:\temp\dir.html

您可以将过滤语句添加到管道中。我不会。试图用oneliner做很多事情的脚本的维护是一个令人头疼的问题。无论如何,性能并不是脚本编写的问题,因此您应该努力获得易于阅读,易于维护的解决方案。

答案 1 :(得分:0)

尽可能使用早期过滤,并帮自己一个忙,并在管道上折叠代码,以便于阅读和维护:

Get-ADUser -filter "OfficePhone -like '*'" -SearchBase 'OU=Test, DC=Domain, DC=net' -Properties sn, GivenName, OfficePhone, Department |
 Select-Object sn, GivenName, OfficePhone, Department |
 Sort-Object sn |
 ConvertTo-Html -head $a -PreContent $Pre -PostContent $Post |
 Out-File c:\temp\dir.html