0
votes

I am trying to handle some "Errors" in my PowerShell script. If a specific file type (.key) does not exist in a specified folder, there is nothing to do for the script, so it should terminate. I use this sample to solve my problem, which does not work as expected. PowerShell did not terminate.

$Eventlogfolder = "c:\temp\test\"

# Check if  subfolder exists and check if .key-files are available in this folder.
# if not - exit. There is nothing to do if no LicenceFile (*.key Files) are available.
$CheckFileExistence = Get-ChildItem $EventLogFolder -recurse -filter  "*.key"
if (!($CheckFileExistence)) {ErrorAction Stop}

What I know is, the Get-ChildItem gives an empty array as a result. There is no error-message or status. I assume that's why ErrorAction did not work here.

So my question is, how do I exit from Get-ChildItem ? When I use EXIT the PowerShell ISE exits.

1
Use Test-Path to test for the existence of files not Get-ChildItem.EBGreen
You can also add if/else statements as well as continue and break statements to skip around in the scriptqbanet359
thank you, i did not know the break statement until now, it works simply doing if (!($CheckFileExistence)) {break} Peter Core

1 Answers

0
votes

Something like this?

$Eventlogfolder     = "c:\temp\test\"
$CheckFileExistence = Get-ChildItem $EventLogFolder -recurse -filter  "*.key"

if ([string]::IsNullOrEmpty($CheckFileExistence)){
    throw "No .key files found in $Eventlogfolder"
}else{
   # do stuff with .key files
}