title: Test-Path and Remove-Item Not Working for File that Exists When Called from Other Application
body: <p>I have a powershell script that checks a few folders on the network for a given file, and deletes it using specific credentials it if it is found.</p>
  
  <p>When I put this script on the server and run it from a command line, it works fine.</p>
  
  <p>When I run it from a separate batch file, it works fine.</p>
  
  <p>When I run it from an MVC app on the same server, using System.Management.Automation.Powershell, the script runs but the "Test-Path" command says the file does not exist, and the "Remove-Item" command does not remove the file, even if the "Test-Path" condition is removed.</p>
  
  <p>I have checked, and the path and file name are correct when it's being called by the MVC app, but for some reason the script does not recognize it.</p>
  
  <p>Any idea why this is the case?</p>
  
  <p>Here's the script (I know this isn't the best way to store password, it's not a production script yet):</p>
  
  <pre><code>$username = 'domain\del'
  $password = '*******'
  
  $securePassword = ConvertTo-SecureString $password -AsPlainText -Force
  $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
  $networkPath = "\\network\files\";
  [string[]]$folders = "Folder1", "Folder2", "Folder3"
  $param = $Args[0];
  
  if($param)
  {
      for($i=0; $i -lt $folders.Length; $i++)
      {
          $path = $networkPath + $folders[$i] + "\" + $param; 
          if ($path | Test-Path)
          {
              Remove-Item $path -Credential $credentail -force
          }
      }
  }
  
  </code></pre>
  
  <p>Here's how I'm executing it from the MVC app:</p>
  
  <pre><code>string file = (string)filename;
  string root = Server.MapPath("~");
  string script = System.Configuration.ConfigurationManager.AppSettings["DeleteScannerImageScriptName"];
  PowerShell shell = PowerShell.Create();
  shell.AddScript(root + script + " " + file);
  Collection&lt;PSObject&gt; results = shell.Invoke();
  </code></pre>