2014-10-10 67 views
1

我有一個很好的腳本,但我只想導出滿足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 

回答

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循環中的任何標準的項目。

+0

像魅力丹一樣工作。感謝你的協助。 – NobleMan 2014-10-10 19:07:21