Reputation: 11
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
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:
Script_2.ps1
:
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:
$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.Upvotes: 3