0

I would like running a script in a directory and then delete the directory, sub-directory and files.

If(Test-Path -Path $var_InterventionManuelle) {Remove-Item -Recurse -Force $var_InterventionManuelle}

When I run the command-line it is working fine... but if someone is, from the command-line, inside that directory and run the script then the directories and files are not delete. I just get an error as the directory is in use.

How may I bypass that problem?

2
  • Check which directory you are in and if necessary change to another one?
    – DavidPostill
    Dec 19, 2014 at 14:15
  • Unfortunately this stupidity is just the way windows works; it won't let you delete a file that any process has open.
    – psusi
    Dec 19, 2014 at 15:47

1 Answer 1

1

You could do something like the below to check if the current directory your script is running in contains $var_InterventionManuelle.

If(Test-Path -Path $var_InterventionManuelle)
{
    While((Get-Item -path ".\").FullName.Contains($var_InterventionManuelle)) { cd .. }
    Remove-Item -Recurse -Force $var_InterventionManuelle
}

An example would be the current directory is "C:\Temp\Scripts\Blah", and $var_InterventionManuelle = "C:\Temp" then the current directory contains $var_InterventionManuelle and it would cd all the way back to C:\.

Obviously, if the $var_InterventionManuelle variable contains the drive root (eg. "C:\") and the current directory the script is running in is on the C:\ drive, the while loop will never finish. If you know the $var_InterventionManuelle variable will NEVER contain the drive root, that's fine, otherwise you'll need to cater for that behavior by doing something like this:

if($var_InterventionManuelle.Split("\")[1].Length -eq 0)
{
    Write-Output "I'm trying to delete the root drive, abort, abort"
    exit
}

The above script checks if there is anything after the first slash in the path. For example "C:\" will split into "C:" and "" so the second item in the array will have a length of 0. Where "C:\Temp\Blah" will split into "C:", "Temp", and "Blah". In this case the second item in the array ("Temp") will have a length of 4, which is not 0...

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .