Home > OS >  Timestamp a txt file from the output of a command all in 1 line
Timestamp a txt file from the output of a command all in 1 line

Time:11-08

I'm trying to timestamp the filename of the following command however I'm struggling to get it included.

ping.exe -n 3600 1.1.1.1 | Foreach{"{0} - {1}" -f (Get-Date),$_} >> $ENV:UserProfile\Downloads\pingresult.txt

I want the output to be "202211081006_pingresult.txt"

CodePudding user response:

You can use the same technique you're using for the content of your file for its name too, by using $(...), the subexpression operator, and a custom date-time format with -f, the format operator:

ping.exe -n 3600 1.1.1.1 |
  ForEach-Object { 
    '{0} - {1}' -f (Get-Date), $_ 
  } >> "$HOME\Downloads\$('{0:yyyyMMddHHmm}' -f (Get-Date))_pingresult.txt"
  • Related