Public/New-OutputFile.ps1

Function New-OutputFile {
<#
 
    .SYNOPSIS
    Function intended for preparing a PowerShell object for output files like reports or logs.
 
    .DESCRIPTION
    Function intended for preparing a PowerShell custom object what contains e.g. file name for output/create files like reports or log. The name is prepared based on prefix, middle name part, suffix, date, etc. with verification if provided path exist and is it writable.
 
    Returned object contains properties
    - OutputFilePath - to use it please check examples - as a [System.IO.FileInfo]
    - ExitCode
    - ExitCodeDescription
 
    Exit codes and descriptions
    - 0 = "Everything is fine :-)"
    - 1 = "Provided path <PATH> doesn't exist
    - 2 = Empty code
    - 3 = "Provided patch <PATH> is not writable"
    - 4 = "The file <PATH>\\<FILE_NAME> already exist - can be overwritten"
    - 5 = "The file <PATH>\\<FILE_NAME> already exist - can't be overwritten"
 
    .PARAMETER ParentPath
    By default output files are stored in the current path
 
    .PARAMETER OutputFileNamePrefix
    Prefix used for creating output files name
 
    .PARAMETER OutputFileNameMidPart
    Part of the name which will be used in midle of output file name
 
    .PARAMETER OutputFileNameSuffix
    Part of the name which will be used at the end of output file name
 
    .PARAMETER IncludeDateTimePartInOutputFileName
    Set to TRUE if report file name should contains part based on date and time - format yyyyMMdd-HHmm is used
 
    .PARAMETER DateTimePartInOutputFileName
    Set to date and time which should be used in output file name, by default current date and time is used
 
    .PARAMETER OutputFileNameExtension
    Set to extension which need to be used for output file, by default ".txt" is used
     
    .PARAMETER NamePartsSeparator
    A char used to separate parts in the name, by default "-" is used
 
    .PARAMETER BreakIfError
    Break function execution if parameters provided for output file creation are not correct or destination file path is not writables
 
    .EXAMPLE
 
    PS \> (Get-Item env:COMPUTERNAME).Value
    WXDX75
     
    PS \> $FileNeeded = @{
        ParentPath = 'C:\USERS\UserName\';
        OutputFileNamePrefix = 'Messages';
        OutputFileNameMidPart = (Get-Item env:COMPUTERNAME).Value;
        IncludeDateTimePartInOutputFileName = $true;
        BreakIfError = $true
    }
     
    PS \> $PerServerReportFileMessages = New-OutputFile @FileNeeded
 
    PS \> $PerServerReportFileMessages | Format-List
 
    OutputFilePath : C:\users\UserName\Messages-WXDX75-20151021-001205.txt
    ExitCode : 1
    ExitCodeDescription : Everything is fine :-)
     
    PS \> New-Item -Path $PerServerReportFileMessages.OutputFilePath -ItemType file
 
    Directory: C:\USERS\UserName
 
    Mode LastWriteTime Length Name
    ---- ------------- ------ ----
    -a---- 21/10/2015 00:12 0 Messages-WXDX75-20151021-001205.txt
     
    The file created on provided parameters.
    Under preparation the file name is created, provided part of names are used, and availability of name (if the file exist now) is checked.
 
    .EXAMPLE
     
    $FileNeeded = @{
        ParentPath = 'C:\USERS\UserName\';
        OutputFileNamePrefix = 'Messages';
        OutputFileNameMidPart = 'COMPUTERNAME';
        IncludeDateTimePartInOutputFileName = $false;
        OutputFileNameExtension = "csv";
        OutputFileNameSuffix = "failed"
    }
     
    PS \> $PerServerReportFileMessages = New-OutputFile @FileNeeded
 
    PS \> $PerServerReportFileMessages.OutputFilePath | Select-Object -Property Name,Extension,Directory | Format-List
 
    Name : Messages-COMPUTERNAME-failed.csv
    Extension : .csv
    Directory : C:\USERS\UserName
 
    PS \> ($PerServerReportFileMessages.OutputFilePath).gettype()
 
    IsPublic IsSerial Name BaseType
    -------- -------- ---- --------
    True True FileInfo System.IO.FileSystemInfo
     
    PS \> Test-Path ($PerServerReportFileMessages.OutputFilePath)
    False
     
    The funciton return object what contain the property named OutputFilePath what is the object of type System.IO.FileSystemInfo.
     
    File is not created. Only the object in the memory is prepared.
 
    .OUTPUTS
    System.Object[]
 
    .LINK
    https://github.com/it-praktyk/New-OutputObject
 
    .LINK
    https://www.linkedin.com/in/sciesinskiwojciech
 
    .NOTES
    AUTHOR: Wojciech Sciesinski, wojciech[at]sciesinski[dot]net
    KEYWORDS: PowerShell, File, FileSystem
 
    CURRENT VERSION
    - 0.9.4 - 2016-11-13
 
    HISTORY OF VERSIONS
    https://github.com/it-praktyk/New-OutputObject/VERSIONS.md
 
    REMARKS
    - The warning generated by PSScriptAnalyzer "Function 'New-OutputFile' has verb that could change system state.
    Therefore, the function has to support 'ShouldProcess'." is acceptable.
 
    LICENSE
    Copyright (c) 2016 Wojciech Sciesinski
    This function is licensed under The MIT License (MIT)
    Full license text: https://opensource.org/licenses/MIT
 
    #>

    
    [cmdletbinding()]
    [OutputType([System.Object[]])]
    param (
        [parameter(Mandatory = $false)]
        [String]$ParentPath = ".",
        [parameter(Mandatory = $false)]
        [String]$OutputFileNamePrefix = "Output",
        [parameter(Mandatory = $false)]
        [String]$OutputFileNameMidPart = $null,
        [parameter(Mandatory = $false)]
        [String]$OutputFileNameSuffix = $null,
        [parameter(Mandatory = $false)]
        [Bool]$IncludeDateTimePartInOutputFileName = $true,
        [parameter(Mandatory = $false)]
        [Nullable[DateTime]]$DateTimePartInOutputFileName = $null,
        [parameter(Mandatory = $false)]
        [String]$OutputFileNameExtension = ".txt",
        [parameter(Mandatory = $false)]
        [alias("Separator")]
        [String]$NamePartsSeparator = "-",
        [parameter(Mandatory = $false)]
        [Switch]$BreakIfError
    )
    
    #Declare variable
    
    [Int]$ExitCode = 0
    
    [String]$ExitCodeDescription = "Everything is fine :-)"
    
    $Result = New-Object -TypeName PSObject
    
    #Convert relative path to absolute path
    [String]$ParentPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($ParentPath)
    
    #Assign value to the variable $IncludeDateTimePartInOutputFileName if is not initialized
    If ($IncludeDateTimePartInOutputFileName -and ($null -eq $DateTimePartInOutputFileName)) {
        
        [String]$DateTimePartInFileNameString = $(Get-Date -format 'yyyyMMdd-HHmmss')
        
    }
    elseif ($IncludeDateTimePartInOutputFileName) {
        
        [String]$DateTimePartInFileNameString = $(Get-Date -Date $DateTimePartInOutputFileName -format 'yyyyMMdd-HHmmss')
        
    }
    
    #Check if Output directory exist
    If (-not (Test-Path -Path $ParentPath -PathType Container)) {
        
        [Int]$ExitCode = 1
        
        $MessageText = "Provided path $ParentPath doesn't exist"
        
        [String]$ExitCodeDescription = $MessageText
        
    }
    Else {
        
        #Try if Output directory is writable - a temporary file is created for that
        Try {
            
            [String]$TempFileName = [System.IO.Path]::GetTempFileName() -replace '.*\\', ''
            
            [String]$TempFilePath = "{0}{1}" -f $ParentPath, $TempFileName
            
            New-Item -Path $TempFilePath -type File -ErrorAction Stop | Out-Null
            
        }
        Catch {
            
            [String]$MessageText = "Provided path {0} is not writable" -f $ParentPath
            
            If ($BreakIfError.IsPresent ) {
                
                Throw $MessageText
                
            }
            Else {
                
                [Int]$ExitCode = 3
                
                [String]$ExitCodeDescription = $MessageText
                
            }
            
        }
        
        Remove-Item -Path $TempFilePath -ErrorAction SilentlyContinue | Out-Null
        
    }
    
    #Constructing the file name
    If (!($IncludeDateTimePartInOutputFileName) -and !([String]::IsNullOrEmpty($OutputFileNameMidPart))) {
        
        [String]$OutputFilePathTemp1 = "{0}\{1}{3}{2}" -f $ParentPath, $OutputFileNamePrefix, $OutputFileNameMidPart, $NamePartsSeparator
        
    }
    Elseif (!($IncludeDateTimePartInOutputFileName) -and [String]::IsNullOrEmpty($OutputFileNameMidPart)) {
        
        [String]$OutputFilePathTemp1 = "{0}\{1}" -f $ParentPath, $OutputFileNamePrefix
        
    }
    ElseIf ($IncludeDateTimePartInOutputFileName -and !([String]::IsNullOrEmpty($OutputFileNameMidPart))) {
        
        [String]$OutputFilePathTemp1 = "{0}\{1}{4}{2}{4}{3}" -f $ParentPath, $OutputFileNamePrefix, $OutputFileNameMidPart, $DateTimePartInFileNameString, $NamePartsSeparator
        
    }
    Else {
        
        [String]$OutputFilePathTemp1 = "{0}\{1}{3}{2}" -f $ParentPath, $OutputFileNamePrefix, $DateTimePartInFileNameString, $NamePartsSeparator
        
    }
    
    If ([String]::IsNullOrEmpty($OutputFileNameSuffix)) {
        
        [String]$OutputFilePathTemp = "{0}.{1}" -f $OutputFilePathTemp1, $OutputFileNameExtension
        
    }
    Else {
        
        [String]$OutputFilePathTemp = "{0}{3}{1}.{2}" -f $OutputFilePathTemp1, $OutputFileNameSuffix, $OutputFileNameExtension, $NamePartsSeparator
        
    }
    
    #Replacing doubled chars \\ , -- , .. - except if \\ is on begining - means that path is UNC share
    [System.IO.FileInfo]$OutputFilePath = "{0}{1}" -f $OutputFilePathTemp.substring(0, 2), (($OutputFilePathTemp.substring(2, $OutputFilePathTemp.length - 2).replace("\\", '\')).replace("--", "-")).replace("..", ".")
    
    
    If (Test-Path -Path $OutputFilePath -PathType Leaf) {
        
        $Answer = Get-OverwriteDecision -Path $OutputFilePath -ItemType "File"
        
        switch ($Answer) {
            
            0 {
                
                [Int]$ExitCode = 4
                
                [System.String]$MessageText = "The file {0} already exist - can be overwritten" -f $OutputFilePath.FullName
                
                [String]$ExitCodeDescription = $MessageText
                
            }
            
            1 {
                
                [Int]$ExitCode = 5
                
                [System.String]$MessageText = "The file {0} already exist - can't be overwritten" -f $OutputFilePath
                
                [String]$ExitCodeDescription = $MessageText
                
            }
            
            2 {
                
                
                Throw $MessageText
                
            }
            
            default {
                
                [System.String]$MessageText = "Unknown answer"
                
                Throw $MessageText
                
            }
            
        }
        
    }
    
    $Result | Add-Member -MemberType NoteProperty -Name OutputFilePath -Value $OutputFilePath
    
    $Result | Add-Member -MemberType NoteProperty -Name ExitCode -Value $ExitCode
    
    $Result | Add-Member -MemberType NoteProperty -Name ExitCodeDescription -Value $ExitCodeDescription
    
    Return $Result
    
}