Asked by:
Not getting correct .CSV export after running script

Question
-
I have a question about running scripts with a CSV output. I am running the script below with | out-file c:\scripts\last logon\results.csv and after it runs I get a csv file with everything in one column. Is there a different syntax I should use for this?
Thanks in advance.....
# PSLimitedLastLogon.ps1
# Specify file of computer NetBIOS names.
$File = "c:\scripts\Last Logon\Computers.txt"
$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"
$Searcher.SearchRoot = "LDAP://$Domain"
$Searcher.PropertiesToLoad.Add("sAMAccountName") > $Null
$Searcher.PropertiesToLoad.Add("lastLogonTimeStamp") > $Null
# Read computer names.
$Computers = (Get-Content $File)
# Filter on computers listed in file.
$Filter = "(|"
ForEach ($Computer In $Computers)
{
# sAMAccountName of computer is NetBIOS name with trailing "$" character.
$Filter = $Filter + "(sAMAccountName=$Computer`$)"
}
$Filter = $Filter + ")"
$Searcher.Filter = $Filter
$Results = $Searcher.FindAll()
ForEach ($Result In $Results)
{
$Name = $Result.Properties.Item("sAMAccountName")
$LL = $Result.Properties.Item("lastLogonTimeStamp")
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()
}
"""$Name"",$LastLogon"
}
Chad Guiney
Monday, July 1, 2019 1:22 PM
All replies
-
Please format your code as code using the code posting tool provided on the icon bar of the post editor (second to last icon). Thanks.
If you want to have a CSV file you should use Export-Csv - it is made for. ;-)
Live long and prosper!
(79,108,97,102|%{[char]$_})-join''
- Proposed as answer by Richard MuellerMVP Monday, July 1, 2019 2:16 PM
- Edited by BOfH-666 Monday, July 1, 2019 2:23 PM
Monday, July 1, 2019 2:06 PM -
I have used similar syntax in the past and it worked fine for me. However, there should be no need to quote the sAMAccountName, as the comma character is not allowed. But dates have commas.
Richard Mueller - MVP Enterprise Mobility (Identity and Access)
Monday, July 1, 2019 2:28 PM -
'"{0}","{1}"' -f $Name,$LastLogon
\_(ツ)_/
- Proposed as answer by LeeSeenLiMicrosoft contingent staff Tuesday, July 2, 2019 2:29 AM
Monday, July 1, 2019 5:09 PM -
Hi,
Was your issue resolved?
If you resolved it using our solution, please "mark it as answer" to help other community members find the helpful reply quickly.
If you resolve it using your own solution, please share your experience and solution here. It will be very beneficial for other community members who have similar questions.
If no, please reply and tell us the current situation in order to provide further help.
Best Regards,
Lee
Just do it.
Wednesday, July 31, 2019 8:40 AM