I'm trying to delete the script after it ran but I'm getting an error saying the file is in use, what can I do?
$exclude = @("*.zip", "*.dll", "*.exe")
Get-ChildItem "C:\.." -Recurse -Exclude $exclude | Remove-Item -Force -Recurse -WhatIf
Remove-Item $PSScriptRoot -Force
3 Answers
$PSScriptRoot is not pointing to the script, bu rather the directory it's in. Try Remove-Item $script:MyInvocation.MyCommand.Path -Force
As far as I know, $PSScriptRoot is the directory where the script is located. Assuming PowerShell 3, you should use $PSCommandPath to call the full path of the script:
Remove-Item $PSCommandPath -Force
I would simple copy the script to temp directory, delete original and run it from temp.
Copy-Item -Path .\myscript.ps1 -Destination $env:TEMP\myscript.ps1
$env:TEMP\myscript.ps1
Remove-Item -Path .\myscript.ps1