如何使用单个命令加载自定义powershell配置文件



我有一台共享计算机,我想为它创建一个自定义的PowerShell配置文件,我可以用一个简单的命令加载该配置文件,但在其他情况下永远不会获得来源。

我试着在主$profile中添加这样的函数:

function custom() {.  C:Users[username]DocumentsWindowsPowerShellcustom_profile.ps1}

当时的想法是,我只需键入命令custom,它就会加载我的自定义配置文件。

这不起作用,因为它在函数范围内进行寻源,当我离开该范围时,所有的函数和别名都会丢失。

可以只执行整个. C:Users[username]DocumentsWindowsPowerShellcustom_profile.ps1命令,但我正在寻找一种用单个命令实现这一点的方法。

如果我在bash中,我只会使用类似alias custom=". C:Users[username]DocumentsWindowsPowerShellcustom_profile.ps1"的东西,但Powershell的alias不起作用。

如何在PowerShell中执行此操作?

或者,将文件更改为psm1(powershell模块),然后:

Function custom { 
   if(-not Get-Module custom_profile){
       Import-Module 'C:Users[username]DocumentsWindowsPowerShellcustom_profile.psm1' 
   } else {
       Remove-Module custom_profile
       Import-Module 'C:Users[username]DocumentsWindowsPowerShellcustom_profile.psm1' 
   }
}

然后运行

custom

会做你想做的事。

如评论中所述,您可能需要

Export-ModuleMember -Variable * -Function * -Alias *

如果您的模块应该导出变量、别名以及函数。

一个简单的方法可能是只使用变量而不是函数。

简介:

$custom = 'C:Users[username]DocumentsWindowsPowerShellcustom_profile.ps1'

交互:

. $custom

可能想使用一个更好的名称,不太可能被覆盖,但相同的概念。

最简单的方法是使用PSReadLine,定义自己要执行的处理程序,例如F5来加载自定义prifile。

这比编写命令要短,因为您必须按1键。

无论如何,您都应该使用PSReadLine,因为它在各个方面都胜过股票控制台。

最新更新