Background
Employing Import-CSV to read in a datafile.
My use case will work better if I am able to comment out certain entries’ as opposed to outright removing them from the datafile.
Datafiles
Datafile – Number of Lines – 11
fullname #Joe Smith Aaron Hall Ted Riley Bob Marley #Grant Hill Peter Tosh Mariah Carey #Tinah Marie Paul George Michael MacDonald Patti Labelle
Script
Outline
- Read File
- $listofPersons = @(Import-CSV -Path $filename -Delimiter “|”);
- Filter List
- Construct Discard Tag
- Discard Tag is #`* ( Anything that starts with # )
- Set-Variable FORMAT_ENTRY_COMMENT_SYNTAX -option Constant -value “#`*”;
- Discard Tag is #`* ( Anything that starts with # )
- Filter
- Save into $listofPersonsPruned entries with property fullname that do not match our discard tag
- $listofPersonsPruned = @($listofPersons | Where-Object {($_.fullname -notlike $FORMAT_ENTRY_COMMENT_SYNTAX)});
- Construct Discard Tag
Code
<# Script Command Line Parameters #> param ( ` [Parameter(Mandatory)] [string] $filename ) Set-StrictMode -Version Latest $script:ErrorActionPreference = "Stop" <# Declare variables #> [string] $log = ""; [int] $iPersonCount = 0; [int] $iPersonCountPruned =0; [string] $objectType = ""; <# Declare $listofPersons as an array of string #> $listofPersons= @(); $listofPersonsPruned= @(); <# Read file using @(Import-CSV -Path $filename -Delimiter "|"); #> $listofPersons = @(Import-CSV -Path $filename -Delimiter "|"); <# Get Object's Type ( $listofPersons2 ) #> $objectType = $listofPersons.GetType(); <# Display Object's Type ( $listofPersons1 ) #> Write-Host ""; $log = "Object Type (`$listofPersons):- {0}" -f $objectType; Write-Host $log; $iPersonCount = $listofPersons.length; Write-Host ""; $log = "Number of Persons:- {0}" -f $iPersonCount; Write-Host $log; <# Filter out commented entries Entries prefixed with # #> Set-Variable FORMAT_ENTRY_COMMENT_SYNTAX -option Constant -value "#`*"; $listofPersonsPruned = @($listofPersons | Where-Object {($_.fullname -notlike $FORMAT_ENTRY_COMMENT_SYNTAX)}); $iPersonCountPruned = $listofPersonsPruned.length; Write-Host ""; $log = "Number of Persons (post pruned):- {0}" -f $iPersonCountPruned; Write-Host $log;
Use Scenario
File – Number of Lines – 11
Invoke
>powershell ./readFile.person.discard.comments.ps1 datafile_11.txt
Output
Output – Image
Output – Text
>powershell ./readFile.person.discard.comments.ps1 datafile_11.txt Object Type ($listofPersons):- System.Object[] Number of Persons:- 11 Number of Persons (post pruned):- 8 >
Source Code Control
GitLab
Powershell – Import-CSV – Return Object’s Type
Link
-
- Files
- Read File And Discard Comments
File Name:- readFile.person.discard.comments.ps1
- Read File And Discard Comments
- Files
Referenced Work
- Microsoft
- Microsoft.PowerShell.Utility
- Import-Csv
Link
- Import-Csv
- Microsoft.PowerShell.Utility