Microsoft Secure Tech Accelerator
Apr 03 2024, 07:00 AM - 11:00 AM (PDT)
Microsoft Tech Community
Library - Function New-LogFile
Published May 15 2019 03:03 PM 210 Views

First published on TECHNET on Mar 01, 2012

So working with a customer on a bunch of scripts to manipulate SharePoint and we needed a standard method of logging what we were doing in our scripts.  So I decided to write a few functions that would make our life easier and would create uniformity in how things are logged.


So the first function I wrote simply creates a new logfile, and I wrote it so that if you wanted to all you would have to do is call the function, this means that both parameters have default values and of course it will return the full path and name of your log file.  I did several things to make this work nicely

    1. Using Get-Date I extract the day, month, year, hour, minute, and second and use them in the file name so that you can be basically guaranteed to not overwrite your other logs files.

    1. As well  I use a prefix on the filename that you can customize so that if you put all your logs in the same folder it will be easy to find the specific log your looking for.

    1. Then I get the folder that you want to place the log into, if the folder doesn't exist I will create it.

    1. And lastly I use New-Item to create the blank file with an extension .log



function New-Logfile




param([String]$LogPath = "C:\Script", [string]$PreFix = "ScriptOutput")


$d = Get-Date


$Day = $d.Day


$Month = $d.Month


$Year = $d.Year


$Hour = $d.Hour


$Min = $d.Minute


$Sec = $d.Second


if(!(Test-Path -Path $LogPath -PathType Container))




New-Item -Path $LogPath -ItemType Directory | Out-Null




$FileName = New-Item -Path "$LogPath\$PreFix$Day$Month$Year$Hour$Min$Sec.log" -ItemType File -Force


return $FileName.FullName






If you would like to check out the function you can download it from here

Version history
Last update:
‎Apr 28 2020 02:43 PM
Updated by: