PowerShell:- File System – Create new file

Background

I need to generate data files on a scheduled basis.

The file’s name should reflect the current time.

 

Script

Outline

  1. Command Line Arguments
    • folder
    • filenamePrefix
    • filenameSuffix
    • fileExt
    • fileTemplate
  2. Sanitize Variables
    • folder
      • If the folder is not specified, use the current folder
        • Use Get-Location command
      • Sanitize folder
        • Make sure that it is not a file
    • fileTemplate
      • Set bTemplateFileInUse based on whether the variable fileTemplate is passed
      • If fileTemplate is indicated
        • Validate the existence of the template file
        • If the template file does not exist, raise an exception
  3. Prepare Environment
    • folder
      • Check if the folder exists
        • Test-Path -path $folder -PathType Container;
      • If the folder does not exist, create the folder
        • New-Item -ItemType directory -Path $folder
  4. Create File
    • If template file is specified, make a copy of the template file
      • Copy-Item -LiteralPath $fileTemplate -Destination $filename
    • If template file is not specified, create an empty file
      • New-Item -ItemType file -Path $filename

Code


param ( `
		    [Parameter(Mandatory = $false)] `
		    [string] $folder`
			
		  , [Parameter(Mandatory = $false)] `
		    [string] $filenamePrefix`
			
		  , [Parameter(Mandatory = $false)] `
		    [string] $filenameSuffix`
			
		  , [Parameter(Mandatory = $false)] `
		    [string] $fileExt = "txt"`
			
		  , [Parameter(Mandatory = $false)] `
		    [string] $fileTemplate`

      )
	  
<#
	Establishes and enforces coding rules in expressions, scripts, and script blocks.
#>
Set-StrictMode -Version latest

<#
	Declare Variables
#>
[string] $FORMAT_TIMESTAMP = "yyyyMMdd_HHmmss";
[string] $FORMAT_FILENAME_FULL = "{0}\{1}{2}{3}.{4}";

[string] $log = "";
[String] $strTS = "";
[string] $filename ="";
[Boolean] $bTemplateFileInUse = $false;
[Boolean] $bFileExistence = $false;
[Boolean] $bfolderExistenceAsFolder = $false;
[Boolean] $bfolderExistenceAsFile = $false;

try
{
	
	<#
		If Folder is not defined, set folder to current location
	#>
	if ( ($folder -eq $null) -or ($folder -eq "") )
	{
		$folder = Get-Location	
	}

	<# 
		Is Template file provided
	#>
	if ( ($fileTemplate -eq $null) -or ($fileTemplate -eq "") )
	{
		$bTemplateFileInUse = $false;
	}
	else
	{
		$bTemplateFileInUse = $true;	
	}

	<#
		Set Folder flags using Test-Path
	#>
	$bfolderExistenceAsFolder = Test-Path -Path $folder -PathType Container;
	$bfolderExistenceAsFile = Test-Path -Path $folder -PathType Leaf;

	<#
		If Specified Folder is actually a file, please raise an exception
	#>
	if (
			( $bfolderExistenceAsFile -eq $true )
	   )
	{
		
		$log = "Folder ( {0} ) is actually a file !" -f $folder;
		
		throw [System.IO.FileNotFoundException] $log
		
	}

	<#
		If Template file is provided, check if it exists
	#>
	if ($bTemplateFileInUse -eq $true)
	{
		
		#Folder existence check
		$bFileExistence = Test-Path -Path $fileTemplate -PathType leaf;

		#If Folder does not exists, please create it
		if ($bFileExistence -eq $false)
		{

			$log = "File ( {0} ) does not exist!" -f $fileTemplate;
			
			throw [System.IO.FileNotFoundException] $log
			
		}


	}

	<#
		Get Folder display buffer
	#>
	$log = "Folder :- {0}" -f $folder;

	<#
		Write out Specified Folder
	#>
	Write-Verbose $log

	<#
		Get TimeStamp
	#>
	$objTS = get-date

	<#
		Get Timestamp Formatted as YYYYMMDD_HHmmSS
	#>
	$strTS = Get-Date -Date $objTS -Format $FORMAT_TIMESTAMP

	<#
		Get Timestamp display buffer
	#>
	$log = "Timestamp :- {0}" -f $strTS;

	Write-Verbose $log

	<#
		Get Filename display buffer
	#>
	$filename = $FORMAT_FILENAME_FULL -f $folder, $filenamePrefix, $strTS, $filenameSuffix, $fileExt

	$log = "Filename :- {0}" -f $filename;
	Write-Verbose $log

	<#
		Folder existence check
	#>
	$bFolderExistence = Test-Path -path $folder -PathType Container;

	<#
		If Folder does not exists, please create it
	#>
	if ($bFolderExistence -eq $false)
	{

		$log = "Create Folder {0}" -f $folder;
		Write-Verbose $log
		
		$null = New-Item -ItemType directory -Path $folder

	}

	<#
		If template file is not in use, please create an empty file
		Else Template file is in use, make a copy of the template file	
	#>
	if ($bTemplateFileInUse -eq $true)
	{
		
		$log = "Copy file {0} to {1}" -f $fileTemplate, $filename;
		Write-Verbose $log

		<#
			Copy File $fileTemplate to $filename
		#>
		Copy-Item -LiteralPath $fileTemplate -Destination $filename
		
	}
	else
	{
		
		$log = "Creating a new empty file ( {0} )" -f $filename;
		Write-Verbose $log
		
		<#
			Create File
		#>
		$null = New-Item -ItemType file -Path $filename

	}

}
catch
{

	<#
		InvocationInfo
	#>
	$PSItem.InvocationInfo | Format-List *

	<#
		Rethrow the current exception
	#>
	throw $PSItem
	
}





Invoke


setlocal

set "_folder=c:\datafile"

set "_filenamePrefix=sampleData_"

set "_fileExt=csv"

set "_fileTemplate=C:\datafile\NutritionalFacts_Fruit_Vegetables_Seafood.csv"

powershell ./fileSystem.file.new.ps1 -Verbose -folder %_folder% -filenamePrefix %_filenamePrefix% -fileExt %_fileExt% -fileTemplate %_fileTemplate%

endlocal

Output

Output – Image

Output – Text


>invoke_fruits.cmd

>setlocal

>set "_folder=c:\datafile"

>set "_filenamePrefix=sampleData_"

>set "_fileExt=csv"

>set "_fileTemplate=C:\datafile\NutritionalFacts_Fruit_Vegetables_Seafood.csv"

>powershell ./fileSystem.file.new.ps1 -Verbose -folder c:\datafile -filenamePrefix sampleData_ -fileExt csv -fileTemplate C:\datafile\NutritionalFacts_Fruit_Vegetables_Seafood.csv
VERBOSE: Folder :- c:\datafile
VERBOSE: Timestamp :- 20210702_113727
VERBOSE: Filename :- c:\datafile\sampleData_20210702_113727.csv
VERBOSE: Copy file C:\datafile\NutritionalFacts_Fruit_Vegetables_Seafood.csv to c:\datafile\sampleData_20210702_113727.csv

>endlocal

>

Source Code Control

GitHub

Gist

DanielAdeniji/fileSystem.file.new.ps1
Link

 

References

  1. Microsoft
    • Docs
      • Docs > PowerShell > Scripting > Reference > Microsoft.PowerShell.Management
      • Docs > .NET > .NET fundamentals
        • Custom date and time format strings
          Link
        • Format types in .NET
          Link
      • Docs > PowerShell > Scripting
        • Everything you wanted to know
          • Everything you wanted to know about exceptions
            Link
  2. StackOverflow
    • How to format a DateTime in PowerShell
      Link

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s