Powershell CSV modification - powershell

CSV source exemple:
"Requested Quantity","Unit of Measure","Requested Date","Forecast Timing Qualifier","Rating"
"4.00 ","EA","26.09.2022","W","DOA1"
"12.00 ","EA","27.09.2022","W","DOA1"
I need to remove the last 3 Characters to Requested Quantity and
I need to convert the Requested Date format to Month.Day.Year for each line.
Input : "4.00 ","EA","26.09.2022","W","DOA1"
Output : "4","EA","09/26/2022","W","DOA1"
I got the Requested quantity ok but I need some help with converting the date portion.
Thanks

For the Requested Quantity column you can use the -replace operator to remove the dot and everything after. For the date column, use [Datetime]::ParseExact() to parse the existing format, then convert back to a string with the desired format:
Import-Csv path\to\source.csv |ForEach-Object {
# Cut the trailing decimals off the quantity
$_.'Requested Quantity' = $_.'Requested Quantity' -replace '\..*$'
# Parse and re-format date column
$_.'Requested Date' = [datetime]::ParseExact($_.'Requested Date', 'dd.MM.yyyy', $null).ToString('MM/dd/yyyy')
# output the modified object for export
$_
} |Export-Csv path\to\output.csv -NoTypeInformation

Related

I want the sorted list of date using powershell

I am getting list of dates and storing it into an array like
$arraylist={2022-03-24T12:05:05Z 2022-03-29T12:04:10Z 2022-03-23T12:54:07Z 2022-03-26T13:15:36Z 2022-03-22T10:06:11Z 2022-03-23T09:54:08Z}
by using a command $arrayList +=$listdate. Now I want the sorted list of date alone like
$sortedlist={2022-03-29 2022-03-26 2022-03-24 2022-03-23 2022-03-23 2022-03-22}
Not with timing. I am doing these things in PowerShell. The details of date which I am getting is in string format not in date-time format. can anyone help me out with this?
I initially split the date with $arrayList.Split('T') and stored the date alone in another array. But it is not sorted form. I tried to sort it but I am not getting desired sorted list.
Is there any other way to get desired sorted list of date?
If you are getting your dates in a single string (as per the example of data you have provided) it would be possible to split the string into an array and then convert the array of strings into datetime objects:
$DateString = "2022-03-24T12:05:05Z 2022-03-29T12:04:10Z 2022-03-23T12:54:07Z 2022-03-26T13:15:36Z 2022-03-22T10:06:11Z 2022-03-23T09:54:08Z"
$array = $DateString -split " "
$FormattedDates = Foreach ($item in $array){
[DateTime]::ParseExact($Item, "yyyy-MM-ddTHH:mm:ssK", $null)
}
$FormattedDates | Sort | ForEach-Object {$_.ToString("yyyy-MM-dd")}

To compare the day , date , timestamp of two lines in file and output the latest day,date,timestamp

I have below lines from two different file having day , date ,timestamp. I need to output the line with latest timestamp.
The lines of one file :
Tue 31/12/2000 17:13:29.83 - file copied
And another file content is :
Sun 17/07/1996 12:11:14.84 - drivers updated
The output must be
Tue 31/12/2000 17:13:29.83 - file copied
How can we compare timestamp?
To parse out the date from these strings you can do:
# get the date and time from the string, remove the dayname as it is incorrect for that date
$dateString = ("Sun 31/12/2000 17:13:29.83 - file copied" -split '-')[0].Substring(4).Trim()
$date1 = [datetime]::ParseExact($dateString, 'dd/MM/yyyy HH:mm:ss.ff', [CultureInfo]"en-US")
# do the same for the date in the second file and call that $date2
Then simply compare the dates using
$theDateYouWant = if ($date1 -gt $date2) { $date1 } else { $date2 }
By stripping off the dayname, you can use $null or [cultureinfo]::InvariantCulture instead of [CultureInfo]"en-US"

How to Display Modified Time and Modified By Fields Correctly with Powershell

I have a script that outputs to CSV all items/files from all Lists and Libraries. In addition, it displays the current and previous versions of an item/file. This also displays which user modified the file for each version and also displays the date/time the file was modified for every version:
function Get-DocInventory([string]$siteUrl) {
$web = Get-SPWeb "http://contoso.com/sites/Depts3/HBG"
foreach ($list in $web.Lists) {
foreach ($item in $list.Items) {
foreach($version in $item.Versions){
$data = #{
"Version" = $version.VersionLabel
"List Name" = $list.Title
"Created By" = $item["Author"]
"Created Date" = ($item["Created"] -as [datetime]).DateTime
"Modified By" = $version["Editor"]
"Modified Date" = ($version["Modified"] -as [datetime]).DateTime
"Item Name" = $item.Name
}
New-Object PSObject -Property $data | Select "List Name", "Item Name", "Version", "Created By", "Created Date", "Modified By", "Modified Date"
}
}
$web.Dispose();
}
}
Get-DocInventory | Export-Csv -NoTypeInformation -Path C:\GenerateReport.csv
Below is a sample of what the script outputs:
And below is an excel example of what I see when I go to the Version History of the Lions.pdf file:
I have 2 problems:
The column Modified By is displaying email and domain username which is not required.
My script displays the column Modified Date as 5 hours ahead. The script output for Version 1 of Lions.pdf displays time as 11:23 AM. But when I go to Version History of Lions.pdf it says that Version 1 was modified at 6:23 AM. The time discrepancy is the same across the board as 5 hours ahead which is incorrect.
I can't seem to figure out what I am doing wrong here. Can someone please assist in the issue I am having? My main concern is the time and I would greatly appreciate any assistance.
User Fields
Normally in server side code, accessing a user field value using array notation (eg myItem["Author"]) would return an object that you would cast to an appropriate type (Microsoft.SharePoint.SPFieldUserValue). Powershell, however, automatically casts these values to strings, which is why you're getting undesirable values.
Fortunately, there's a way around it! First, get the field itself as an object, then pass the field value into the field's GetFieldValue() method.
$userField = $item.Fields.GetField("Author");
$authorObject = $userField.GetFieldValue($item["Author"]);
You'll then have an object with properties you can access to retrieve the desired values, such as LookupValue for the user's display name on the site.
$authorName = $authorObject.LookupValue;
Date Fields
Date fields are little easier, because Powershell will actually hand them over to you as DateTime objects.
To format a DateTime object, you can just call .ToString() and pass in a parameter indicating the desired format.
$data = #{
...
"Modified Date" = $item["Modified"].ToString("MM/dd/yyyy h:mm tt");
...
}
Time Discrepancy
This is most likely attributable to your local timezone. The times displayed on a SharePoint site via the browser are determined by your PC's timezone settings. The times actually saved to SharePoint's underlying database are determined by the server's timezone settings.
To reconcile them, you can use the DateTime object's .ToUniversalTime() method to get a corresponding DateTime object in UTC time (and optionally offset it as desired until it aligns with the local timezone and daylight savings adjustments).
Edit: I'm guessing you're in US Eastern time (UTC-5) and it's giving you results in UTC time (Universal Coordinated Time, which is 5 hours ahead of you except during daylight saving time). You should be able to offset the hours manually to account for this.
$localOffset = -5;
$modified = $version["Modified"] -as [datetime];
if($modified.IsDaylightSavingTime()){$localOffset += 1;}
$modifiedLocal = $modified.addHours(-$localOffset);

How can reorder a file by asc or desc order from specific column

How can reorder a file by asc or desc order from specific column date and time or only date column.
{"hostname":"sg2","role":"epay","eventid":"ALERT_ORACLE","date":"02/08/2011","time":"01:30:00"},
{"hostname":"sg1","role":"pay","eventid":"ALERT_DF","date":"11/24/2010","time":"19:33:01"},
{"hostname":"sg3","role":"ipay","eventid":"ALERT_SMF","date":"12/11/2012","time":"02:30:00"},
Usually use "sort -gk (column number)" in that case not able to catch date and time column or only date, maybe is need some separator string or related.
Expetected view is:
{"hostname":"sg1","role":"pay","eventid":"ALERT_DF","date":"11/24/2010","time":"19:33:01"},
{"hostname":"sg2","role":"epay","eventid":"ALERT_ORACLE","date":"02/08/2011","time":"01:30:00"},
{"hostname":"sg3","role":"ipay","eventid":"ALERT_SMF","date":"12/11/2012","time":"02:30:00"},
Your life would be easier if you had chosen an ISO date format (YYYY-mm-dd), but
sort_by_date() {
awk -F \" '{
split($16, date, "/")
split($20, time, ":")
timestamp = mktime(date[3]" "date[1]" "date[2]" "time[1]" "time[2]" "time[3])
print timestamp "\t" $0
}' "$1" |
sort -k1,1n |
cut -f2-
}
sort_by_date filename
For descending, use sort -k1,1nr
Use sort with : as delimiter and order by column 5M for date comparison:
$ sort -t: -k5M file
{"hostname":"sg1","role":"pay","eventid":"ALERT_DF","date":"11/24/2010","time":"19:33:01"},
{"hostname":"sg2","role":"epay","eventid":"ALERT_ORACLE","date":"02/08/2011","time":"01:30:00"},
{"hostname":"sg3","role":"ipay","eventid":"ALERT_SMF","date":"12/11/2012","time":"02:30:00"},
Source: Sort logs by date field in bash.

How to match date mm/dd/yyyy

Given the following input
506028500,1820196768,43,0,84552257, ,1,-71.16,42.42,04/26/2012,
I want to filter the date at the end of the row, so I can change its mm/dd/yyyy format into MySQL date format yyyy-mm-dd:
I am trying to match the date at the end of the row having first removed the trailing ',' (comma).
{
s/,$//g
/\([0-9][0-9]\)\/\([0-9][0-9]\)\/\([0-9][0-9][0-9][0-9]\)$/=
}
I'm getting 12847, but am expecting 04262012.
What am I doing wrong, that I can't even match the date that's there?
Thanks.
This might work for you:
echo "506028500,1820196768,43,0,84552257, ,1,-71.16,42.42,04/26/2012," |
sed 's|,\(..\)/\(..\)/\(....\),$|,\3-\2-\1,|'
506028500,1820196768,43,0,84552257, ,1,-71.16,42.42,2012-26-04,
If you just want the date:
echo "506028500,1820196768,43,0,84552257, ,1,-71.16,42.42,04/26/2012," |
sed 's|.*,\(..\)/\(..\)/\(....\),$|\3-\2-\1|'
2012-26-04
This works for me:
sed "s/\([0-9]\{2\}\)\/\([0-9]\{2\}\)\/\([0-9]\{4\}\)$/\3-\1-\2/g" someFile.txt
At least it replaces the date string with one of the desired format.
To only print the date at the end, the following works for me:
sed "s/.*\([0-9]\{2\}\)\/\([0-9]\{2\}\)\/\([0-9]\{4\}\)$/\3-\1-\2/g" someFile.txt