0

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}

Todd
  • 1
  • Nested ```if statements``` are just a pain, in most cases. Change your logic to a ```switch statement```. Use the built-in snippet samples, using the hotkey to see them. That's ```Crtl+J``` in the PowerShell ISE or ```Crtl+Alt+J``` in VSCode, or see the PS help files for examples. That ```Write-Host``` is not needed, ***and really not a thing in variable value assignment use case***. If you want to assign a value to your variable and also automatically write to the screen, you can use Powershell variable squeezing. – postanote Apr 07 '23 at 20:18

2 Answers2

1

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
#>
postanote
  • 15,138
  • 2
  • 14
  • 25
0

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
        }
Todd
  • 1