Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fileSystem.file.info.ps1
param ( `
[Parameter(Mandatory = $true)] `
[string] $file`
)
<#
Establishes and enforces coding rules in expressions, scripts, and script blocks.
#>
Set-StrictMode -Version latest
<#
Declare Variables
#>
[string] $log = "";
[Boolean] $bFileExistence = $false;
[System.IO.FileInfo] $objFileInfo = $null;
[long] $fileSizeInBytes =0;
[string] $fileSizeAsString="";
[string] $FORMAT_FILE_FILENAME_NOT_SPECIFIED = "";
[string] $FORMAT_FILE_DOES_NOT_EXISTS = "";
[string] $FORMAT_FILE_OPERATION = "";
[string] $FORMAT_FILE_SIZE = "";
[string] $FORMAT_FILE_SIZE_AND_METRIC = "";
<#
Set global variables
#>
$FORMAT_FILE_FILENAME_NOT_SPECIFIED = "File not specified";
$FORMAT_FILE_DOES_NOT_EXISTS = "File ( {0} ) does not exist!";
$FORMAT_FILE_OPERATION = "Reviewing file:- {0}";
$FORMAT_FILE_SIZE = "`t File Size: {0}";
$FORMAT_FILE_SIZE_AND_METRIC = "`{0:n3} {1}";
function beautifyFileSize{
param
(
[Parameter(Position=0)]
[long] $fileSizeInBytes
, [Parameter(Position=0)]
[ref]$result
)
[double] $fileSize = 0;
if ($fileSizeInBytes -gt 1E9 )
{
$fileSize = $fileSizeInBytes / ( 1024 * 1E6 );
$result.value = $FORMAT_FILE_SIZE_AND_METRIC -f $fileSize, "GB";
}
elseif ($fileSizeInBytes -gt 1E6 )
{
$fileSize = $fileSizeInBytes / ( 1024 * 1E3 );
$result.value = $FORMAT_FILE_SIZE_AND_METRIC -f $fileSize, "MB";
}
elseif ($fileSizeInBytes -gt 1E3 )
{
$fileSize = $fileSizeInBytes / 1E3;
$result.value = $FORMAT_FILE_SIZE_AND_METRIC -f $fileSize, "KB";
}
else
{
$result.value = $FORMAT_FILE_SIZE_AND_METRIC -f $fileSizeInBytes, "Bytes";
}
}
try
{
Write-Host "";
<#
If file is not specified, raise an exception
#>
if ( ($file -eq $null) -or ($file -eq "") )
{
$log = $FORMAT_FILE_FILENAME_NOT_SPECIFIED;
throw [System.ArgumentNullException] $log
}
$log = $FORMAT_FILE_OPERATION -f $file;
Write-Host $log;
<#
Using Test-Path, determine if file exists
#>
$bfileExistence = Test-Path -LiteralPath $file -PathType Leaf;
<#
If Specified File does not exist!
#>
if (
( $bfileExistence -eq $false )
)
{
$log = $FORMAT_FILE_DOES_NOT_EXISTS -f $file;
throw [System.IO.FileNotFoundException] $log
}
<#
Get File
#>
$objFileInfo = get-item -LiteralPath $file;
<#
Get File Length
#>
$fileSizeInBytes = $objFileInfo.Length;
<#
Beautify File Size
#>
beautifyFileSize `
-fileSizeInBytes ( $fileSizeInBytes ) `
-result ([ref] $fileSizeAsString)
<#
Display File Size
#>
$log = $FORMAT_FILE_SIZE -f $fileSizeAsString;
Write-Host $log
$objFileInfo = $null;
}
catch
{
<#
InvocationInfo
#>
#$PSItem.InvocationInfo | Format-List *
<#
Rethrow the current exception
#>
throw $PSItem
}
@DanielAdeniji

This comment has been minimized.

Copy link
Owner Author

@DanielAdeniji DanielAdeniji commented Jul 19, 2021

Using formatted messages

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment