openlang

Detecting a missing input file

Hello, I've run into a difficulty with a script of mine. Searching the web hasn't turned up a solution.

A folder receives a particular set of files daily (at least in theory), retaining about 3 weeks of them. My target file has csv-like contents, and its name always includes these two strings. “SDD_492813_030_031_IBZXCD” and “.csv” (its actual extension is .sav, rather than .csv).

My script picks the previous day's file each day and imports it to process it, but three days ago the missing file caused it to fail. I'd like to test for the file's presence and show an error if it's absent.

Online sources mentionusing [System.IO.File]::Exists($path) or test-path, yet aside from the 2 shared strings, the name varies unpredictably each day, so I can't determine it's full path beforehand.

This is my current code

$InputDirectory = "D:\Incoming"

$DailyInput = (Get-ChildItem -Path $InputDirectory  -Include "*SDD_492813_030_031_IBZXCD*" "*.csv*" -Recurse | ? {
  $_.LastWriteTime -gt (Get-Date).AddDays(-2) #pick files from the prior day
})

$Records = Import-Csv -Path $DailyInput -Delimiter '|' -ErrorAction Stop # read the selected file

I'm imagining a test like if $DailyInput is null

{

Display an error

}

Else

{

$Records = Import-CSV …

}

Thanks beforehand

Tavin

The conversation continues 2

Follow the reasoning
  1. Permalink

    looking through this, I'd take the approach you suggested initially as well. Basically, $DailyInput either holds a value or doesn't. The import could be replaced with the following:

    if ($DailyInput) {
      $Records = Import-Csv -Path $DailyInput -Delimiter '|' -ErrorAction Stop
    } else {
      Write-Error "Missing input file"
    }

    then proceed as usual afterward.

    For a more detailed explanation: giving a variable alone as the condition effectively attempts a boolean conversion of its value.

    PS> $words = "a little text"
    PS> [bool]$words
    True
    PS> $empty = ""
    PS> [bool]$empty
    False

    A fileinfo object in that variable will evaluate as $true, and otherwise you'll get $false. One caveat when applying this in other situations: a variable that might hold the integer 0 will convert to False in that case

Other sides of the same question

  1. F# negation when testing file existence

    I'm using this code to signal an error if a file is missing. Instead, this error appears. What did I misunderstand?

    Replies 2Latest activity fsharp
  2. Can main() supply an exit status without disrupting control flow?

    Must an exit status always be supplied through os.exit()? Calling os.exit() inside main() prevents me from using defer, produ…

    Replies 3Latest activity odin
  3. Email alerts for exceptions and errors in an application

    I want an email sent whenever my application encounters an error. exception plus the .go filename and its line number. that w…

    Replies 2Latest activity go