Временная метка Powershell - PullRequest
       0

Временная метка Powershell

0 голосов
/ 13 февраля 2020

Я пытаюсь экспортировать журнал в файл csv в powershell, но у меня возникают трудности с размещением отметки времени для каждого «Журнала» в файле. Я могу экспортировать журнал в файл csv, но для каждого регистрируемого действия мне нужна отдельная временная метка. Например, я хотел бы, чтобы приведенный ниже вывод в моем CSV-файле выглядел следующим образом и имел метку времени для каждого (обратите внимание на метку времени перед действием)

2020/02/13 93520 - Performing the operation "Remove File" on target "\\03042019-PC\C$\Users\*\AppData\Local\Apps\Test\21.txt". 

2020/02/13 93522 - Performing the operation "Remove File" on target "\\03052019-PC\C$\Users\*\AppData\Local\Apps\Test\51.txt".  

Любая помощь будет принята с благодарностью! Вот что у меня есть: (из исследования онлайн)

Import-Module ActiveDirectory


$timestamp = "LogFile"

$filepath = "C:\$timestamp.csv"


#$Computers = Get-ADComputer -Filter {Name -like "*-PC"} | Select-Object -ExpandProperty Name 
$Computers = Get-ADComputer -Filter {Name -like "03*2019-PC"} | Select-Object -ExpandProperty Name 

# Loop through users and delete the file

ForEach ($Computer in $Computers) {

    $path = "\\$Computer\C$\Users\*\AppData\Local\Apps\Test\*"
    $result = Get-ChildItem -Path $path | Remove-Item -force -verbose *>> $filepath 
} 


$upperLimit = [datetime]::MaxValue #replace with your own date
$lowerLimit = [datetime]::MinValue #replace with your own date

$log | foreach {
$dateAsText = ($_ -split '\s',2)[0]
try
{
$date = [datetime]::Parse($dateAsText)
if (($lowerLimit -lt $date) -and ($date -lt $upperLimit))
{
$_ #output the current item because it belongs to the requested time frame
}
}
catch [InvalidOperationException]
{
#date is malformed (maybe the line is empty or there is a typo), skip it
}
}

1 Ответ

0 голосов
/ 13 февраля 2020

Полагаю, вы хотите, чтобы отметка времени была текущей датой и временем, хотя я не уверен, что означает число 5-ди git, например, цифры 93520 в вашем примере - что?

2020/02/13 93520 - Выполнение операции «Удалить файл» на цели »\ 03042019-PC \ C $ \ Users * \ AppData \ Local \ Apps \ Test \ 21.txt".

В любом случае, если вам нужна отметка даты + времени с текущими датой и временем, просто сгенерируйте и отформатируйте ее с помощью командлета get-date и объедините ее с текстом журнала, используя отформатированную строку. Подробнее о форматированной строке здесь .

Пример приведен ниже. Примечание: hh:MM:ss tt выводит 12-часовое время с AM / PM. HH:mm:ss 24-часовое время выхода

КОД

cls

$fakeLogText = '93520 - Performing the operation "Remove File" on target "\03042019-PC\C$\Users*\AppData\Local\Apps\Test\21.txt'
$output = "{0} {1}" -f (get-date -f "yyyy/mm/dd hh:MM:ss tt"), $fakeLogText
$output

$fakeLogText = '93522 - Performing the operation "Remove File" on target "\03052019-PC\C$\Users*\AppData\Local\Apps\Test\51.txt'
$output = "{0} {1}" -f (get-date -f "yyyy/mm/dd hh:MM:ss tt"), $fakeLogText
$output

ВЫХОД

enter image description here

Также отмечу, что ваша программа не будет работать так, как написано. Вы передаете содержимое $log в foreach, но переменная $ log никогда не загружается данными

ОБНОВЛЕНИЕ - Рабочая программа

Эта программа делает то, что Я думаю, вы хотите это сделать. Закомментируйте мой звонок на Get-ADComputer и раскомментируйте звонок на Get-ADComputer, который вы хотите

cls

Import-Module ActiveDirectory

$filepath = "C:\temp\logFile.csv"
$allUsersTextFileList = @()

#$Computers = Get-ADComputer -Filter {Name -like "*-PC"} | Select-Object -ExpandProperty Name 
#$Computers = Get-ADComputer -Filter {Name -like "03*2019-PC"} | Select-Object -ExpandProperty Name
$Computers = ("MyComputer1", "MyComputer2")

# Loop through users and delete their txt files

ForEach ($Computer in $Computers) 
{
    #make a list of users
    $userPathList = @(Get-ChildItem -Path "\\$Computer\C$\Users\")

    foreach ($userPath in $userPathList)
    {
        #for this user, make a path to their txt files
        $userTestFolderPath = ("{0}\AppData\Local\Apps\Test" -f $userPath.Fullname)

        #if the path exists, make list of all txt files in the \Test folder
        if (test-path -LiteralPath $userTestFolderPath -PathType Container)
        {
            $userTextFileList = @(Get-ChildItem -Path $userTestFolderPath -Filter *.txt)

            #add this user's list to the "all users" list
            $allUsersTextFileList += $userTextFileList
        }
    }
} 

$itemList = New-Object System.Collections.ArrayList
$itemList.clear()
$item = [ordered]@{} 

foreach ($textFile in $allUsersTextFileList)
{
    Remove-Item -force -verbose -LiteralPath $textFile.Fullname 

    $item.Date = (get-date -f "yyyy/mm/dd hh:MM:ss tt")
    $item.File = "Performing the operation 'Remove File' on target {0}" -f $textFile.Fullname 
    $itemList.add((New-Object PSObject -Property $item)) | out-null
}

$itemList | Export-Csv -LiteralPath "C:\temp\logFile.csv" -NoTypeInformation

ВЫХОД

enter image description here

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