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

标签 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 中执行此操作?

最佳答案

或者,将文件更改为 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/

相关文章:

c# - 在 C# 中将 PSObjects(或 PS 命令)转换为 JSON

regex - 提取两个双引号之间的所有数据

linux - 搜索模式并替换同一行中 = 和 ""之后的内容

未指定 Android 模拟器

powershell - 在 Powershell 的 Export-Csv 中使用和不使用管道的区别

.net - Get-Date 转换为字符串与 ToString()

powershell - 如何将 System.Collections.ArrayList 添加到 PowerShell 自定义对象?

powershell - 测试路径 PowerShell 问题

javascript - JSON.解析 : unexpected character at line 1 column 1 of the JSON data in Firefox only

powershell - 在 powershell 中检索 NUnit 自定义属性