Sunday, April 24, 2011

The 2011 Scripting Games Advanced Event 10: Use PowerShell to Create a Function to Create Temp Files

The 2011 Scripting Games Advanced Event 10: Use PowerShell to Create a Function to Create Temp Files

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


#
#
# 2011 Scripting Games Advanced Event 10: Use PowerShell to Create a Function to Create Temp Files
#
# by F.Richard 2011-04
#
#

#Requires -Version 2.0

Function CreateTempFile {
<#
.SYNOPSIS
Create temp file
.DESCRIPTION
create temp file then return filename
.PARAMETER encoding
write file in encoding format
You can use: "Unicode", "UTF7", "UTF8", "UTF32", "ASCII","BigEndianUnicode", "Default","OEM"
"Default" = ANSI format / Default parameter = "Default"
.PARAMETER notepad
display temp file in notepad after creation
.EXAMPLE
"hahaha" | CreateTempFile
write "hahaha" in a temp file and return filename
.EXAMPLE
"hohoho" | CreateTempFile -notepad
write "hohoho" in a temp file and display it in notepad then return filename
.EXAMPLE
dir C:\ | CreateTempFile -encoding unicode
write directory of c:\ in a temp file in unicode format then return filename
#>
Param(
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeLine = $true)]
[psobject] $inputdata,

[Parameter(Mandatory = $false, Position = 1)]
[ValidateSet("Unicode", "UTF7", "UTF8", "UTF32", "ASCII","BigEndianUnicode", "Default","OEM")]
[string] $Encoding="Default",

[Parameter(Mandatory = $false, Position = 2)]
[switch]$notepad,
[Switch]$Whatif
)

# temp file name
# use windows IO function but can use %temp%\(get-date).ToString('yyyyMMdd')
$tempfile = [System.IO.Path]::GetTempFileName()

# create temp file
Write-Debug "Create Temp file $tempFile"
Write-Verbose "Create Temp file $tempFile"
if ($Whatif) {
Write-Host "What if: Create Temp file $tempFile"
} else {
Out-File -filePath $tempFile -InputObject $inputdata -Encoding unicode
}

# open temp file in notepad if switch
if ($notepad) {
Write-Debug "Open file $tempFile in notepad"
Write-Verbose "Open file $tempFile in notepad"
if ($Whatif) {
Write-Host "What if: Open file $tempFile in notepad"
} else {
Notepad $tempFile | Out-Null
}
}

# return temp filename
Write-Debug "return tempfile name"
Write-Verbose "return tempfile name"
if ($Whatif) {
Write-Host "What if: return $tempFile"
return
} else {
return $tempfile
}
}

No comments: