2017-07-19 102 views
2

我有参数的脚本:导入功能

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?

谢谢!

+0

给出点源中的common.ps1的完整路径 –

回答

4

问题是,您正在从其他目录运行脚本。 PowerShell正在寻找.\common.ps1使用当前目录,而不是脚本的目录。要解决此问题,请使用包含当前脚本路径的内置变量$PSScriptRoot。 (我假设你正在使用的PowerShell 3.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 
+0

这很好,谢谢! – MaurGi