profile.ps1 如何导入脚本和函数

Pla*_*zma 6 powershell

我有一些自己制作的函数和脚本。问题是我不确定保存在哪里以及如何加载。

在本地配置文件上,我有以下内容:C:\Users\Plazma\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

有了这个:

Import-Module c:\Users\Plazma\Documents\WindowsPowerShell\Get-serialnumber.ps1 -Force
Import-Module c:\Users\Plazma\Documents\WindowsPowerShell\Invoke-AutoIPAssigning.ps1 -Force
Import-Module C:\Users\Plazma\Documents\WindowsPowerShell\Reset-Password.ps1 -Force
Import-Module C:\Users\Plazma\Documents\WindowsPowerShell\Send-Email.ps1 -Force
Run Code Online (Sandbox Code Playgroud)

在这些文件中,我有函数/脚本。这是一个很好的做法,或者我应该以其他方式导入它?使用 ForEach 加载该位置的所有文件?如果一个功能将使用另一个功能(例如总是在重置密码后我想发送电子邮件)我应该如何导入它?

Ben*_*est 11

我从未见过Import-Module用于从脚本导入定义的方法,我什至不知道这是否有效。通常,人们会像这样.从他们的库脚本中获取源代码:$profile

Microsoft.Powershell_profile.ps1

. c:\Users\Plazma\Documents\WindowsPowerShell\Get-serialnumber.ps1
. c:\Users\Plazma\Documents\WindowsPowerShell\Invoke-AutoIPAssigning.ps1
. C:\Users\Plazma\Documents\WindowsPowerShell\Reset-Password.ps1
. C:\Users\Plazma\Documents\WindowsPowerShell\Send-Email.ps1
Run Code Online (Sandbox Code Playgroud)

点源在调用会话的上下文中执行脚本,因此在脚本范围内定义的任何内容(例如函数或变量)都可以在父会话中使用。


但是,如果您有很多这样的脚本在网络上运行,最好的解决方案是将这些脚本写入(一个或多个)模块,因为模块更易于移植,并且如果您不这样做,您可以托管自己的 NuGet 提要不想上传到公共PowerShell Gallery