Check if file exists

Hi, I have a bit of a situation with a script I wrote. I tried looking online, but didn’t find any help.

I have a folder in which everyday (in theory) a certain list of files arrives, the folder stores the files of the last 2 weeks. The file I need to filter is structured like a csv and every file name contains two particular strings. “SDD_380712_020_021_IBACDC” and “.csv” (the file itself is a .sav, so .csv is not the extension).

I made a code that everyday selects the file from the day before and imports it for processing, two days ago the file wasn’t present so my script had an error. I was looking for a way to check if the file exists and display an error otherwise.

I found online suggestion aboutusing test-path or [System.IO.File]::Exists($path), but the problem is besides those 2 common strings my files have a different and unpredictable name everyday, so I cannot know it’s exact path.

Here is my code so far

$VenditeGrezze = "C:\Files"

$FileCDC = (Get-ChildItem -Path $VenditeGrezze -Include "*SDD_380712_020_021_IBACDC*" "*.csv*" -Recurse | ? {
  $_.LastWriteTime -gt (Get-Date).AddDays(-1) #the file is from yesterday
})

$Data = Import-Csv -Path $FileCDC -Delimiter '|' -ErrorAction Stop # Import the file

My idea is something like if $FileCDC is null
{
Sends error message
}
Else
{
$Data = Import-CSV …
}

Ty in advance
Alice

reading your code, your initial idea is how I would handle it too. Essentially `$FileCDC` contains something or it doesn’t. You could change your import operation to this:

if ($FileCDC) {
    $Data = Import-Csv -Path $FileCDC -Delimiter '|' -ErrorAction Stop
} else {
    Write-Error "File not found"
}

and then carry on from there.
To over explain it: if the condition is just a variable, then it will essentially try to cast that variable as a boolean.

PS> $test = "some words"
PS> [bool]$test
True
PS> $test2 = ""
PS> [bool]$test2
False

If the variable contains any kind of fileinfo object then it will be treated as $true, otherwise it’ll be a $false. But fair warning for using this elsewhere, if the variable could potentially contain the integer 0 then converting that to a boolean will return False

1 Like

Thank you so much, didn’t know you could simply do that!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.