我跟着这个问题,但我似乎无法让这个工作.
(为了测试)我有一个带有2个脚本的powershell模块:variables.ps1和function.ps1以及一个清单mymodule.psd1(这些文件都在同一个目录中)
这是variables.ps1的内容:
$a = 1;
$b = 2;
Run Code Online (Sandbox Code Playgroud)
这是function.ps1的内容
. .\variables.ps1
function myfunction
{
write-host $a
write-host $b
}
Run Code Online (Sandbox Code Playgroud)
当我导入模块并调用myfunction时.这是输出:
C:\> Import-Module .\mymodule.psd1
C:\> myfunction
. : The term '.\variables.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.
At C:\Users\Jake\mymodule\function.ps.ps1:8 char:4
+ . .\variables.ps1
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (.\variables.ps1:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : CommandNotFoundException
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?
Mat*_*sen 14
在脚本中使用相对路径时,它们与调用者相关$PWD- 您当前所在的目录.
要使其相对于当前脚本在文件系统上的目录,可以使用自动变量 $PSScriptRoot
. (Join-Path $PSScriptRoot variables.ps1)
Run Code Online (Sandbox Code Playgroud)
该$PSScriptRoot变量是在PowerShell 3.0版中引入的,对于PowerShell 2.0,您可以使用以下方法模拟它:
if(-not (Get-Variable -Name 'PSScriptRoot' -Scope 'Script')) {
$Script:PSScriptRoot = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
}
. (Join-Path $PSScriptRoot variables.ps1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4519 次 |
| 最近记录: |