Average Rating:

5.00 by 2 users.

32 Downloads, 67 Views

advanced10.ps1

By: Tim Parkinson 20 Apr 2011 06:01 PM UTC in the category: Advanced Event 10

Description:

An advanced function which creates the log file and writes out to it. By default uses temporary folder of the user, and a GUID as the filename with a .txt extension. All of these may be overridden by parameters (including a scriptblock to generate the filename). Supports encoding and whatif, verbose and debug parameters. Allows display of the program in notepad (may be overridden) and returns the filename that is written to.
function Out-TemporaryFile
{
<#
.SYNOPSIS
   Creates a new temporary file with the content specified.
.DESCRIPTION
   Creates a new temporary file with the content specified, and returns the path to the file.

   By default, creates the file in the temporary folder as specified by $env:TEMP.
   This behaviour may be overridden using the -Path parameter. Will generate the filename
   parameter using a GUID, with a .txt extension. The generation of the filename may be overridden
   by specification of the -Filename parameter, which may be a code block.
   The extension may also be overridden by use of the -Extension parameter.

   Optionally the function will display the file in Notepad (or other specified viewer), and supports 
   different encoding via the -Encoding parameter.
.PARAMETER InputObject
    The content to be written to the file.
.PARAMETER Temporary
    A switch determining whether to use a temporary file. Default is true and cannot be used in conjunction
    with the Path switch.
.PARAMETER Path
    The path to a folder which should be used to create the temporary file.
.PARAMETER Filename
    A filename to use for the temporary file. May be a string or a ScriptBlock which will generate the filename.
.PARAMETER Extension
    The file extension to use for the temporary file. Default is '.txt'.
.PARAMETER Display
    A switch which determines whether to display the file. Default display program is Notepad, which may be 
    overridden by use of the -DisplayProgram parameter.
.PARAMETER DisplayProgram
    The name (if in the executable PATH) or path of a program to execute for display of the temporary file. 
    Defaults to 'notepad.exe'.
.PARAMETER Encoding
    Specify the encoding to be used by the file. Valid values are: "Unicode", "UTF7", "UTF8", "UTF32", "ASCII", "BigEndianUnicode", "Default", "OEM".
.PARAMETER NoClobber
    Will not over-write a pre-existing file.
.EXAMPLE
    Out-TemporaryFile "banana"
    
    Details
    -------
    Writes the specified string to a temporary file in the temporary directory with a GUID generated filename.
.EXAMPLE
    Get-Process | Out-TemporaryFile
    
    Details
    -------
    Illustrates piping the output of a command, which will generate output in a temporary directory with GUID generated filename.
.EXAMPLE
    Out-TemporaryFile -Path "c:\" "banana"
    
    Details
    -------
    Generates the temporary file in the specified path (C:\)
.EXAMPLE
    Out-TemporaryFile -Filename "banana" "banana"
    
    Details
    -------
    Uses the filename banana for the temporary file
.EXAMPLE
    Out-TemporaryFile -Filename {0..9 | % {$f +=$_.ToString()};$f}
    
    Details
    -------
    Illustrates the use of a code block for generation of the temporary filename.
.EXAMPLE
    Get-Process | Out-TemporaryFile -Extension ".log" -Display
    
    Details
    -------
    Generates a temporary file with extension '.log' and displays it in notepad.exe.
.EXAMPLE
    Get-Process | Out-TemporaryFile -Extension ".log" -Display -DisplayProgram "MyViewer.exe -file "     

    Details
    -------
    Illustrates how to use the function to open a viewer other than notepad.exe.
.EXAMPLE
    Get-Process | Out-TemporaryFile -Filename "processes" -Encoding "ASCII" -NoClobber
    
    Details
    -------
    Generates a log of the processes to the filename processes.txt using ASCII encoding. If the file already exists, the function will error.
.NOTES
    Tim Parkinson's entry for the advanced event 10 of the 2011 Scripting Games.
    
    Standard:
    Advanced function, comment based help
    Accepts piped content
    Returns path to the created file
    Can create files with temporary names in the temporary folder (default)
    
    Extra:
    Switch to allow display
    Supports encoding
    Supports whatif, debug and verbose
    
    Extra-extra:
    Optionally allows specification of the path
    Optionally allows specification of a filename, or scriptblock to generate a filename
    Allows override of the program used to display the file
    Supports a NoClobber parameter
#>

    [CmdletBinding(SupportsShouldProcess=$true,DefaultParametersetName='temp_folder')]
    param(
       [Parameter(
           Mandatory=$true,
           Position=1,
           ValueFromPipeline=$true
       )]
       $InputObject,
       [Parameter(
           Mandatory=$false,
           Position=2,
           ParameterSetName='temp_folder'
        )]
        [switch]$Temporary=$true,
        [Parameter(
           Mandatory=$false,
           Position=2,
           ParameterSetName='named_path'
        )]
        $Path,
        [Parameter(
           Mandatory=$false,
           Position=3
        )]
        $Filename,
        [Parameter(
           Mandatory=$false,
           Position=4
        )]
        $Extension='.txt',
        [Parameter(
           Mandatory=$false,
           Position=5
        )]
        [switch]$Display=$false,
        [Parameter(
           Mandatory=$false,
           Position=6
        )]
        [string]$DisplayProgram="notepad.exe",
        [Parameter(
           Mandatory=$false,
           Position=7
        )]
        [string]
        [ValidateSet("Unicode", "UTF7", "UTF8", "UTF32", "ASCII", "BigEndianUnicode", "Default", "OEM")]
        $Encoding='Unicode',
        [Parameter(Mandatory=$false)]
        [switch]$NoClobber
    )

    begin
    {
        # Because file content is expected on the pipeline, setup of the file occurs here
        # Determine the path to the temporary file.
        # Check whether temporary folder to be used
        if ($Temporary)
        {
            Write-Debug "Using temporary path"
            $Path = $env:TEMP            
        } else {
            # A path has been specified, make sure it exists
            Write-Debug "-Path $Path specified"
            if (-not (Test-Path $Path))
            {
                throw "Specified path $Path does not exist"
                return
            }
        }
        
        Write-Debug "Using Path $Path"
        Write-Verbose "Using Path $Path"
        
        # Get the filename without the extension
        # Was an argument passed?
        if ($Filename)
        {
            # A filename argument passed, so determine whether it's a string or a scriptblock
            # if it's something else then throw an error
            Write-Debug "-Filename $Filename specified"
            switch ($Filename.GetType())
            {
                "String"
                {
                    # Just use as is
                    Write-Debug "-which is a string"
                    break
                }
                "ScriptBlock"
                {
                    # Execute the scriptblock to determine the filename
                    Write-Debug "-which is a scriptblock"
                    $Filename = &$Filename
                    break
                }
                default
                {
                    throw "Filename should be a String or ScriptBlock"
                    return
                }  
            }          
        } else {
            # The Filename parameter was null, so generate a guid
            Write-Debug "Using a GUID for filename"
            $Filename = ([guid]::NewGuid()).ToString()
        }
        
        Write-Debug "Using Filename $Filename"
        Write-Verbose "Using Filename $Filename"
        
        # Make sure that the extension has a leading '.'
        if (-not ($Extension -match "^\."))
        {
            Write-Debug "Adding leading '.' to file extension"
            $Extension = ".$Extension"
        }
        
        Write-Debug "Using Extension $Extension"
        Write-Verbose "Using Extension $Extension"
        
        # Put the path, filename and extension together
        $full_path = Join-Path $Path "$Filename$Extension"
    
        Write-Debug "Using Full Path $full_path"
        Write-Verbose "Using Full Path $full_path"
        
        # If Noclobber is set and the file already exists, throw an error
        if ($NoClobber -and (Test-Path $full_path))
        {
            throw "File exists and NoClobber specified"
            return
        }
    }

    process
    {
        Write-Debug "Writing to $full_path"
        Write-Verbose "Writing to $full_path"
        if($pscmdlet.ShouldProcess($full_path, "Writing $InputObject"))
        {
            out-file -FilePath $full_path -Encoding $Encoding -InputObject $InputObject -Append
        }
    }

    end
    {
        
        # If required display the output 
        if ($Display)
        {
            Write-Debug "-Display specified"
            if ($pscmdlet.ShouldProcess($full_path, "Displaying in $DisplayProgram"))
            {
                Write-Verbose "Displaying"
                Write-Debug "Displaying in $DisplayProgram"
                Invoke-Expression "$DisplayProgram $full_path"
            }
        }
        
        # Return the file path
        Write-Debug "Returning path $full_path"
        Write-Output $full_path
    }
}
Top

Comments: