我有一个带参数的脚本:
param (
[Parameter(Mandatory=$true)][string]$VaultName,
[Parameter(Mandatory=$true)][string]$SecretName,
[Parameter(Mandatory=$true)][bool]$AddToMono = $false
)
...
Run Code Online (Sandbox Code Playgroud)
在这个脚本中,我想要包含我在另一个ps1文件中编写的函数:common.ps1
我经常导入这个
. .\common.ps1
Run Code Online (Sandbox Code Playgroud)
但如果我在脚本中这样做,我得到:
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.
Run Code Online (Sandbox Code Playgroud)
如何在此脚本中导入common.ps1?
谢谢!
问题是您从其他目录运行脚本.PowerShell正在寻找.\common.ps1使用当前目录,而不是脚本目录.要解决此问题,请使用内置变量$PSScriptRoot,该变量包含当前脚本的路径.(我假设您使用的是PowerShell v3.0或更高版本.)
function foo {
return "from foo"
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
然后我执行了这个:
PS> .\some_other_folder\with_params.ps1 -VaultName myVault -SecretName secretName -AddToMono $false
Run Code Online (Sandbox Code Playgroud)
得到这个输出:
Vault name is myVault
from foo
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
894 次 |
| 最近记录: |