| by Arround The Web | No comments

Get Date and Time on the Same Line – PowerShell

PowerShell utilizes the “Get-Date” cmdlet to get the current date and time on Windows. The date and time are fetched to get assistance in multiple PowerShell operations, such as it is used to time stamp the log file. More specifically, you can utilize different commands to ensure that date and time print on the same line.

This post aims to guide related to printing the time and date on the same line.

How to Get the Date and Time on the Same Line in PowerShell?

These approaches can be utilized to get or print the date and time on the same line in PowerShell:

Method 1: Get/Retrieve the Date and Time on the Same Line in PowerShell Utilizing the “Get-Date -Format G” Command

The “Get-Date” cmdlet is usually used to print the current time and date of the system. In order to get the date and time on the same line, we need to specify the format with the help of the “-Format” parameter and then assign the “G” specifier.

Example

This example will demonstrate a procedure to get the date and time on the same line by executing the below command:

> Get-Date -Format G

In the stated code above:

  • Get-Date” provides the system’s current date and time.
  • -Format” parameter customizes the format of the fetched date and time.
  • Adding the “G” with the “-Format” parameter will get the date and time in the shorter format:

The output confirms that the date and time have been printed on the same line.

Method 2: Get/Retrieve the Date and Time on the Same Line in PowerShell Utilizing “(Get-Date).ToString()” Command

The “(Get-Date).ToString()” can also be utilized to print the date and time on the same line. In this method, the “Get-Date” cmdlets get the date and time first, and then the “ToString()” method converts it into the string format.

Example

Let’s print/get the time and date on the same line by executing the given command:

> (Get-Date).ToString()

As you can see, the date and time have been printed on the same line.

Conclusion

The date and time can be printed/get on the same line using two methods, including “Get-Date -Format G” and “(Get-Date).ToString()”. In the first approach, you can define the format of the date and time output, whereas the second approach fetches the date and time, convert it into a string, and then display it on the terminal. This post has presented a guide to get the date and time on the same line in PowerShell.

Share Button

Source: linuxhint.com

Leave a Reply