使用参数在脚本中导入函数

时间:2017-07-19 02:20:34

标签: powershell

我有一个带参数的脚本:

param (
    [Parameter(Mandatory=$true)][string]$VaultName,
    [Parameter(Mandatory=$true)][string]$SecretName,
    [Parameter(Mandatory=$true)][bool]$AddToMono = $false
 )
...

在这个脚本中,我想要包含我在另一个ps1文件中编写的函数:common.ps1

我通常用

导入它
. .\common.ps1

但如果我在脚本中这样做,我会得到:

The term '.\common.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the
path is correct and try again.

如何在此脚本中导入common.ps1?

谢谢!

1 个答案:

答案 0 :(得分:6)

问题是您正在从其他目录运行脚本。 PowerShell正在使用当前目录查找.\common.ps1,而不是脚本目录。要解决此问题,请使用内置变量$PSScriptRoot,其中包含当前脚本的路径。 (我假设您使用的是PowerShell v3.0或更高版本。)

common.ps1

function foo {
    return "from foo"
}

with_params.ps1

param (
    [Parameter(Mandatory=$true)][string]$VaultName,
    [Parameter(Mandatory=$true)][string]$SecretName,
    [Parameter(Mandatory=$true)][bool]$AddToMono = $false
 )

 . $PSScriptRoot\common.ps1

 Write-Output "Vault name is $VaultName"
 foo
然后我执行了这个:

 PS> .\some_other_folder\with_params.ps1 -VaultName myVault -SecretName secretName -AddToMono $false

得到了这个输出:

Vault name is myVault
from foo