Link to home
Start Free TrialLog in
Avatar of E=mc2
E=mc2Flag for Canada

asked on

How can I configure the script not to create a new file if the original file is not present?

I need to modify the following script so that if it can't find the original.txt file it will not create a newdatafile.txt

$InputFile = "C:\Programs\Temp\original.txt"
$OutputFile = "C:\Programs\Temp\newdatafile.txt"

Function ParseText ($OutputFile,$InputFile){
Begin{
$poline,$totline,$total = $NULL,$NULL,$NULL
Set-Content $OutputFile $null
}
Process{
      Get-Content -Path $InputFile | % {

If ($_ -match "AZI\*1"){
      If ($poline -ne $null -and $total -ne $null){
      $Totline = "Total: `$$Total"
      write-host "This is Total `$$total"
            "`n$poline `r`n$totline" | out-file $OutputFile -Encoding UTF8 -Append
            $poline,$totline,$total = $NULL,$NULL,$NULL
      }
}
   If($_ -match "(MA\*)(\d{0,10})") {
      $poline = "PONumber: $($Matches[2])"
    }Elseif ($_ -match "PO1"){
        $col=$_.split("*") ; $total += [double]$col[2] * [double]$col[4]
  }
 }
}
}

ParseText $OutputFile $InputFile


Currently, this will produce the new file regardless if it finds the input file or not.

It must not create the new file if the input file does not exist.
Avatar of Randy Poole
Randy Poole
Flag of United States of America image

$InputFile = "C:\Programs\Temp\original.txt"
$OutputFile = "C:\Programs\Temp\newdatafile.txt"

Function ParseText ($OutputFile,$InputFile){
Begin{
$poline,$totline,$total = $NULL,$NULL,$NULL
Set-Content $OutputFile $null
}
Process{
      Get-Content -Path $InputFile | % {

If ($_ -match "AZI\*1"){
      If ($poline -ne $null -and $total -ne $null){
      $Totline = "Total: `$$Total"
      write-host "This is Total `$$total"
            "`n$poline `r`n$totline" | out-file $OutputFile -Encoding UTF8 -Append
            $poline,$totline,$total = $NULL,$NULL,$NULL
      }
}
   If($_ -match "(MA\*)(\d{0,10})") {
      $poline = "PONumber: $($Matches[2])"
    }Elseif ($_ -match "PO1"){
        $col=$_.split("*") ; $total += [double]$col[2] * [double]$col[4]
  }
 }
}
}

if exist $InputFile ParseText $OutputFile $InputFile

Open in new window

Only call your procedure if the file exists
Avatar of E=mc2

ASKER

This does not seem to work.

Missing '(' after 'if' in if statement.
At C:\.....\NEW.ps1
:29 char:4
+ if  <<<< exist $InputFile ParseText $OutputFile $InputFile
    + CategoryInfo          : ParserError: (OpenParenToken:TokenId) [], ParseE
   xception
    + FullyQualifiedErrorId : MissingEndParenthesisInIfStatement
ASKER CERTIFIED SOLUTION
Avatar of Randy Poole
Randy Poole
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of E=mc2

ASKER

Thanks, yes I am, my apology for not mentioning it.
I will test this and get back to you.
Avatar of E=mc2

ASKER

This works very well, excellent.