Добавить время в выходной файл - PullRequest
0 голосов
/ 02 октября 2019

Этот сценарий добавляет пользователей домена к любой группе «Администраторы» другого компьютера или системы удаленного домена через 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)
    }
}

Вот так выглядит выходной файл, здесь я хочу добавить четвертыйстолбец с датой и временем:

ComputerName,Availability,Status
TD123696WJN339P,Oniline,Success
TD123419WJN339P,Oniline,Success
ComputerName,Availability,Status
5VERF9097LTIO01,Offline,failed
ZF001024DJH706G,Offline,failed
5MICF9017LTIO01,Offline,failed

Ответы [ 2 ]

2 голосов
/ 02 октября 2019

Простой подход состоит в том, чтобы просто добавить другое поле к вашему выводу, например

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
0 голосов
/ 02 октября 2019

Это действительно интересный подход, который у вас там работает с CSV, и он немного усложняет сценарий (с моей точки зрения и без неуважения!).

Почему бы не попробовать использовать пользовательский объект PowerShell?

#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
$result = 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
            [PSCustomObject]@{
                Computer = $Computer
                Availability = $availability
                Status = $status
                Date = Get-Date
            }
        } catch {
            Write-Verbose "Failed"
        }
    } else {
        Write-Warning "$Computer : Offline"
        $availability = "Offline"
        $status = "failed"
        #Update the status in the output file
        [PSCustomObject]@{
            Computer = $Computer
            Availability = $availability
            Status = $status
            Date = Get-Date
        }
    }
}

$result | Export-Csv -Path $Output -NoTypeInformation

Таким образом, вы сохраните результат в переменной $result и сможете экспортировать его как CSV без каких-либо сложностей. Использование PowerShell Custom Object - отличный способ хранить данные из разных источников и выводить их так, как вы хотели бы видеть.

Попробуйте и оставьте отзыв, если хотите :)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...