Reputation: 590
I have a text file which will contain some content as shown below:
SnapshotCreateTime : 7/30/2015 9:15:24 AM
SnapshotCreateTime : 7/30/2015 9:18:45 AM
SnapshotCreateTime : 7/31/2015 7:13:26 AM
SnapshotCreateTime : 7/30/2015 9:22:46 AM
SnapshotCreateTime : 7/30/2015 9:26:07 AM
What I need to do is that I need to retrieve the date format of each and write it to another text file. I have come up with something as below, but not working as expected:
$contents = Get-Content "Path\file.txt"
foreach($cont in $contents) {
$s = $cont -split ':'
$name = $s[1]
$name.Trim() | Add-Content "Path\newfile.txt"
}
The result of the above script is like:
7/30/2015 9
7/30/2015 9
7/31/2015 7
7/30/2015 9
7/30/2015 9
What I really need to have is like:
7/30/2015
7/30/2015
7/31/2015
7/30/2015
7/30/2015
I know select-string might work here, but I cant really say a specific string format other than d/mm/yyyy. Any thoughts or suggestions to achieve what I mentioned. Any help would be really appreciated.
Upvotes: 0
Views: 34
Reputation: 72680
You split on ':' which is also in hours. You can split on space and take the forth element.
$contents = Get-Content "Path\file.txt"
foreach($cont in $contents) {
$s = $cont -split ' '
$name = $s[4]
$name.Trim() | Add-Content "Path\newfile.txt"
}
On my own, I prefer @jsaak regex, or use the [datetime]::ParseExact()
method to get the date.
Upvotes: 1
Reputation: 59031
You could use a simple regex where you select the date and replace the string with the capture group:
$contents | % {
$_ -replace '.*: (.*/.*/....).*', '$1' |
Add-Content "Path\newfile.txt"
}
Upvotes: 1