Home > Net >  How exclude powershell script file from self deletion if it deletes by file content
How exclude powershell script file from self deletion if it deletes by file content

Time:11-19

i need to delete several generated files. I created a script:

Get-ChildItem -Recurse | Select-String "Generated by Terragrunt" -List | Select-Object Path | Remove-Item

The problem is of course it is matching the script it self, thus it deletes it self.

What is the easiest way to prevent it. I would like to have a method that is stable against changing script name and folder (it should always delete relative to its position but not it self).

CodePudding user response:

You can get the name of the current script file like this:

$currentScriptFile = if ($PSCommandPath) { Split-Path $PSCommandPath -Leaf } else { Split-Path $MyInvocation.MyCommand.Definition -Leaf }

Then use as

Get-ChildItem -Recurse -File -Exclude $currentScriptFile
  • Related