Powershell Self Remove After Script Run

Powershell Self Remove After Script Run

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

0

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 
2

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 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.