简体   繁体   中英

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?

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).

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-*

You can remove sourced functions if you know the path of the dot-sourced file:

Get-ChildItem function: | 
Where-Object {$_.ScriptBlock.File -eq $path} | 
Remove-Item

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM