Using Powershell if/then to create different exit codes based on file count in a folder

55 Views Asked by At

I'm trying to create a script that counts every file in a folder. The count part on its own works fine but I'm looking to make it output an exit code based off of the count for use in an automation tool.

   value | message  | exit code
    =15   "finish OK" (0) 
    <15   "not ready" (1)
    >15   "corruption" (2)

I tried the below, but it says "line 2 char 14 cannot bind argument to parameter 'path' because it is null"

    $filecount = Write-Host ( Get-ChildItem -File "c:\test\" | Measure-Object ).Count
    if(test-path $filecount){
     if((get-item $filecount).Count = 15){
    "Finish OK";EXIT 0
     }
     if((get-item $filecount).Count > 15){
     "CORRUPTION";EXIT 2}
     else{"REVIEW DATA"}
 
    }
    else{"NOT READY";EXIT 1}

2

There are 2 best solutions below

0
postanote On

As per my comment. You may be just overcomplicating this. Something like the below may be more prudent.

$FileCount = (Get-ChildItem -File 'D:\Temp' | Measure-Object).Count
switch ($FileCount)
{
    {$FileCount -eq 15} {'finish OK' }
    {$FileCount -lt 15} {'not ready'}
    {$FileCount -gt 15} {'corruption'}
}
# Results
<#
corruption
#>

PowerShell variable squeezing, to assign a value to a variable and output to the screen at the same time, is just this.

($FileCount = (Get-ChildItem -File 'D:\Temp' | Measure-Object).Count)
# Results
<#
100
#>

So, doing this across multiple folders could be something like this:

Clear-Host
Get-ChildItem -Path 'D:\Temp\CheckFileCount' | 
ForEach-Object {
    $FolderName = $PSItem.Name
    ($FileCount = (Get-ChildItem -File $PSItem.FullName | Measure-Object).Count)
    switch ($FileCount)
    {
        {$FileCount -eq 15} {"$FolderName : finish OK" }
        {$FileCount -lt 15} {"$FolderName : not ready"}
        {$FileCount -gt 15} {"$FolderName : corruption"}
    }
}
# Results
<#
15
EqualTo15 : finish OK
16
GreaterThan15 : corruption
14
LessThan15 : not ready
#>
0
Todd On

Here's what ended up working. Very similar to postanote's solution

param([string]$arg1)
        $filecount = Write-Output ( Get-ChildItem -File "$arg1" | Measure-Object 
    ).Count
        if($filecount -eq 15) {
        "Finish OK";EXIT 0
         }
         if($filecount -ge 15){
         "CORRUPTION-Review Source";EXIT 2
         }
        else{"NOT READY, RUN DOWNLOAD AGAIN...";EXIT 1
        }