Reputation: 1
Beginners question on Powershell (version 3 is in use). Those variables work fine, but they can be perhaps improved
I have, inside a loop
$LastWriteTime = get-childitem $file.fullname | select LastWriteTime
$LastWriteTime_text = "$LastWriteTime"
$LastWriteTime_text_short = $LastWriteTime_text.substring(16,10) -replace "\W", '_'
The 2nd and 3rd line are because I don't know how to reformat the output of the first line directly as text. Therefore " ... ". It works. But using those extra variables is not efficient
Another also not too nice formatting using extra variables (which is kinda bad). I just dont know how to pipe
$check_hex = get-content -Path "C:\Test Script\Table.txt" | select-string -pattern "$file_type" | select -first 1
$check_hex_trim = $check_hex -replace "\W", '_'
$check_hex_txt = $check_hex_trim -creplace '[^A-Z]',''
Is there also a source with practicale examples how to handle those formatings?
Upvotes: 0
Views: 82
Reputation: 174485
$LastWriteTime
is a [DateTime]
object - when you convert it to a string, you lose a lot of information.
Instead of converting it to a string, keep it as it is, and then use Get-Date -Format
or ToString()
when you need to display it somewhere.
You also don't need to use Get-ChildItem
if you already have a FileInfo
object:
foreach($file in Get-ChildItem "C:\path\with\files")
{
# grab the LastWriteTime property
$LastWriteTime = $file.LastWriteTime
# Use Get-Date -Format to get a string with the time
Get-Date $lastWriteTime -Format "HH:mm:ss"
# You can also use ToString()
$LastWriteTime.ToString("HH:mm:ss")
}
You can use standard date formatting strings with both methods:
PS C:\> Get-Date -Format "d"
11/2/2015
PS C:\> Get-Date -Format "o"
2015-11-02T20:44:49.2382560+01:00
PS C:\> (Get-Date).ToString("y")
November, 2015
And custom formatting strings as well (like shown above):
PS C:\> [datetime]::Now.ToString("dddd, MMM d")
Monday, Nov 2
PS C:\> "{0:HH:mm:ss.fff}" -f $(Get-Date) # even the -f operator can do this!
20:48:34.415
PS C:\> Get-Date -Format "yyyy, MMMM"
2015, November
Upvotes: 1