Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of get-date in powershell to create a log string

I'm using these lines in a script to write some information that I'll finally put in a log file.

$log = "some text: "
$log += Get-Date
$log += "; some text"

This way I'll get my data correctly, so my output will be some text: 02/13/2013 09:31:55; some text. Is there a shorter way to obtain this result? I mean some like this (that actually doesn't work)

$log = "some text: " + Get-Date + "; some text"
like image 329
Naigel Avatar asked Feb 13 '13 08:02

Naigel


People also ask

How do I convert a date to a string in PowerShell?

The method (Get-Date). ToString() converts a DateTime object a String object.

How do I create a log file in PowerShell?

The simplest way to generate log files by adding content to a text file is: Function Log-Message([String]$Message) { Add-Content -Path "C:\Temp\Log. txt" $Message } Log-Message "Beginning exeuction of the script:" Log-Message "Exeucting of the script..." Log-Message "Completed exeuction of the script!"

Why we use $_ in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

How do I get just the date in PowerShell?

Using the “Get-Date” command, you can find the current date, format dates, tomorrow's date, and a lot more with PowerShell.


1 Answers

Try:

$log = "some text: $(Get-Date); some text"

The $() expand value from functions or from variable's property es: $($myvar.someprop) when they are inside a string.

like image 115
CB. Avatar answered Oct 16 '22 12:10

CB.