PowerShell tips and tricks

root's picture

How to remove the contents from a File:

Note: this does not removes the file. It only clears the content, which is very useful if you want to clear a log on which an application writes continuously. This will ensure the filesystem's space is cleared (especially when cleaning huge logs) and the log is still accessible by the application.
PS C:\> Clear-Content file

Example:
PS C:\Users\tempuser\OpenVPN\log> ls


    Directory: C:\Users\tempuser\OpenVPN\log


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       12/27/2016   8:36 PM           1438 config.log
-a----        2/24/2018   3:56 PM           [color=red]1506[/color] core.log


PS C:\Users\tempuser\OpenVPN\log> [color=green]Clear-Content core.log[/color]
PS C:\Users\tempuser\OpenVPN\log> ls


    Directory: C:\Users\tempuser\OpenVPN\log


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       12/27/2016   8:36 PM           1438 config.log
-a----        3/16/2018   8:17 PM              [color=red]0[/color] core.log

How to do the equivalent of Linux's “tail -f” in PowerShell:

Note: the option -tail 10 shows only the last 10 lines from the file before showing what is new.
If you do not put this, the command will show first ALL lines. Be careful on huge files when not using this option.

PS C:\> Get-Content file -tail 10 -wait

How to display the current username in PowerShell:

PS C:\> $env:username
whatever

How to display the computer name in PowerShell:

PS C:\Users\whatever> $env:computername
THEWINDOWS

Thou shalt not steal!

If you want to use this information on your own website, please remember: by doing copy/paste entirely it is always stealing and you should be ashamed of yourself! Have at least the decency to create your own text and comments and run the commands on your own servers and provide your output, not what I did!

Or at least link back to this website.

Recent content

root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root
root