Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove a dot sourced script in PowerShell?

If I have dot sourced :

. "\foo-bar.ps1"

How can I see obtain the list of all dot sourced scripts and how can I remove "foo-bar/ps1" from the dot sourced scripts?

like image 933
pencilCake Avatar asked Dec 04 '12 19:12

pencilCake


People also ask

What does the dot mean in PowerShell?

The PowerShell dot-source operator brings script files into the current session scope. It is a way to reuse script. All script functions and variables defined in the script file become part of the script it is dot sourced into. It is like copying and pasting text from the script file directly into your script.

Where are PowerShell scripts stored?

PowerShell scripts can be created within PowerShell Universal to execute manually, on a scheudle or when events happen within the platform. They are stored on disk and also persisted to a local or remote Git repository. Script properties are stored in the scripts. ps1 configuration file.


2 Answers

As far as I know, you can't remove a dot sourced script. That is why modules where introduced in PowerShell 2.0. See About_Modules

You can convert your "foo-bar.ps1" to a module. A module can be imported (Import-Module) and removed (Remove-Module).

like image 172
JPBlanc Avatar answered Oct 05 '22 17:10

JPBlanc


I agree with @JPBlanc that you cannot remove a dot-sourced script in general but depending on your own coding conventions you may be able to do this in practice.

First a couple observations about why you cannot do this in general:

(1) PowerShell has no notion of a dot-sourced script as a separate entity. Once you dot-source it, its contents becomes part of your current context, just as if you had manually typed each line at the prompt. Thus you cannot remove it because it does not actually exist:-)

(2) For the very same reason as (1) you cannot list dot-sourced scripts.

Now, how to do it anyway:

Depending on the contents and conventions of your dot-sourced script, though, you may be able to do what you want. If, for example, the script simply defines three functions--call these func-a, func-b, and func-c--then you can both list and remove those functions.

List assimilated functions:

Get-ChildItem function:func-*

Remove assimilated functions:

Remove-Item function:func-*
like image 31
Michael Sorens Avatar answered Oct 05 '22 17:10

Michael Sorens