PowerShell 路径解析不同,具体取决于使用时间

PowerShell path resolves differently depending on when it's used

我正在开发一个 PowerShell 模块,我的一个测试中的路径解析非常奇怪。

当前文件夹结构如下所示:

ISPS/
├── ISPS/
│   ├── Private/
│   ├── Public/
│   │   ├── Add-ICDCrawler.ps1
│   │   ├── Get-ICDCrawler.ps1
│   │   ├── New-ICDCrawler.ps1
│   │   └── Remove-ICDCrawler.ps1
│   ├── ISPSCrawler.psd1
│   └── ISPSCrawler.psm1
├── tests/
│   ├── Add-ICDCrawler.tests.ps1
│   ├── Get-ICDCrawler.tests.ps1
│   ├── New-ICDCrawler.tests.ps1
│   └── Remove-ICDCrawler.tests.ps1

表现怪异的测试是 Remove-ICDCrawler.tests.ps1。文件的开头和相关部分如下所示:

$ModuleRoot = Split-Path $PSScriptRoot -Parent

. $ModuleRoot\ISPS\Public\Get-ICDCrawler.ps1
. $ModuleRoot\ISPS\Public\Remove-ICDCrawler.ps1

当它是 运行 时,点源对 Get-ICDCrawler 行有效,但对 Remove-ICDCrawler 无效。这是出现的错误消息:

. : The term 'D:\Projects\ISPS\ISPS\ISPS\Public\Remove-ICDCrawler.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 D:\Projects\ISPS\tests\Remove-ICDCrawler.tests.ps1:4 char:3
+ . $ModuleRoot\ISPS\Public\Remove-ICDCrawler.ps1
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

这很简单。路径中的 ISPS 个文件夹过多。如果我从测试的第 4 行中删除 ISPS 文件夹之一并重试,它会完美运行。问题是 Get-ICDCrawler.ps1Remove-ICDCrawler.ps1 文件都存储在同一目录中,据我所知,路径应该解析为正确的目录。正如我所提到的,从第 4 行的路径中删除 ISPS 是可行的,但这违背了我对 PowerShell 的所有了解。有谁知道为什么会这样吗?

Name                           Value                  
----                           -----                  
PSVersion                      5.1.15063.608          
PSEdition                      Desktop                
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.15063.608         
CLRVersion                     4.0.30319.42000        
WSManStackVersion              3.0                    
PSRemotingProtocolVersion      2.3                    
SerializationVersion           1.1.0.1                

我想出来了,所以我离开了这个,以便将来人们可以嘲笑它。

Get-ICDCrawler 文件的开头如下所示:

$ModuleRoot = Split-Path $PSScriptRoot -Parent

. $ModuleRoot\Private\Find-XmlNode.ps1
. $PSScriptRoot\New-ICDCrawler.ps1

所以发生的是我导入该文件并且 $ModuleRoot 变量被更改为相对于 Get-ICDCrawler.ps1 文件。我必须确保变量的命名方式不同,以免名称空间发生冲突。