Sunday, April 24, 2011

The 2011 Scripting Games Advanced Event 9: Use PowerShell to Create a File Name Based on Date and Username

The 2011 Scripting Games Advanced Event 9: Use PowerShell to Create a File Name Based on Date and Username

My personal script:
http://2011sg.poshcode.org/1781
Average Rating: 3.00 by 2 users.
(Download it)


#
#
# 2011 Scripting Games Advanced Event 9: Use PowerShell to Create a File Name Based on Date and Username
#
# by F.Richard 2011-04
#
#

#Requires -Version 2.0

Param(
[Parameter(Mandatory = $false, Position = 0, ValueFromPipeLine = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[String] $string = "My log",

[Parameter(Mandatory = $false, Position = 1)]
[ValidateNotNullOrEmpty()]
[String] $foldername = "HSGLogFiles",

[Parameter(Mandatory = $false, Position = 2)]
[ValidateNotNullOrEmpty()]
[switch] $mydoc
)

<#
.SYNOPSIS
Create log file
.DESCRIPTION
create filename (YYYYMMDD_username.log) in
.PARAMETER string
String to write Default: "My log"
.PARAMETER foldername
Folder name to write Default: "HSGLogFiles"
.PARAMETER path
path where write foldername Default: "CommonApplicationData"
.PARAMETER mydoc
switch to write in my document's directory / replace path folder
.EXAMPLE
CreateLogFile
write file C:\ProgramData\HSGLogFiles\20110420_franck.log
(if we are april 20 2011 and my username is franck in Windows 7)
.EXAMPLE
CreateLogFile -mydoc
write file %userprofile%\Documents\HSGLogFiles\20110420_franck.log
(if we are april 20 2011 and my username is franck)
#>



# if switch mydoc write directory on my document's folder
if ($mydoc) {
$path = [Environment]::GetFolderPath("MyDocuments") + "\" + $foldername
} else {
$path = [Environment]::GetFolderPath("CommonApplicationData") + "\" + $foldername

}


# Create directory if not already exist
if (!(Test-Path -path $path)) {
New-Item $path -type directory | Out-Null
}


# create filename (YYYYMMDD_username.log) if not already exist
$filename = (get-date).ToString('yyyyMMdd') + "_" + ($env:USERNAME) + ".log"
If ((Test-Path("$path\$filename")) -eq $False){
"Log file" | Out-File "$path\$filename"
}

No comments: