Antony Nelson G
Antony Nelson G

Reputation: 11

Can't remove directory passed as argument to the powershell script runs asynchronously

I have a powershell script which needs to delete the directory passed as argument and the script should be started asynchronously.

Example: Script_1.ps1

$Path = "C:\XYZ"

$tempDir = "C:\Temp"

Start-Process -FilePath "powershell.exe" -ArgumentList "$($tempDir)\Script_2.ps1","-PathToDelete","$Path"

Script_2.ps1

param(
# The path to delete
[Parameter(Mandatory=$True,ValueFromPipeline=$False,HelpMessage="The path to delete")]
[string]$PathToDelete,
)

Remove-Item -path $PathToDelete -Recurse -Force 

exit 0

Currently ,Remove_Item throws exception saying path cannot deleted because it's in use. Process explorer says the path to be deleted is used by powershell process started in script_1.ps.

Upvotes: 1

Views: 162

Answers (1)

mklement0
mklement0

Reputation: 437408

You say that the process running Script_1.ps1 is preventing the removal, and I'm assuming you've already ruled out the following causes:

  • You're running that script from a directory located inside the directory tree you're trying to remove.
  • Inside that script, before calling Script_2.ps1:
    • you're changing the current directory to a directory located inside the directory tree.
    • or you've opened a file located in that directory tree without having closed it yet.

This leaves the following potential - and obscure - cause:

The process-level working directory - which is distinct from PowerShell's current location - may be a directory inside the directory tree you're trying to remove, thereby preventing removal.

To rule that out, change it to C:\ from inside Script_2.ps1, before calling Remove-Item, as follows:

[Environment]::CurrentDirectory = 'C:\'

Note:

  • That PowerShell's working directory (as reflected in the automatic $PWD variable and the return value from Get-Location) differs from the process' is unfortunate, but cannot be avoided, because a single PowerShell process can host multiple runspaces (sessions) simultaneously, each of which must maintain their own working directory (location) - see GitHub issue #3428.
  • A more common pitfall that results from this discrepancy is owed to the fact that .NET APIs use the process' working directory, which means that you cannot pass relative paths to .NET methods without risking their resolution relative to a different working directory than PowerShell's - see this answer for more information.

Upvotes: 3

Related Questions