简体   繁体   English

从另一个运行 PowerShell 脚本

[英]Run a PowerShell script from another one

What is the best and correct way to run a PowerShell script from another one?从另一个脚本运行 PowerShell 脚本的最佳和正确方法是什么?

I have a script a.ps1 from which I want to call b.ps1 which does different task.我有一个脚本 a.ps1,我想从中调用 b.ps1 来执行不同的任务。

Let me know your suggestions.让我知道你的建议。 Is dot sourcing is the best option here?点采购是这里的最佳选择吗?

Dot sourcing will run the second script as if it is part of the caller—all script scope changes will affect the caller.点源将运行第二个脚本,就好像它是调用者的一部分——所有脚本范围的更改都会影响调用者。 If this is what you want then dot-source,如果这是你想要的,那么点源,

However it is more usual to call the other script as if it were a function (a script can use param and function level attributes just like a function).然而,更常见的是将另一个脚本当作函数来调用(脚本可以像函数一样使用param和函数级属性)。 In many ways a script is a PowerShell function, with the name of the file replacing the naming of the function.在许多方面,脚本是一个 PowerShell 函数,文件名取代了函数的命名。

Dot sourcing makes it easier to at a later stage convert your script(s) into a module, you won't have to change the script(s) into functions.点源使以后更容易将您的脚本转换为模块,您不必将脚本更改为函数。

Another advantage of dot sourcing is that you can add the function to your shell by adding the file that holds the functions to Microsoft.PowerShell_profile.ps1, meaning you have them available at all times (eliminating the need to worry about paths etc).点源的另一个优点是您可以通过将保存函数的文件添加到 Microsoft.PowerShell_profile.ps1 来将函数添加到 shell,这意味着您可以随时使用它们(无需担心路径等)。

I have a short write-host at the top of my dot sourced files with the name of the function and common parameters and I dot source the functions in my profile.我在点源文件的顶部有一个简短的写入主机,其中包含函数名称和通用参数,并且我点源了配置文件中的函数。 Each time I open PowerShell, the list of functions in my profile scrolls by (If like me, you frequently forget the exact names of your functions/files You'll appreciate this as over time as the number of functions start to pile up).每次我打开 PowerShell 时,我的配置文件中的函数列表都会滚动(如果像我一样,你经常忘记函数/文件的确切名称,随着时间的推移,随着函数的数量开始堆积,你会意识到这一点)。

Old but still relevant.旧但仍然相关。 I work with modules with "Import-Module ", this will import the module in the current powershell session.我使用带有“导入模块”的模块,这将在当前的 powershell 会话中导入模块。 To avoid keep in cache and to always have the last changes from the module I put a "Get-Module | Remove-Module" that will clear all the loaded modules in the current session.为了避免保留在缓存中并始终拥有模块的最后更改,我放置了一个“Get-Module | Remove-Module”,它将清除当前会话中所有加载的模块。

Get-Module | Remove-Module
Import-Module '.\IIS\Functions.psm1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM