Search code examples
powershellpowershell-4.0

How can I check if specific files are within a folder and write to host if they are present or not


I'm trying to check if a list of files exists within a folder, if they do exist then write to host that they do if not write to host that they do not.

my code works to check if all the files exist however when trying to write to console it always evaluates to working even if files are missing.

this will return true for each file in $msis if present in the folder


        $Instance = "TEST"
        $msipath = "D:\CCS\${Instance}\"
        $msis = @("${msipath}CCS1.msi", "${msipath}CC2.msi", "${msipath}CCS3.msi", "${msipath}CCS4.msi")
        foreach($msi in $msis){
          $test = (Test-Path $msi) -PathType leaf)
          write-host "$test"
    }
      

I added and if else statement to check if $test is true write-host "I Work" else write-host "I Fail"

my issue is that even when the files are missing it will still evaluate to "I work" it's only when all files are not present that it evaluates to "I fail".

What i'm trying to do is have it write to host "I fail" if one or more files are missing.


  if ($test -eq 'True')
  { write-host "I work" }
  else
  {
  write-host "I fail"
  }


Solution

  • Test-Path -Path takes <string[]> as input, meaning, it can evaluate multiple paths, there is no need to loop here:

    $Instance = "TEST"
    $msipath = "D:\CCS\$Instance"
    $msis = 'CCS1.msi', 'CCS2.msi', 'CCS3.msi', 'CCS4.msi' | ForEach-Object {
        Join-Path $msipath -ChildPath $_
    }
    
    If((Test-Path $msis).Contains($false))
    {
        write-host "I Fail"
    }
    else
    {
        write-host "I Work"
    }