由于格式不正确,将表导出为文件两次

时间:2016-01-23 16:54:38

标签: powershell powershell-v3.0

我正在使用此代码:

Function Main
{
    $domain = "LDAP://www.example.com"
    $outfile = 'C:\Scripts\Tests\usersDump.csv'
    $properties = "SamAccountName", "lastLogonTimestamp", "AccountExpires", "FirstName", "LastName", "distinguishedName", "employeeNumber", "employeeID", "description", "extensionattribute8", "userAccountControl"


    Write-Host "Searching AD..."
    $dn = New-Object System.DirectoryServices.DirectoryEntry($domain)
    $ds = New-Object System.DirectoryServices.DirectorySearcher($dn)
    $ds.Filter = '(&(objectCategory=User)(samAccountType:1.2.840.113556.1.4.803:=805306368))'
    $ds.PageSize=1000
    $ds.PropertiesToLoad.AddRange($properties)
    $list = $ds.FindAll()
    Write-Host "Complete"


    # The AD results are converted to an array of hashtables.
    Write-Host "Exporting User Attributes to table..."
    $table = @()
    $garbageCounter = 0
    foreach($item in $list) {
        $hash = @{}
        foreach($name in $properties){
            if ($item.Properties[$name]) {
                $hash.$name = $item.Properties[$name][0]
            } else {
                $hash.$name = $null
            }
        }
        $table += New-Object PSObject -Property $hash
        $garbageCounter++
        if ($garbageCounter -eq 1000)
        {
            [System.GC]::Collect()
            $garbageCounter = 0
        }
    }
    [System.GC]::Collect()
    Write-Host "Complete."

    $listOfBadDateValues = '9223372036854775807', '9223372036854770000', '0'
    $maxDateValue = '12/31/1600 5:00 PM'

    Write-Host "fixing table values for `"lastLogonTimestamp`" and `"AccountExpires`""
    $tableFixedValues = $table | % { 
        if ($_.lastLogonTimestamp) {
            $_.lastLogonTimestamp = ([datetime]::FromFileTime($_.lastLogonTimestamp)).ToString('g')
        }; if (($_.AccountExpires) -and ($listOfBadDateValues -contains $_.AccountExpires)) {
            $_.AccountExpires = $null
        } else {
            if (([datetime]::FromFileTime($_.AccountExpires)).ToString('g') -eq $maxDateValue) {
                $_.AccountExpires = $null
            } Else {
                $_.AccountExpires = ([datetime]::FromFileTime($_.AccountExpires)).ToString('g')
            }
        };$_}
    Write-Host "Complete"

    Write-Host "Exporting table to csv file $outfile"
    $tableFixedValues | Export-Csv $outfile –encoding "unicode" -NoTypeInformation -Force
    Write-Host "Complete"

    Write-Host "Done."
}

Main

问题是文件已写入所以一切都在1列中。为了在自己的列中创建属性,我使用此代码...

Write-Host "Converting $outfile to csv file $OutputResultsFile"
$outFileFixed = 'C:\Scripts\Tests\usersDumpFixed.csv'
Import-Csv $outfile | Export-Csv $outFileFixed -NoTypeInformation -Force
Write-Host "Complete"

有没有办法可以做到这一点而无需再次打开它?

1 个答案:

答案 0 :(得分:1)

从Export-csv中删除-Encoding Unicode参数,然后它不会在一列中