Format Date Time to your Output Needs
If you want to format the date and assign the string to a variable.
I have combined both PowerShell and .NET to provide the flexibility.
$oDate = '{0}' -f ([system.string]::format('{0:yyyyMMddHHmmss}',(Get-Date)))
How this Works
- PowerShell Operator - '{0}' -f (.....)
- .NET Notation - [system.string]::format('customformat',InputObject)
- Customised Format by combining PowerShell with .NET - '{0:yyyyMMddHHmmss}'
- Input Object provided by PowerShell cmdlet - (Get-Date)
- Stored in the PowerShell variable - $oDate
Example
If the date and time when run was Monday, 5 July 2021 5:45:22 PM (Format '{0:F}').
Using the Code
You can customise the the string to meet your requirements by modifying 'yyyMMddHHmmss' using the Microsoft .NET Custom Date Time Notation.
$date -format "yyyMMdd"
is much more intuitive for formatting a single object than'{0:yyyyMMdd}' -f $date
.-f
operator (with the syntax as shown in the accepted answer), but no-format
operator. The error message is complaining aboutormat
not being a valid RHS operand, but note that recent PowerShell versions actually emit a different, more helpful error message:Unexpected token '-format' in expression or statement
.ToString(...)
... and that, combined with enough programming experience, we can guess that the format strings use zero-indexed references to the objects being interpolated, and use {} to wrap placeholders.)