I'm writing a script which displays the last 7 backups of my server. The scripts outputs the following: TimeCreated, Level, ID, Message,Size in a html table.
my script:
$lastsevendays = (get-date) - (new-timespan -day 7)
$MyObject = Get-WinEvent -FilterHashTable #{LogName='Microsoft-Windows-Backup'; StartTime=$lastsevendays}
$BackupSize = #{ Name = "BackupSize"; Expression = { (($objFSO.GetFolder("C:\Users\LaBackup").Size) / 1MB) } }
$MyObject |
Select 'TimeCreated', 'LevelDisplayName','ID', 'Message', $BackupSize |
ConvertTo-HTML -Head $Header |
Out-file C:\Users\script.htm
I want the script to run everyday and automatically remove backups row which date back from more than 7 seven.
I think i'm supposed to select row which have "Date" less or equal than seven days ago,
and delete them to add more recent row.
I have no idea how i could do this as, ConvertTo-HTML seems to regenerate a whole table each time it's called.
Some ideas??
thanks in advance
Give this a try:
Get-WinEvent -LogName Microsoft-Windows-Backup | Where-Object -FilterScript { $_.TimeCreated -gt [DateTime]::Now.AddDays(-7); }
This uses the Where-Object cmdlet to filter events that are older than 7 days in the Microsoft-Windows-Backup log.
EDIT
I guess I misunderstood what you were looking for. All I did was change the -lt operator to -gt.
Related
I'm beginner in power shell ( HTML ) and I need some help. I want to get a variable from the McAfee website. In this page there is a table where you can download the latest .dat files.
I only need the version number - now it's 8963 - from the first table ( Download V2 Virus Definition Updates (DATs) ) and this result needs to be saved in a variable because I want to compare it with other variable from another script.
Now I'm able to query all of the tables with all of the data:
$r = Invoke-WebRequest -Uri https://www.mcafee.com/enterprise/en-us/downloads/security-updates.html
$r.parsedhtml.getelementsbytagname("TR") |
% { ( $_.children | ?{ $_.tagName -eq "td"} | % innerText ) }
Write-Host
Unfortunately it's too much information for me, because list all of the data which is in a table.
The retrived data in pic.: data
Thanks for the help.
Well this isn't the cleanest method, but if you expect the first entry to allwayse be the one supplying the Filename of the needed .exe you could use this:
($r.parsedhtml.getelementsbytagname("TR") |% { ( $_.children | ?{ $_.tagName -eq "td"} | % innerText ) } | Select-Object -First 1).Split('xdat')[0]
This basically takes the first String of your query, splits the string on the position of xdat and than takes everything before xdat.
The Output then is 8963.
If you want to do it the more correct way, you should look out for the correct html-attribute to filter for.
I have a process that I am trying to fully automated and have hit upon a stumbling block.
The process runs through a number of SQL queries and then outputs these results to different named CSV files.
Where my issue lies is that where no results are returned in the query to the dataset when I export the data (which I must do to satisfy auditors) there is no header data written to the CSV file.
What I need to do therefore is IF the dataset contains 0 rows then to simply export a CSV file containing the headings "Client", "Balance", "Account".
Where as if there is data within the table then the process can continue as it currently does.
What I am is unsure how the hell this can be achieved...
I am currently muting whether or not I will have to export the data and then write a loop to delete any lines from the CSV containing for example "Client" then re-import the CSV's add the column heading that I want and export it again. As this is messy, ideally I would like to keep away from this..
Code is
$SqlCmd.CommandTimeout=$timeout;
$SqlCMD.CommandText = $034CASHQUERY;
$SqlCmd.Connection = $SqlConnection;
## - Extract Data and build sql data object
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);
$DataSetTable = $DataSet.Tables["Table"];
IF($DataSet.Tables["Table"]){
$isnotnull
$DataSet.Tables["Table"] | Export-Csv $034CASHOUT -NoTypeInformation
echo "CL2 Exported"
}
else {
}
Has anyone come across this before or aware of how to iterate through the issue?
You could create a .csv file and add the header text manually.
$headerText = ('"Client","Balance","Account"' + "`n")
New-Item $034CASHOUT | Add-Content -value $headerText
Also, I think your IF condition may be a bit wonky. Are you looking for:
IF($DataSet.Tables["Table"] -isnot $null)
All together:
IF($DataSet.Tables["Table"] -isnot $null){
$DataSet.Tables["Table"] | Export-Csv $034CASHOUT -NoTypeInformation
echo "CL2 Exported"
}
else {
$headerText = ('"Client","Balance","Account"' + "`n")
New-Item $034CASHOUT | Add-Content -value $headerText
}
This is probably not the best way to do it, but I think this is what you described.
Can you please provide more information on the data you're processing? I understand if there is no data you want "Client", "Balance", "Account".
When there is data present, will it also be in these 3 columns?
If so this is your answer:
$DataSet.Tables["Table"] |
Select-Object Client,Balance,Account |
Export-Csv $034CASHOUT -NoTypeInformation
I am looking at a way to list how many times an AD property matching a certain value appears against each user.
Specifically - Users in our AD have a Custom Attribute distinguishing their company. I need to run monthly reports that will display a list of all companies and how many users are listed.
This is as close as I have it - but it is not user friendly for our Accounts team.
import-csv c:\HostedCompanyList.csv -header ID |
foreach {
$total = (get-aduser -filter "(extensionattribute1 -eq '$($_.ID)') -and (extensionattribute2 -eq 'billed')" -properties *).count
write-host $total $_.ID
}
This is the content of HostedCompanyList.csv
ID
Company1
Company2
Company3
My output shows as `
35 Company1
12 Company2
27 Company3
I'd like to output this information to a CSV or HTML file as opposed to displaying it on the PS window.
I appreciate this is likely already a very long winded way of running this query - could I perhaps have overlooked a much simpler method?
Bonus points if there's a way I can do this without having to import a CSV file at all - that would cut out the need to add additional entries into that list when new "companies" get added on or taken away!
Thank you for any help offered.
Untested, since I don't have the same extension attributes, but this shape:
query everyone, filter the billed people
group-object by company name
select properties and export to csv
should work with one query, no text file to read from, and csv export.
$filter = "extensionattribute2 -eq 'billed'"
$users = Get-ADUser -filter $filter -Property extensionattribute1, extensionattribute2
$groups = $users | Group -Property extensionattribute1
$groups | select Count, Name | Export-Csv out.csv -notypeinformation
I'm attempting to write a script which will read in a CSV generated by querying AD for user information (that part is done) but then will allow me to add a string to the beginning of each value of a column in the CSV file and then export it.
For instance we have this CSV file:
"displayname","Office"
Bob,7142
Janet,8923
SantaClaus,0912
NicCage,0823
I want to take each entry for "Office", add the string "BUG" before it and then export it back out. The modified CSV should look like:
"displayname","Office"
Bob,BUG7142
Janet,BUG8923
SantaClaus,BUG0912
NicCage,BUG0823
At this point, I've been attempting to read in just the "Office" column and then displaying it with "Write-Host". The idea being that if I can do that then maybe I can create a new variable that would be something like:
$BUG = "BUG"
$NewVar = $BUG$Office
Which would hopefully look like the second CSV file. I am extremely new to powershell scripting.
The attempts I've made so far are these:
Attempt #1:
$UserList = Import-CSV C:\Users\username\CSV.csv
$UserList | ForEach-Object ($_.Office) { $UserList }
Attempt #2:
$projectName = import-csv C:\Users\username\CSV.csv | % {$_.Office}
$BUG = "BUG"
$projectName | ForEach-Object ($_) {$projectName}
Attempt #3:
$UserList = Import-CSV C:\Users\username\CSV.csv
#ForEach ($Office in $Userlist) {
#Write-Host $UserList.Office
#}
Attempt #4:
Import-Csv "C:\Users\username\CSV.csv" -Header ("displayname","Office","whenCreated","EmailAddress") | Select-Object Office | Export-CSV -Path C:\users\Username\test.csv
I have gotten it to read out just the Office numbers before using the ForEach-Object loop structure but then it never stops reading out the office numbers so that's unhelpful.
I think I'm going in the right direction, but I just can't figure out how to modify a column like this.
Instead of trying to extract the Office column, just pipe the full data set (all columns) to ForEach-Object, change the value of the Office property and pipe it back to Export-Csv:
$Prefix = "BUG"
Import-Csv .\file.csv | ForEach-Object {
$_.Office = $Prefix + $_.Office
$_
} | Export-Csv .\file_modified.csv -NoTypeInformation
I am new to powershell. Currently we are in need of a poweshell script to compare two large (100000 rows and n columns (n > 300, also column headers are Dates corresponding to each wednesday). The value of n keeps on incrementing each week in the file. We need to compare the files (current week and last week), and need to make sure that the only difference between the two files is the last column.
I have gone through some Forums and Blogs and I could do only Little due to my ignorance.
If there is a way to drop the last column from a csv file in powershell, we may be able to make use of the below script below to compare the previous week's file and the current week's file after droping the last column from current week's file.
It would be really helpful if someone can help me here with your hard earned knowledge
[System.Collections.ArrayList]$file1Array = Get-Content "C:\Risk Management\ref_previous.csv"|Sort-Object
[System.Collections.ArrayList]$file2Array = Get-Content "C:\Risk Management\ref_current.csv"|Sort-Object
$matchingEntries = #()
foreach ($entry in $file1Array) {
if ($file2Array.Contains($entry)) {
$matchingEntries += $entry
}
}
foreach ($entry in $matchingEntries){
$file1Array.Remove($entry)
$file2Array.Remove($entry)
}
Cheers,
Anil
Assuming that the column name you want to exclude is LastCol (adjust to your actual column name):
$previous = Import-csv "C:\Risk Management\ref_previous.csv" | Select-Object -Property * -ExcludeProperty LastCol | Sort-Object;
$current = Import-csv "C:\Risk Management\ref_current.csv" | Sort-Object;
Compare-Object $previous $current;
This will drop the last column from each of the input files and indicate whether the remaining content differs.
Based on the answer that alroc gave, you should be able to get the last column name using a split operation on the first line of the CSV file, and then using that on the -ExcludeProperty parameter.
However, the Compare-Object command on this doesn't work for me, but it does pull back the right data into each variable.
$CurrentFile = "C:\Temp\Current.csv"
$PreviousFile = "C:\Temp\Previous.csv"
$CurrentHeaders = gc $CurrentFile | Select -First 1
$CurrentHeadersSplit = $CurrentHeaders.Split(",")
$LastColumn = $CurrentHeadersSplit[-1] -Replace '"'
$Current = Import-Csv $CurrentFile | Select -Property * -ExcludeProperty $LastColumn | Sort-Object
$Previous = Import-Csv $PreviousFile | Sort-Object
Compare-Object $Current $Previous
The import-csv and export-csv both give the opportunity to exclude columns.
The import-csv has the -header option and you simply name the incoming headers and exclude the last columns header. If there are 10 columns, only name 9. The last column will be excluded.
For export-csv, select the columns you'd like to write out ( |select col1,col2,col3|export-csv... ) and don't select the column you're trying to exclude.