powershell append date time to beginning of file - powershell

I'm working to get a powershell command that will dump the value into output.xml. First a value is requested from the user, then the application log is parsed for that value and the results are returned to output.xml. I would like to also tag the beginning with the date time stamp, but haven't been able to figure it out. This is what I have come up with to accomplish the parsing, and I have attempted to use a few other methods:
read-host (Get-Date).tostring("dd-MM-yyyy-hh-mm-ss")
I guess I don't understand exactly where to put this part of the code to make it work. My whole script looks like this.
$value = read-host "Enter your search value"
Get-WinEvent -Logname application -EA silentlycontinue | ?{$_.LevelDisplayName -eq "Error" -or $_.LevelDisplayName -eq "Warning"} | Out-File '$output.xml' -Append

Use Out-File to write the first line(s) of the file as well:
$value = Read-Host "Enter your search value"
"# $(Get-Date -Format 'dd-MM-yyyy-hh-mm-ss')" |Out-File output.log
"# User $($env:USERNAME) supplied the following search term '$value'" |Out-File output.log -Append
Get-WinEvent -Logname application -EA silentlycontinue | ?{$_.LevelDisplayName -eq "Error" -or $_.LevelDisplayName -eq "Warning"} | Out-File output.log -Append

If all you're looking for is the first line to be the data use this instead.
(Get-Date).tostring("dd-MM-yyyy-hh-mm-ss") | Out-File .\output.xml
Don't forget to use -Append if you're adding more lines after the date.

A simple edit to your write method:
Out-File "$(Get-Date -UFormat '%Y-%m-%d-%H-%M-%S-')$output.xml" -Append

Related

Column from powershell query with array list of servers is not exporting properly to csv

need some help with this bit of code. So I have got some powershell that is called from a bit of code as below:
powershell -file "E:\crs\shared\utils\EventViewerExport\EventViewerExport.ps1" "BAUT101,BAUT103,BAUT105,BAUT106,BAUT107,BAUT108,BAUT109,BAUT010"
The powershell code that the above calls is below:
#List of servers:
$ArraySvr = $args[0].split(",") ;
foreach ($Server in $ArraySvr){
$args = #{}
$args.Add("StartTime", ((Get-Date).AddMinutes(-160)))
$args.Add("EndTime", (Get-Date))
$args.Add("LogName", "System")
$args.Add("ID",7001)
Get-WinEvent -FilterHashtable $args -ComputerName $Server | select MachineName,LogName,LevelDisplayName,TimeCreated,ProviderName,ID,#{n='Message';e={(New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}} | export-csv -Delimiter '|' -Path E:\crs\shared\utils\EventViewerExport\EventViewerExportFile.csv -Append -Force
}
The script is almost 100% perfect, except the "Message" column isn't pulling through the the CSV file while its in the foreach function.
My csv file looks like this:
#TYPE Selected.System.Diagnostics.Eventing.Reader.EventLogRecord
"MachineName"|"LogName"|"LevelDisplayName"|"TimeCreated"|"ProviderName"|"Id"|"Message"
"BAUT101.compname.adp"|"System"|"Information"|"03/03/2022 18:03:15"|"Microsoft-Windows-Winlogon"|"7001"|
However the Message column does pull through when I take out the foreach function, as below:
$args = #{}
$args.Add("StartTime", ((Get-Date).AddMinutes(-160)))
$args.Add("EndTime", (Get-Date))
$args.Add("LogName", "System")
$args.Add("ID",7001)
Get-WinEvent -FilterHashtable $args -ComputerName 'BAUT101' | select MachineName,LogName,LevelDisplayName,TimeCreated,ProviderName,ID,#{n='Message';e={(New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}} | export-csv -Delimiter '|' -Path E:\crs\shared\utils\EventViewerExport\EventViewerExportFile.csv -Append -Force
By running this set of code with the foreach function, I get the correct csv export:
#TYPE Selected.System.Diagnostics.Eventing.Reader.EventLogRecord
"MachineName"|"LogName"|"LevelDisplayName"|"TimeCreated"|"ProviderName"|"Id"|"Message"
"BAUT101.compname.adp"|"System"|"Information"|"03/03/2022 18:03:15"|"Microsoft-Windows-Winlogon"|"7001"|"compname\djgood"
Does anyone know why on earth the Message column won't export when I'm running the powershell with an array of servers, but it will when I query a specific computer name?
Can anyone help me out please?
Thanks in advance.

Powershell get-content where-object

Morning, I am new to the world of Windows PowerShell and wondered if someone could advise on the following.
I am searching a txt file for a certain string of text.
Get-Content -Path "filepath" | Where-Object {
$_ -like '*string*'
} | Out-File c:\output.txt
This works OK for me but I want to be a little smarter and only pull back the string for that particular day.
I've tried to use the following
Get-Content -Path "filepath" | Where-Object {
$_ -like Get-Date -DisplayHint Date -UFormat "%d/%m/%y" + '*string*'
} | Out-File c:\output.txt
The line in the text file always starts with the date in that format but then I need to check for a string in the same line?
You need to put the Get-Date in parentheses:
Get-Content -Path "filepath" | Where-Object {
$_ -like (Get-Date -DisplayHint Date -UFormat "%d/%m/%y") + '*string*'
} | Out-File c:\output.txt
So, after trying several attempts, I've noticed that the file I am querying has the date format in MM/dd/yyyy format so this was why I wasn't finding anything.
Also, I needed to look for the previous day as well so added a little bit more in.
Tweaked it slightly and works now
get-content -path "location of text file" | where-object {$_ -like ("{0:MM/dd/yyyy}" -f (get-date).AddDays(-1)) + 'Sqlserver'} | out-file filename
Thanks everyone for your help

Overwrite an existing file with date as filename

I am very new to PowerShell scripting. I am trying to overwrite an existing file with date and time in it's file name.
Here is what i'm using.
$LogName = "Security"
$EventID = 4725
$Date = ((get-date).addDays(-1))
$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('MM-dd-yyyy_hh.mm.ss')
get-eventlog $LogName $EventID -after $Date | Export-CSV $Path -notypeinformation | Out-File -Filepath $Path -Append
However, upon running, it returns with an error that says
Out-File : The process cannot access the file because it is being used by another process
I hope you guys can help me with this. Thanks!
Try using ConvertTo-Csv not Export-CSV.
Get-EventLog $LogName $EventID -after $Date | ConvertTo-Csv -NoTypeInformation | Out-File -Filepath $Path -Append
The error is down to the fact that your trying to read and write to a file ($path) at the same time.
This will stop Export-CSV creating a file before you append to the same file, cutting out the error.

Out-File inside a foreach statement

im trying to run this script, it works but every time that it changes from item on the list it erases the file and starts over.
what i need this to do is to get from the list of items all the users and put them all in a single text file.
$sitios = Get-Content -Path C:\sitios.txt
Connect-SPOService -Url https://aaa.sharepoint.com/ -Credential Admin#aaa.onmicrosoft.com
foreach ($sitio in $sitios){
$sitio
Get-SPOUser -Site $sitio -Limit ALL | Out-File -FilePath C:\usuarios.txt
}
any help is appreciated
You could use the -Append switch of Out-File but all you should have to do is move it outside the loop.
(foreach ($sitio in $sitios){
Write-Host $sitio
Get-SPOUser -Site $sitio -Limit ALL
}) | Out-File -FilePath C:\usuarios.txt
That way all output will be sent to Out-File. I added Write-Host $sitio so that was not going to be in the file. You could also use Set-Content which is considered the preferential choice over Out-File
The brackets are needed around the loop so that we can use the pipe output. That foreach construct cannot have data directly piped from it. An answer here covers the reason.
That all being said you could then do something like this
$sitios | ForEach-Object{
Write-Host $_
Get-SPOUser -Site $_ -Limit ALL
} | Set-Content C:\usuarios.txt
This output should be a complex object that might not have a proper tostring equivalent. You can still get all the data with something like this instead.
$sitios | ForEach-Object{
Write-Host $_
Get-SPOUser -Site $_ -Limit ALL
} | Export-CSV C:\usuarios.txt -NoTypeInformation
You can use the Add-Content Cmdlet:
https://technet.microsoft.com/en-us/library/ee156791.aspx
Instead of Out-File use Add-Content
as in:
[...] | Add-Content C:\usuarios.txt

How to tail log files in Powershell for particular string

We would like to tail several log files "live" in powershell for particular string. We have tried to use "get-content" command but without luck because everytime as a result we received only results from one file. I assume that it was caused by "-wait" parameter. If there is any other way to tail multiple files ? I heard about runspaces but still I don't know how to implement it.
Our sample script below
dir d:\test\*.txt -include *.txt | `
Get-Content -Wait | `
select-string "windows" | `
ForEach-Object {Write-EventLog -LogName Application -Source "Application error" -EntryType information -EventId 999 -Message $_}
Any help will be appreciated.
Might be slightly late to the party...
As per here, we can use the following in a .ps1 file;
$ProgressPreference='SilentlyContinue'
Workflow My-Tail
{
Param([string[]] $Path)
foreach -parallel ($file in $path)
{
Get-Content -Path $file -Tail 1 -Wait
}
}
This lets us tail multiple files, invoking in powershell like;
My-Tail (dir C:\Users\User\Documents\*.log)
All that's left then is to filter by the required string;
My-Tail (dir C:\Users\User\Documents\*.log) | Select-String -Pattern ".*ERROR.*"
This will tail all files ending in .log in Documents, outputting lines that contain the text 'ERROR'
The only way I can think to do this is to create a bunch of jobs that run the command on each file. You can then receive the job output in a loop and changes in any of the files will be written to the screen:
gci d:\test\*.txt | % { $sb = [scriptblock]::create("get-content -wait $_") ; start-job -ScriptBlock $sb }
while(1) {
$m = $(get-job | receive-job | select-string "searchstring")
if($m -ne $null) {
Write-EventLog -LogName Application -Source "Application error" -EntryType information -EventId 999 -Message $m
}
sleep 1
}