0

I am trying to create a log filename for today date time using powershell command

 $date = Get-Date
    $log = "D:\NewFolder\Logs\FixService$date.log"  
    "Write this text to log" >> $log  

I am getting error as shown below , How to do this?

 out-file : The given path's format is not supported.
    At D:\NewFolder\somefile.ps1:5 char:1
    + "Write this text to log" >> $log
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : OpenError: (:) [Out-File], NotSupportedException
        + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand

But this works without date in log file name

$date = Get-Date  
$log = "D:\Crowdstrike\Logs\FixService.log"   
"Write this to log" >> $log

What I am doing wrong?

SmartestVEGA
  • 8,415
  • 26
  • 86
  • 139
  • Depending on your culture, the `$date` might contain colons (`:`) which aren't supported in a filename, see: [Allowed characters in filename](https://stackoverflow.com/a/4814088/1701026) – iRon Oct 11 '21 at 09:32
  • what change i need to make this work? – SmartestVEGA Oct 11 '21 at 09:34
  • 2
    See this one: https://stackoverflow.com/questions/2249619/how-to-format-a-datetime-in-powershell – harper Oct 11 '21 at 09:34
  • Does this answer your question? [Using Out-File to have a date variable within the name for the file](https://stackoverflow.com/questions/50339544/using-out-file-to-have-a-date-variable-within-the-name-for-the-file) – iRon Oct 11 '21 at 09:34
  • 1
    This worked $date = Get-Date $DateStr = $date.ToString("yyyyMMdd") $log = "D:\Crowdstrike\Logs\FixService$DateStr.log" – SmartestVEGA Oct 11 '21 at 09:37
  • Can't post as answer. It's more a hint that this is duplicate question. – harper Oct 12 '21 at 07:13
  • 1
    Does this answer your question? [How to format a DateTime in PowerShell](https://stackoverflow.com/questions/2249619/how-to-format-a-datetime-in-powershell) – harper Oct 12 '21 at 07:13
  • yes @harper post that as answer, i will accept – SmartestVEGA Oct 12 '21 at 07:58

2 Answers2

3

Powershell uses ToString method to convert the value of the current DateTime object to its equivalent string representation using the specified format and the formatting conventions of the current culture. You can inspect your current culture by

[System.Globalization.CultureInfo]::CurrentCulture.Name 

Or using Get-Culture Cmdlet. The issue here is that the resultant string contain the characters that are not allowed in filenames. So one solution is to use the format parameter of the get-date Cmdlet.

Get-Date -Format yyyyMMdd
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
1
$LogPath = "C:\Users"

$LogPathName = Join-Path -Path $LogPath -ChildPath "logToday-$(Get-Date -Format 'MM-dd-yyyy').log"
Narayana Lvsl
  • 315
  • 2
  • 10