Search code examples
powershellif-statementoutlookpst

How to have powershell use a else statement to search another folder


I am trying to import some PST files into Outlook automatically, I currently am using the following script

Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null 
$outlook = new-object -comobject outlook.application 
$namespace = $outlook.GetNameSpace("MAPI") 
dir “$env:USERPROFILE\appdata\local\microsoft\outlook\.pst” | % { 
$namespace.AddStore($_.FullName) }

I would like to add a else statement so that if the pst file is not found in the first location then it will check in "$env:USERPROFILE\Documents\Outlook Files"


Solution

  • For a single file, use Test-Path to verify if the file is in the location you expect, for example:

    $pathA = "C:\path\to\my\file"
    $pathB = "C:\path\to\another\file"
    
    if(Test-Path $pathA){
      # do something with $pathA
    }
    else {
      # do something with $pathB
    }
    

    In your case you are using dir (an alias for Get-ChildItem) which returns all files in a folder matching the path/name specified. What you may want to do is to look for the files first in PathA and, if you don't find any, look in PathB:

    $pathA = "C:\path\to\my\folder\*.pst"
    $pathB = "C:\path\to\another\folder\*.pst"
    
    $files = Get-ChildItem $pathA
    
    if($files){
      # do something with $pathA
    }
    else {
      # do something with $pathB
    }