无法从其他脚本调用PowerShell脚本

时间:2017-02-22 12:55:28

标签: windows powershell windows-7 powershell-v5.0

我正在尝试从另一个文件 begin.ps1 调用 enable.ps1 文件。这两个文件都在同一个文件夹中。所以,我认为可以为此目的使用以下代码。

以下是我在 begin.ps1 中编写的用于调用的代码。

#
# begin.ps1
#



function MapDrives ($Message)
    {
        Write-Host Network drives does not exist till now. Trying again to connect
        Write-Host ...............................................................
        WriteInLogFile "Network drives does not exist till now. Trying again to connect"

        $ScriptPath = Split-Path $MyInvocation.InvocationName
& "$ScriptPath\enable.ps1"


        cmd /c pause | out-null
        Start-Sleep -s 20
    }

我要调用的PowerShell文件: enable.ps1

  • 我正在使用Visual Studio 2015
  • Windows 7
  • PowerShell 5
  • begin.ps1和enable.ps1都位于相同的文件夹位置:

    C:\ Users \ srijani.ghosh \ Documents \ visual studio 2015 \ Projects \ test \ test

你对我该如何处理这个有什么想法吗?

P.S:马丁建议做了一些改变。现在代码看起来像这样:

function MapDrives ($Message)
{
    Write-Host Network drives does not exist till now. Trying again to connect
    Write-Host ...............................................................
    WriteInLogFile "Network drives does not exist till now. Trying again to connect"

    $ScriptPath = split-path -parent $MyInvocation.MyCommand.Definition
    & "$ScriptPath\enable.ps1"


    cmd /c pause | out-null
    Start-Sleep -s 20
}

而且,我试图在PowerShell ISE中运行它。它给出了这个错误。

Network drives does not exist till now. Trying again to connect
...............................................................
& : The module 'param($Message)
    Write-Host Network drives does not exist till now. Trying again to connect
    Write-Host ...............................................................
    WriteInLogFile "Network drives does not exist till now. Trying again to connect"
    $ScriptPath = split-path -parent $MyInvocation.MyCommand.Definition
    & "$ScriptPath' could not be loaded. For more information, run 'Import-Module param($Message)
    Write-Host Network drives does not exist till now. Trying again to connect
    Write-Host ...............................................................
    WriteInLogFile "Network drives does not exist till now. Trying again to connect"
    $ScriptPath = split-path -parent $MyInvocation.MyCommand.Definition
    & "$ScriptPath'.
At C:\Users\srijani.ghosh\Documents\visual studio 2015\Projects\test\test\begin.ps1:45 char:7
+     & "$ScriptPath\enable.ps1"
+       ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (param($Message)...cmd \enable.ps1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CouldNotAutoLoadModule

1 个答案:

答案 0 :(得分:0)

你做得对。但是,$ScriptPath似乎不包含任何值(正如您在错误消息中看到的那样)。

您可能必须替换

$ScriptPath = Split-Path $MyInvocation.InvocationName

$ScriptPath = split-path -parent $MyInvocation.MyCommand.Definition