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

时间:2016-04-04 14:32:43

标签: powershell

我有一台共享计算机,我想为其创建一个自定义PowerShell配置文件,我可以使用一个简单的命令加载它,但从来没有获取过来。

我尝试将这样的函数添加到主$ profile:

function custom() {.  C:\Users\[username]\Documents\WindowsPowerShell\custom_profile.ps1}

我的想法是我可以输入命令custom,它会加载我的自定义配置文件。

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

可以只执行整个. C:\Users\[username]\Documents\WindowsPowerShell\custom_profile.ps1命令,但我正在寻找一种方法来执行一个命令。

如果我使用bash,我只会使用类似alias custom=". C:\Users\[username]\Documents\WindowsPowerShell\custom_profile.ps1"的内容,但是Powershell的alias并不会这样做。

我如何在PowerShell中执行此操作?

3 个答案:

答案 0 :(得分:3)

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

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

然后运行

custom

会做你想做的事。

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

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

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

答案 1 :(得分:0)

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

简介:

$custom = 'C:\Users\[username]\Documents\WindowsPowerShell\custom_profile.ps1'

交互:

. $custom

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

答案 2 :(得分:0)

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

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

无论如何你应该使用PSReadLine,因为它在每个方面都超过了控制台。