New-DummyFile.ps1


<#PSScriptInfo
 
.VERSION 19.05.25
 
.GUID e8b387f4-cea3-4bf3-86e0-613aacea239a
 
.AUTHOR Tim Small
 
.COMPANYNAME Smalls.Online
 
.COPYRIGHT 2019
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
Initial Release
 
.PRIVATEDATA
 
#>


<#
 
.DESCRIPTION
 Generate a dummy file for testing.
 
#>
 
[CmdletBinding(SupportsShouldProcess)]
param(
    [ValidateNotNull()][string]$Path = "./Dummy.File",
    [ValidateNotNull()][int64]$FileSize = 100MB
)

begin {

    function convertFileSize {
        param(
            $bytes
        )
    
        if ($bytes -lt 1MB) {
            return "$([Math]::Round($bytes / 1KB, 2)) KB"
        }
        elseif ($bytes -lt 1GB) {
            return "$([Math]::Round($bytes / 1MB, 2)) MB"
        }
        elseif ($bytes -lt 1TB) {
            return "$([Math]::Round($bytes / 1GB, 2)) GB"
        }
        elseif ($bytes -lt 1PB) {
            return "$([Math]::Round($bytes / 1TB, 2)) GB"
        }
    }

    try {
        $PathRegex = [regex]::Matches($Path, "(?:(?'folderPath'.+[\/\\])(?:(?'fileName'.+)|)|.+)")
        $PathTable = @{
            "FolderPath" = (Get-Item -Path ($PathRegex.Groups | Where-Object -Property "Name" -eq "folderPath").Value -ErrorAction Stop);
            "FileName"   = ($PathRegex.Groups | Where-Object -Property "Name" -eq "fileName").Value
        }
    }
    catch {
        $ErrorDetails = $_

        throw $ErrorDetails
    }

    Write-Verbose "Folder Path: '$($PathTable['FolderPath'].FullName)'"
    Write-Verbose "Filename: '$($PathTable['FileName'])'"

    $FullPath = Join-Path -Path $PathTable['FolderPath'] -ChildPath $PathTable['FileName']
    Write-Verbose "Dummy File Path: '$($FullPath)'"

}

process {

    if ($PSCmdlet.ShouldProcess($FullPath, "Create dummy file")) {
        $TmpFile = New-TemporaryFile

        $FileObj = [System.IO.File]::Create($TmpFile)
        $FileObj.SetLength($FileSize)
        $FileObj.Close()

        Move-Item -Path $TmpFile -Destination $FullPath

        $DummyFileItem = Get-Item -Path $FullPath

        return [pscustomobject]@{
            "Directory" = $DummyFileItem.Directory;
            "FileName"  = $DummyFileItem.Name;
            "FileSize"  = (convertFileSize -Bytes $DummyFileItem.Length)
        }
    }
}