首页 > 解决方案 > 在输出文件中添加时间

问题描述

此脚本通过 PowerShell 将域用户添加到任何其他或远程域计算机/系统的“管理员”组。

这将返回 csv 中的最终状态,其中包含三列(计算机名称、可用性、状态)

我需要在包含时间和日期的输出文件中添加第四列。

#Create a file in the required path and update in the below command line
$Output = "C:\CSV\Output.csv" 
#The output field of the computer will blank if the user is already exist in the group
Add-Content -Path $Output -Value "ComputerName,Availability,Status"
$status = $null
$availability = $null
#Save the CSV (Comma seperated) file with the server host name and the username to be added
Import-Csv C:\CSV\Computer.csv | ForEach-Object {
    $Computer=$_.Computer
    $User=$_.user
    if (Test-Connection -ComputerName $Computer -Count 1 -Quiet) {
        Write-Verbose "$Computer : Online"
        $availability="Oniline"
        try {
            $GroupObj=[ADSI]"WinNT://$Computer/Administrators,group"
            $GroupObj.PSBase.Invoke("Add",([ADSI]"WinNT://jdom.edu/$User").Path)
            $status="Success"
            #Update the status in the output file
            Add-Content -Path $Output -Value ("{0},{1},{2}" -f $Computer, $availability, $status)
        } catch {
            Write-Verbose "Failed"
        }
    } else {
        Write-Warning "$Computer : Offline"
        $availability = "Offline"
        $status = "failed"
        #Update the status in the output file
        Add-Content -Path $Output -Value ("{0},{1},{2}" -f $Computer, $availability, $status)
    }
}

这是输出文件的外观,这是我想在第四列中添加日期和时间的地方:

计算机名称、可用性、状态
TD123696WJN339P,在线,成功
TD123419WJN339P,在线,成功
计算机名称、可用性、状态
5VERF9097LTIO01,离线,失败
ZF001024DJH706G,离线,失败
5MICF9017LTIO01,离线,失败

标签: powershell

解决方案


简单的方法是在输出中添加另一个字段,即

Add-Content -Path $Output -Value "ComputerName,Availability,Status,Timestamp"

"{0},{1},{2},{3}" -f $Computer, $availability, $status, (Get-Date)

但是,除非您实际上想要在输出文件中有多个标题行(为什么?),否则您应该使用计算属性Export-Csv.

Import-Csv 'input.csv' |
    Select-Object Computer, User, @{n='Status';e={
        if (Test-Connection -ComputerName $_.Computer -Count 1 -Quiet) {
            ...
        } else {
            ...
        }
    }}, @{n='Timestamp';e={Get-Date}} |
    Export-Csv 'output.csv' -NoType

推荐阅读