简体   繁体   中英

Export powershell script to CSV

I have a small script which retrieves the LastLogonTimestamp and the SAMAccount for all users in a particular OU in AD and converts the timestamp to a date and extracts just the date from the string. That part works fine. I then would like to output that to a CSV so it may be opened in Excel and be perfectly formated into columns and look all pretty.

I have tried ConvertTo-Csv and Export-Csv but have been uncuccessful. The problem is I am new to Powershell. This is my first script and I don't fully understand how this works. My script is probably terribly messy and illogical but it does the job so far.

Please help. Thanks.

$userlist = Get-ADUser -SearchBase "OU=IT,DC=whatever,DC=com,DC=au" -Filter * -Properties * | Select-Object -Property Name,LastLogonTimestamp,SAMAccountName | Sort-Object -Property Name

$userlist | ForEach-Object {
    $last = $_.LastLogonTimestamp;
    $ADName = $_.SAMAccountName;

    $tstamp = w32tm /ntte $last;
    if($tstamp.Length -lt "40"){}else
    {
        $ADDate = [DateTime]::Parse($tstamp.Split('-')[1]).ToString("dd/MM/yyyy")
        write-host $ADDate;
        write-host $ADName;
    }
}

You will have to create objects for each user and pipe those to the Export-CSV cmdlet:

$usersList | %{

# current logic

$user = new-object psobject
$user | add-member -membertype noteproperty -name LastLogon -value $last
$user | add-member -membertype noteproperty -name ADName -value $ADName
$user | add-member -membertype noteproperty -name ADDate -value $ADDate
$user
} | export-csv test.csv -notype

Alternative syntax for populating the object:

$properties = @{"LastLogon" = $last; "ADName" = $ADName; "ADDate" = $ADDate}
$user = new-object psobject -property $properties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM