如何正确设置执行powershell子脚本的路径

本文关键字:脚本 路径 powershell 何正确 设置 执行 | 更新日期: 2023-09-27 18:30:07

已解决:下面的解决方案是使用以下联接路径:[System.Reflection.Assembly]::LoadFrom((Join-Path (pwd) "MyAssembly.dll")) | out-null

原始问题

我有powershell脚本和一个程序集文件,如下所示:

D:'path1'script1.ps1
D:'path2'script2.ps1
D:'path2'MyAssembly.dll

在D:''path1''script1.ps1中,我需要调用D:''path2''script2.ps1。然后,script2.ps1将依次加载一些已经放置在D:''path2文件夹中的C#程序集。我的印象是,如果我执行"设置位置"或"推送位置",那么工作目录将为script2.ps1中发生的任何事情正确设置。

script1.ps1看起来像这样:

$otherpath = "D:'path2"
Set-Location -Path $otherpath
Push-Location -Path $otherpath
.'script2.ps1

script2.ps1看起来像这样:

[System.Reflection.Assembly]::LoadFrom("MyAssembly.dll") | out-null

但是,当我在D:''path1中时,我执行script1.ps1如下,然后我得到一个FileNotFound异常:

D:'path1>powershell .'script1.ps1
Exception calling "LoadFrom" with "1" argument(s): "Could not load file or assembly
'file:///D:'path1'MyAssembly.dll' or one of its dependencies. The system cannot find the file
specified."
At D:'path2'script2.ps1:1 char:1
+ [System.Reflection.Assembly]::LoadFrom("MyAssembly.dll") | out-null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FileNotFoundException

如何正确设置路径,以便当我从D:''path1调用script1.ps1时,环境将D:''path2正确设置为对D:''path2中程序集的所有调用的工作目录?

如何正确设置执行powershell子脚本的路径

只要script2中的工作目录没有更改,使用[System.Reflection.Assembly]::LoadFrom((Join-Path (pwd) "MyAssembly.dll")) | out-null就可以工作。

另一种选择是使用$MyInvocation.MyCommand.Path,它将始终提供当前脚本的完整路径。你可以这样使用它:

[System.Reflection.Assembly]::LoadFrom((Join-Path (Split-Path $MyInvocation.MyCommand.Path) "MyAssembly.dll")) | out-null

使用以下连接路径:

[System.Reflection.Assembly]::LoadFrom((Join-Path (pwd) "MyAssembly.dll")) | out-null