【问题标题】:How to properly set the path for executing a child powershell script?如何正确设置执行子 powershell 脚本的路径?
【发布时间】:2013-09-03 18:21:24
【问题描述】:

已解决:以下解决方案是使用以下 Join-Path: [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# 程序集。我的印象是,如果我执行 Set-Location 或 Push-Location,那么工作目录将针对 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 中所有对程序集的调用的工作目录?

【问题讨论】:

  • 如果将 MyAssembly.dll 更改为 .\MyAssembly.dll 会怎样?或者甚至更好地明确给出完整路径?
  • 添加 .\ 不起作用,同样的错误。但是,使用 (Join-Path (pwd) $assemblyName) 确实有效。谢谢你的提示!我将用答案更新上面的问题。如果你输入这个答案,我也会选择它。
  • 不,你想通了。如果您愿意,您可以发布修复它的答案,并且在一段时间后(我忘记了多长时间)您可以接受它。
  • 2 天,如果我没记错的话。

标签: c# powershell


【解决方案1】:

只要 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

【讨论】:

  • 我会将此添加为评论,但我没有所需的代表。
【解决方案2】:

使用以下连接路径:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    相关资源
    最近更新 更多