Average Rating:

3.00 by 2 users.

26 Downloads, 69 Views

Advanced10_2011.ps1

By: Jason Scott 18 Apr 2011 02:12 AM UTC in the category: Advanced Event 10

################################################################################
# Advanced10_2011.ps1
# Author: Jason Dale Scott <jason.dale.scott@gmail.com>
# Date  : April 15, 2011
# 2011 Scripting Games, Advanced Event #10
################################################################################
#requires -Version "2.0"
Set-StrictMode -Version "2.0"

Function Out-TempFile
{
    [CmdLetBinding(SupportsShouldProcess=$True,ConfirmImpact="Medium",DefaultParameterSetName="Default")]
    Param(
        [Parameter(Mandatory=$True,ValueFromPipeLine=$True,Position=0)]
        [PSObject]
        $InputObject,
        
        [Parameter(Mandatory=$False)]
        [Alias("show","display")]
        [Switch]
        $DisplayFile,
        
        [Parameter(Mandatory=$False)]
        [ValidateSet("Unicode","UTF7","UTF8","UTF32","ASCII","BigEndianUnicode","Default","OEM")]
        [String]
        $Encoding = "Unicode"
    )
    
    BEGIN
    {
        Write-Verbose ("Started execution at: {0}." -f (Get-Date).ToString())
    
        function Get-TempFileName
        {
            #Generate a name for the temp file using the current process ID and a random number
            $TempFileName = "TEMP-{0}-{1}.tmp" -f $PID, (Get-Random)
            
            Write-Verbose ("Generated temp file name: {0}." -f $TempFileName)
            Write-Debug   ("Generated temp file name: {0}." -f $TempFileName)
            
            #Return the full path of the proposed temp file including the
            #temp directory from the environment
            Write-Output ("{0}\{1}" -f $env:tmp, $TempFileName)
        }
        
        #Generate a temp file name
        $TempFileFullPath = Get-TempFileName 
        
        $Counter = 1
        Write-Debug "Checking for temp file uniqueness."
        
        #If the file name that we generated alredy exists, continue generating
        #new ones untill we find one that doesn't. Exit after 100 attempts.
        While( Test-Path $TempFileFullPath )
        {
            Write-Debug ("File name '{0}' is not unique, generating a new name." -f $TempFileFullPath)
            
            #Generate a new temp file name
            $TempFileFullPath = Get-TempFileName
            
            #If we've done this 100 times already, throw an error and quit.
            if ( $Counter -ge 100 ) { Throw "Unable to find a unqiue temp file name."; exit }
            $Counter++
        }
        
        #Create an array to hold all of the objects that we're going to output
        #to the temp file. We'll store them here and write them in the END block.
        #If we write them out during the PROCESS block, any collections will get
        #unrolled and be very ugly.
        $OutputObject = @()

    }
    
    PROCESS
    {
        #Add the current object to our output colleciton
        #This is to prevent collections received on the pipeline
        #from being unrolled
        $OutputObject += $_
    }
    
    END
    {
        #Write the final OutputObject collection to the temp file
        #Out-File will inherit the -confirm and -whatif parameters and prompt
        #the user as appropriate.
        $OutputObject | Out-File -FilePath $TempFileFullPath -Encoding $Encoding

        
        #Make sure the file exists before we try to open it or show it's path
        #if we were run with -whatif or -confirm and then cancelled, the file
        #won't exist
        if ( Test-Path $TempFileFullPath )
        {
            if ( $DisplayFile )
            {
                #Open the file up in notepad if the use provided the -DisplayFile paramter
                Write-Verbose ("Opening {0} in notepad." -f $TempFileFullPath)
                Invoke-Expression "Notepad.exe `"$TempFileFullPath`""
            }
            
            #The requirements asked that the function output the path to the temp file.
            #I'd rather pass along an object than a string.  The file and folder name are
            #displayed in the default output for the System.IO.FileInfo object, and the
            #FullName property can be used to access the full pathname of the file if needed.
            Write-Output (Get-Item $TempFileFullPath)
        }
   }
    
<#
.SYNOPSIS
Writes data to a temporary file.


.DESCRIPTION
The Out-TempFile function sends output to a temporary file.  The temporary
file name is automatically generated and is returned to the caller.

The location for the temporary file is the TMP location specified in the
current environment.

The filename takes the format TEMP-<process PID>-<random number>.tmp


.PARAMETER Encoding
Specifies the type of character encoding used in the file. Valid values
are "Unicode","UTF7", "UTF8", "UTF32", "ASCII", "BigEndianUnicode",
"Default", and "OEM". "Unicode" is the default.

"Default" uses the encoding of the system's current ANSI code page.

"OEM" uses the current original equipment manufacturer code page
identifier for the operating system.


.PARAMETER InputObject
Specifies the objects to be written to the temporary file. Enter a
variable that contains the objects or type a command or expression
that gets the objects.


.PARAMETER DisplayFile
Opens the temporary file for viewing using the Notepad text editor.


.INPUTS
System.Management.Automation.PSObject
    You can pipe any object to Out-TempFile


.OUTPUTS
System.IO.FileInfo
    An object representing the newly created temporary file


.EXAMPLE
    Get-Process | Out-TempFile


    Directory: C:\Users\Jason Scott\AppData\Local\Temp

    Mode                LastWriteTime     Length Name
    ----                -------------     ------ ----
    -a---        17/04/2011  10:04 PM      66954 TEMP-12032-1149144463.tmp


    
    Description
    -----------
    This command sends a list of processes on the computer to the   
    TEMP-12032-1149144463.tmp file in the user's temporary folder.

#>    
    

}
Top

Comments: