This small PowerShell script helps to create a new file inside the folder if file does not exist, if file exists rename it with the date and times. This logic I always use in my scripts when I want to implement logs system for my script. When the file is renamed (While creating new file) it adds date and time to old file name. This way you can have proper logging mechanism for few of my scripts.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
function Set-Log { [CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact='Medium', HelpURI='http://vcloud-lab.com' )] #[CmdletBinding( Param ( [parameter(Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)] [alias('C')] [String[]]$filePath = 'C:\Temp\XML\TextXML.xml' ) #Param Begin {} #Begin Process { if (Test-Path $filePath) { $parentPath = Split-Path -Path $filePath -Parent $fileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath) $fileExtension = [System.IO.Path]::GetExtension($filePath) $dateTime = [System.DateTime]::Now $oldFileName = "{0}\$fileName-{1}{2:d2}{3:d2}{4}{5}$fileExtension" -f $parentPath, $dateTime.Year ,$dateTime.Month, $dateTime.Day, $dateTime.ToShortTimeString().Replace(':',''), $dateTime.Millisecond Rename-Item -Path $filePath -NewName $oldFileName -Force New-Item -Path $filePath -ItemType File -Force } #if (Test-Path $filePath) else { New-Item -Path $filePath -ItemType File -Force } #else } #Process End {} #End } #function Set-Log |
Download this Set-Log script here or it also available on github.com
There is only one parameter to this PowerShell function, is FilePath which accepts complete path of file.
Useful Articles
Part 1: Powershell: Get registry value data from remote computer
Part 2: Microsoft Powershell: remotely write, edit, modify new registry key and data value
Part 3: Microsoft Powershell: Delete registry key or values on remote computer
Microsoft Powershell generate random anything (Filename, TempPath, GUID, Password)
How to Install and Use Microsoft PowerShell on Linux