简体   繁体   English

将Powershell脚本导出到CSV

[英]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. 我有一个小脚本,该脚本为AD中特定OU中的所有用户检索LastLogonTimestamp和SAMAccount,并将时间戳转换为日期,并仅从字符串中提取日期。 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. 然后,我想将其输出到CSV,以便可以在Excel中将其打开并完美地格式化为列,并且看起来很漂亮。

I have tried ConvertTo-Csv and Export-Csv but have been uncuccessful. 我已经尝试了ConvertTo-Csv和Export-Csv,但是都失败了。 The problem is I am new to Powershell. 问题是我是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: 您将必须为每个用户创建对象并将其通过管道传输到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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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