Average Rating:

5.00 by 2 users.

54 Downloads, 201 Views

1 Comment(s)

New-TemporaryFile

By: Boe Prox 22 Apr 2011 02:37 AM UTC in the category: Advanced Event 10

Description:

In at the last minute...kind of like last year. This command takes the original requirements of creating a temp file on the user's temp folder that accepts data from the pipeline if used and supports whatif,verbose and debug. After creation of the file, the file path and name is displayed. An option to open the file can be performed using the -DisplayFile switch. In its default state, you can run the command and it will automatically generate a file and save it to your temp folder. Because I felt that was sort of a limited feature, I added the ability to state your own destination path and file if needed. An additional feature is that if the folder path does not exist at the time, the folders will automatically be created for you. Also added is the option to determine what type of encoding you wish to use using the -Encoding parameter and supplying the proper encoding name. When added to a profile, this function will be visible for use.
Function New-TemporaryFile {
<#   
.SYNOPSIS   
   Script to create a file in a specified location and add sub-folders
   if needed to satisfy directory input.
   
.DESCRIPTION 
   Script to create a file in a specified location and add sub-folders if needed
   to satisfy directory input. If the log file already exists in the location
   specified, then the log file will not be create or overwritten. If logfile and directory
   are not provided, then the command will generate a random file and save to the user's temp
   folder.

.PARAMETER LogFile 
    Optional Name of logfile to create. 
    
.PARAMETER Directory 
    Optional Directory to store logfile. Command will recursivly create sub-folders as needed to create full path. 
    
.PARAMETER Data
    Allows for optional data that can be written to the log file upon creation.

.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.

.PARAMETER DisplayFile
    Opens the newly created file in notepad to view data.
    
.NOTES   
    Name: New-TemporaryFile
    Author: Boe Prox 
    DateCreated: 21April2011  
    
.EXAMPLE   
    New-LogFile
    
    File created on: C:\Users\boe\AppData\Local\Temp\tmpE2C.tmp
 
Description 
-----------     
By not specifying a logfile or directory name, the command will generate a random file and save
the file to the user's temp folder.

.EXAMPLE   
    "This is some data" | New-LogFile
    
    File created on: C:\Users\boe\AppData\Local\Temp\tmpE5T.tmp

.EXAMPLE  
    New-TemporaryFile -Encoding ASCII -Data "Random text"
    
    File created on: C:\Users\boe\AppData\Local\Temp\tmpT5Y.tmp
 
Description 
-----------     
Creates a randomly generated logfile at the user's temp folder with specified text added to the
file using ASCII encoding.    
 
Description 
-----------     
By not specifying a logfile or directory name, the command will generate a random file and save
the file to the user's temp folder with the added data inside the file.

.EXAMPLE   
    New-LogFile -Logfile newlog.txt
    
    File created on: C:\Users\boe\AppData\Local\Temp\newlog.txt

Description 
-----------     
Creates a logfile based on user specification in the user's temp folder.   
    
.EXAMPLE  
    New-TemporaryFile -Encoding ASCII -Data "Random text" -DisplayFile
    
    File created on: C:\Users\boe\AppData\Local\Temp\tmpT5Y.tmp
 
Description 
-----------     
Creates a randomly generated logfile at the user's temp folder with specified text added to the
file using ASCII encoding. By using the DisplayFile switch, the file will be opened in notepad
after created.
 
Description 
-----------     
This command will create, if needed the temp\logs folder path and then create the newlog.txt file.

.EXAMPLE 
    $currentdate = Get-Date -UFormat %Y%m%d  
    New-TemporaryFile -Directory C:\logs -Logfile "$($currentdate)log.txt"
    
    File created on: C:\logs\20110421log.txt
 
Description 
-----------     
Creates a logfile named 20110415_log.txt in C:\logs. If the logs folder does not exist,it will be created.

.EXAMPLE 
    $data = "$(Get-Date): $Env:Username logged into $Env:Computername"
    $currentdate = Get-Date -UFormat %Y%m%d  
    New-TemporaryFile -Directory C:\logs -Logfile "$($currentdate)log.txt" -Data $data
    
    File created on: C:\logs\20110421log.txt
 
Description 
-----------     
Creates a logfile named 20110415_log.txt in C:\logs that contains some logging information. If the logs folder does
 not exist,it will be created.

#>  

[cmdletbinding( 
    ConfirmImpact = 'low',
    SupportsShouldProcess = 'True',
    DefaultParameterSetName = 'Random' 
    )] 
    
Param( 
    [Parameter( 
        Position = 1,ParameterSetName = 'UserInput')] 
        [string]$LogFile,
    [Parameter( 
        Position = 2,ParameterSetName = 'UserInput')] 
        [string]$Directory,
    [Parameter( 
        Position = 3,ValueFromPipeLine = "True")] 
        [string]$Data,
    [Parameter( 
        Position = 4)]
        [ValidateSet("Unicode", "UTF7", "UTF8", "UTF32","ASCII", "BigEndianUnicode", "Default","OEM")] 
        [string]$Encoding,
    [Parameter( 
        Position = 5)] 
        [Switch]$DisplayFile        
    ) 


Begin {
    Write-Verbose "Creating hash table to store parameters"
    $SplatTable = @{}
    <#
    Depending on the user parameter selection, either a randomly generated temp file will be created in the temp folder if nothing is selected,
    or the script will use the user provided information for the directory and file.
    #>
    Switch ($PScmdlet.ParameterSetName) {
        'Random' {
            Write-Verbose "Creating a randomly generated temp file"
            $splattable['FilePath'] = [system.io.path]::GetTempFileName()
            Write-Debug "$($splattable['FilePath'])"
            }
        'UserInput' {
            #Build complete path and file string
            Write-Verbose "Building full path to file and storing in hash table based on user input"
            If ($PSBoundParameters['Directory']) {
                #perform a check to see if a full path was given or not,otherwise issues will arise
                Write-Verbose "Testing to see if given a full path or just a folder name to create"
                If ($directory -match "^\w{1}:\\\w?") {
                    Write-Verbose "Using given path"
                    Write-Debug "Directory: $directory"
                    }
                Else {
                    Write-Verbose "Appending directory to current path"
                    $Currentdirectory = Get-Location  | Select-Object -ExpandProperty Path
                    $directory = "$currentdirectory\$directory"
                    Write-Debug "Folder: $directory" 
                    }      
                }
            Else {
                Write-Verbose "Using User's temp directory"
                $directory = $Env:Temp
                Write-Debug "Folder: $directory"          
                }
            If ($PSBoundParameters['logfile']) {
                #User user specified logfile name
                Write-Verbose "Adding FilePath to hash table"
                $splattable['FilePath'] = "$directory\$logfile"
                Write-Debug "FilePath: $directory\$logfile"
                }
            Else {
                #Use a hard-coded file temp file name
                Write-Verbose "Adding FilePath to hash table"
                $splattable['FilePath'] = "$directory\TempFile.txt"
                Write-Debug "FilePath: $directory\TempFile.txt"
                }            
            }
        }
    If ($PSBoundParameters['Encoding']) {
        Write-Verbose "Adding Encoding to hash table"
        $SplatTable['Encoding'] = $Encoding
        Write-Debug "Encoding: $encoding"
        }
    #Set error action to Stop to trap any errors
    Write-Verbose "Setting ErrorAction to: Stop"
    $splatTable['ErrorAction'] = 'Stop'
}

Process {
    <#
    Perform the check for data during the Process, otherwise it will be skipped when
    being passed through the pipeline if checked at the Begin statement.
    #>
    If ($PSBoundParameters['Data']) {
        Write-Verbose "Adding Data to hash table"
        $SplatTable['InputObject'] = $Data
        Write-Debug "Data: $data"
        }
    #Ensure that the CompleteFolder variable has nothing currently saved to it
    $CompleteFolder = $Null
    #Test for Specified Folder if given by user
    If (Get-Variable Directory -ErrorAction SilentlyContinue) {
        Write-Verbose "Begin testing the folder path: $Directory"
        ForEach ($folder in $Directory -split "\\") {
            If ($folder -ne "") { 
                Write-Verbose "Testing $Folder"
                #Add the current folder into variable for testing  
                $CompleteFolder = $CompleteFolder + ($Folder + "\")
                Write-Debug "CompleteFolder: $completefolder"
                #Test the folder path
                If (-Not (Test-Path $CompleteFolder)) {
                    Try {
                        Write-Verbose "Creating Folder: $Folder"
                        If ($pscmdlet.shouldprocess($Folder)) {
                            New-Item -Path $Currentpath -Name $Folder -ItemType Directory -ErrorAction Stop | Out-Null
                            }
                        }
                    Catch {
                        Write-Verbose "$($Error[0])"
                        Break
                        }
                    #Add to current path variable to assist in building a new folder if needed
                    Write-Debug "Completefolder $completefolder"
                    $currentpath = $CompleteFolder
                    }
                Else {
                    #Add to current path variable to assist in building a new folder if needed
                    Write-Debug "Completefolder $completefolder"
                    $currentpath = $CompleteFolder
                    }
                }
            }
        }
    #Test for file
    Write-Verbose "Testing for log file existence"
    If (Test-Path $splattable['FilePath']) {
        Try {
            #Create the new file
            Write-Verbose "Creating new log file with data"
            If ($pscmdlet.shouldprocess($($splattable['FilePath']))) {
                Out-File @SplatTable
                } 
            } 
        Catch {
            Write-Verbose "$($Error[0])"
            Break
            }
        }
    Else {
        Try { 
            #Create the new file
            Write-Verbose "Creating new log file with data"
            If ($pscmdlet.shouldprocess($($splattable['FilePath']))) {
                Out-File @SplatTable
                }        
            }
        Catch {
            Write-Verbose "$($Error[0])"
            Break
            }
        }
    }
End {
    If ($PSBoundParameters['DisplayFile']) {
        Write-Verbose "Opening $($splattable['FilePath']) in notepad"
        Write-Host -ForegroundColor Green "File created on: $($splattable['FilePath'])"
        Start-Process -FilePath NotePad.exe -ArgumentList $splattable['FilePath']
        }
    Else {
        #Display path and file
        Write-Host -ForegroundColor Green "File created on: $($splattable['FilePath'])"
        }       
    }
}
Top

Comments:

4/22/2011 4:09 AM
Wow ... excellent script. I like your use of parameters, and extensive help. Did you use splatting? I see you learned something at the PowerShell Deep dive! I also have several articles on Hey Scripting Guy! blog written by James B. about splatting as well. Their use really simplifies things and makes for cleaner code. Dude, you rock!!!