1

I would just like help writing my if statement, I am having a hard time finding information online to do what I would like. Basically I need my if statement to see if the $file is located at a specified location (which can be multiple locations if possible). So far I have this:

foreach ($file in $MyInvocation.MyCommand.Path) {
  if ($file) {  #I need this to search a specific directory or directories
  }
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
SgtOVERKILL
  • 309
  • 3
  • 11
  • The question and code you posted don't make sense. `$MyInvocation.MyCommand.Path` is the full path to the script, which obviously does exist, otherwise the code wouldn't be running in the first place. It's also not a collection, which makes the `foreach` loop pointless. – Ansgar Wiechers Mar 25 '16 at 13:39

3 Answers3

1

If you want to see if something exists try using the test-path command. This will return a true/false value that you can plug into subsequent if statements and do what you want respectively.

$fileTest = test-path [file path here]
if($fileTest -eq $true){
    #what happens when the file exists
}
else{
    #what happens when the file does not exist
}
nkasco
  • 326
  • 1
  • 2
  • 13
0

You could also use a .NET method:

if(![System.IO.File]::Exists($file)){
  # File exists
}

A better way to check if a path exists or not in PowerShell

Community
  • 1
  • 1
Tapani
  • 3,191
  • 1
  • 25
  • 41
0

If you just want to know if the file exists at one of the locations then use:

if( ( (test-path 'c:\testpath1\test.txt','c:\testpath2\test.txt') -eq $true).Count)
{
"File found!";
}

If you want to know where the file is found then execute the test-path for each path seperatly.

if( ( (test-path 'c:\testpath1\test.txt') -eq $true).Count)
{
"File found at testpath1!";
}
if( ( (test-path 'c:\testpath2\test.txt') -eq $true).Count)
{
"File found at testpath2!";
}
Sdaele
  • 89
  • 7