gpt4 book ai didi

powershell - 点源文件不起作用

转载 作者:行者123 更新时间:2023-12-03 16:38:37 25 4
gpt4 key购买 nike

我关注 this问题,但我似乎无法让这个工作。

(为了测试)我有一个带有 2 个脚本的 powershell 模块:variables.ps1 和 function.ps1 以及一个 list mymodule.psd1 (这些文件都在同一个目录中)

这是 variables.ps1 的内容:

$a = 1;
$b = 2;

这是function.ps1的内容
. .\variables.ps1
function myfunction
{
write-host $a
write-host $b
}

当我导入模块并调用 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

为什么这不起作用?

最佳答案

在脚本中使用相对路径时,它们相对于调用者 $PWD - 您所在的当前目录。

要使其相对于文件系统上当前脚本所在的目录,可以使用自动变量 $PSScriptRoot

. (Join-Path $PSScriptRoot variables.ps1)
$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)

关于powershell - 点源文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33463713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com