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?
CodePudding user response:
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
CodePudding user response:
$LogPath = "C:\Users"
$LogPathName = Join-Path -Path $LogPath -ChildPath "logToday-$(Get-Date -Format 'MM-dd-yyyy').log"