Issue
I have 10 .txt files and all these files have rows or records that start with 2-digit numbers like 01, 02, 03, 04 ... and so on.
File1.txt
01,333,abc,test2,44,55
02,883,def,test5,33,093
03....and so on.
Now, if powershell finds a file that doesn't contain a record that starts with either "01" or "02", then i want to throw an error or exception.
Also, if there is such kind of file, then i don't want to copy that invalid format file to the output folder. I only want to modify and copy txt files that have 01 or 02.
How can i do this?
Get-ChildItem -Path 'C:\InputFiles\'-Filter '*.txt' -File | ForEach-Object {
$file = $_.FullName
$FileData = Get-Content $file
if($FileData[01] -notlike "01,"){
Write-Host $file "File is INVALID"
}
$data = switch -Regex -File $file {
'^01,' {
do stuff...
}
'^02,' {
do stuff...
}
default {$_}
}
}
$data | Set-Content -Path $file -Force
Copy-Item -Path $file -Destination 'C:\OutputFiles\' -Force
Solution
One way of doing this could be
Get-ChildItem -Path 'C:\InputFiles\'-Filter '*.txt' -File | ForEach-Object {
$isValid = $true
switch -Regex -File $_.FullName {
'^0[12],' { <# line begins with '01' or '02', so it's OK; do nothing #> }
default { $isValid = $false; break }
}
if ($isValid) {
# modify the file where you need and copy to the destination folder
}
else {
Write-Error "File $($_.FullName) is INVALID"
}
}
or do it without using regex:
Get-ChildItem -Path 'C:\InputFiles\'-Filter '*.txt' -File | ForEach-Object {
$isValid = $true
foreach ($line in (Get-Content -Path $_.FullName)) {
if ($line -notlike '01,*' -and $line -notlike '02,*') {
$isValid = $false
break
}
}
if ($isValid) {
# modify the file where you need and copy to the destination folder
}
else {
Write-Error "File $($_.FullName) is INVALID"
}
}
Answered By - Theo Answer Checked By - Mary Flores (WPSolving Volunteer)