仅导出符合条件的计算机

时间:2014-10-10 17:52:34

标签: powershell

我有一个很好用的脚本,但我想只导出符合foreach语句中三个条件之一的机器。现在它导出所有机器,我必须在excel中手动清理。

#Create an LDAP searcher object and pass in the DN of the domain we wish to query
$Searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]"LDAP://DC=ten,DC=thomsonreuters,DC=com")

#Pass in the ceriteria we are searching for.
#In this case we're looking for computers that are enabled and running Windows 7

$Searcher.Filter = "(&(objectCategory=computer)(objectClass=computer)(!UserAccountControl:1.2.840.113556.1.4.803:=2)(operatingSystem=Windows 7*))"

$Searcher.PageSize = 100000

# Populate General Sheet(1) with information

$results = $Searcher.Findall()

$results | ForEach-Object { $_.GetDirectoryEntry() } |
select @{ n = 'CN'; e = { ($_.CN) } },
@{ n = 'DistinguishedName'; e = { $_.DistinguishedName } },
@{ n = 'extensionattribute7'; e = { $_.extensionattribute7 } },
@{ n = 'extensionattribute1'; e = { $_.extensionattribute1 } },
@{ n = 'NewComputerName'; e = { 'Filler' } } |
Export-Csv 'C:\temp\Windows7_Only.csv' -NoType -Force

$csv = Import-Csv -Path "c:\Temp\Windows7_Only.csv"
foreach ($row in $csv)
{
   if (($row.CN -notmatch '^U\d{7}') -and ($row.DistinguishedName -like "*Laptops*") -and ($row.extensionattribute7 -match '^U\d{7}$') -and ($row.CN -notmatch '\d{3}'))
   {
          $row.NewComputerName = $row.extensionattribute7 + "-TPL-ZZ"
   }
   elseif (($row.CN -notmatch '^U\d{7}') -and ($row.DistinguishedName -like "*Desktops*") -and ($row.extensionattribute7 -match '^U\d{7}$') -and ($row.CN -notmatch '\d{3}'))
   {
          $row.NewComputerName = $row.extensionattribute7 + "-TPD-ZZ"
   }

   elseif (($row.CN -notmatch '^U\d{7}') -and ($row.DistinguishedName -like "*Virtual*") -and ($row.extensionattribute7 -match '^U\d{7}$') -and ($row.CN -notmatch '\d{3}'))
   {
          $row.NewComputerName = $row.extensionattribute7 + "-TPV-ZZ"
   }


  }
 $csv | export-csv c:\temp\fixed.csv -NoTypeInformation -Force

1 个答案:

答案 0 :(得分:0)

试试这个:

$csv = $csv | where { ($_.CN -notmatch '^U\d{7}') -and ($_.CN -notmatch '\d{3}') -and ($_.extensionattribute7 -match '^U\d{7}$') -and (($_.DistinguishedName -like "*Laptops*") -or ($_.DistinguishedName -like "*Desktops*") -or ($_.DistinguishedName -like "*Virtual*")) }

在最后一行之前。它应该过滤掉那些没有达到foreach循环中任何标准的