Powershell variable export-CSV cache?

为君一笑 提交于 2019-12-02 17:30:34

问题


I am working on a script by Richard L. Mueller (http://www.rlmueller.net/PowerShell/PSLastLogon.txt)

Trap {"Error: $_"; Break;}

$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"

$Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
$Searcher.PropertiesToLoad.Add("samAccountName") > $Null
$Searcher.PropertiesToLoad.Add("lastLogon") > $Null

$arrUsers = @{}


ForEach ($DC In $D.DomainControllers)
{
$Server = $DC.Name
$Searcher.SearchRoot = "LDAP://$Server/" + $Domain.distinguishedName
$Results = $Searcher.FindAll()
ForEach ($Result In $Results)
{
    $DN = $Result.Properties.Item("samAccountName")
    $LL = $Result.Properties.Item("lastLogon")
    If ($LL.Count -eq 0)
    {
        $Last = [DateTime]0
    }
    Else
    {
        $Last = [DateTime]$LL.Item(0)
    }
    If ($Last -eq 0)
    {
        $LastLogon = $Last.AddYears(1600)
    }
    Else
    {
        $LastLogon = $Last.AddYears(1600).ToLocalTime()
    }
    If ($arrUsers.ContainsKey("$DN"))
    {
        If ($LastLogon -gt $arrUsers["$DN"])
        {
            $arrUsers["$DN"] = $LastLogon
        }
    }
    Else
    {
        $arrUsers.Add("$DN", $LastLogon)
    }
}
}


$inactiveusers = @()
$Users = $arrUsers.Keys
ForEach ($DN In $Users)
{
$Date = $arrUsers["$DN"]
"$DN;$Date"
$inactiveusers += $DN
$inactiveusers += $Date
$inactiveusers | export-csv "c:\test.csv"
}

Thinking to store the info to another array, I added the those line start with $inactiveusers (total of 4 lines). However the CSV exported does not gives me the correct result, instead of listing the user samAccountName & lastlogon, the length of the samAccountName is returned.

Further to this, since then I cannot export the same variable in my another script even the script is just simple as:

$inactiveusers = "Test"
$inactiveusers | Export-Csv c:\test.csv
write-host $inactiveusers

The CSV exported still give me the length of the string "Test", however the write-host result is correct. I tried remove-variable, logoff & login back but both without luck. I am not sure where the cache stored. I can work on the script later on but first I want to able to export this variable to CSV in another script.
appreciate anyone can give me some hint


回答1:


The Export-Csv cmdlet does not export strings. It exports the properties of objects as fields of the output CSV file. In case of string objects, the exported property is the length of the string. You need to transform the hashtable into a list of custom objects to make the export work as you expect:

$arrUsers.Keys | % {
  New-Object -Type PSObject -Property @{
    'sAMAccountName' = $_
    'lastLogon'      = $arrUsers[$_]
  }
} | Export-Csv 'C:\test.csv' -NoType

Also the manual date calculation could be replaced with the FromFileTime() method:

$lastLogon = [DateTime]::FromFileTime($Result.Properties.Item("lastLogon"))

With that said, why are you doing this "by hand" in the first place? The ActiveDirectory PowerShell module has a cmdlet Get-ADUser that already does all the work for you:

Import-Module ActiveDirectory

Get-ADUser -Filter * -Properties * | ? {
  $_.LastLogonDate -lt (Get-Date).AddDays(-60)
} | select SamAccountName, LastLogonDate | Export-Csv 'C:\test.csv' -NoType



回答2:


Why move all the items from $arrUsers to $inactiveusers? You can achieve desired result by adding this at the very end:

$arrUsers.getEnumerator() | Select-Object Key,Value | 
   Export-Csv c:\test.csv  -NoTypeInformation

Find out more about Export-CSV: http://technet.microsoft.com/en-us/library/hh849932.aspx



来源:https://stackoverflow.com/questions/25277632/powershell-variable-export-csv-cache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!