我有一台共享计算机,我想为其创建一个自定义 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 中执行此操作?
最佳答案
或者,将文件更改为 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 *
如果您的模块应该导出变量和别名以及函数。
关于powershell - 如何使用单个命令加载自定义 powershell 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36405552/