1

I have a script based powershell module (.psm1) and I have it imported into my main script. This module however needs to call a batch file that is located inside its same directory but apparently it is unable to see it. Currently the function in question looks like this:

function MyFunction
{
    & .\myBatch.bat $param1 $param2
}

How can I make the function see the batch file?

m4tx
  • 4,139
  • 5
  • 37
  • 61
Mike Cheel
  • 12,626
  • 10
  • 72
  • 101

2 Answers2

3

. is the current working directory, not the directory in which the module resides. The latter can be determined via the MyInvocation variable. Change your function to this:

function MyFunction {
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  $dir = Split-Path $Invocation.MyCommand.Path
  $cmd = Join-Path $dir "myBatch.bat"
  & $cmd $param1 $param2
}
Community
  • 1
  • 1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Why are you accessing **MyInvocation** in the parent scope? Wouldn't it be defined in the local (script) scope? I tested this and it doesn't work - the **.Path** property is null. I'd just access **$MyInvocation** directly from the script with no scope modifiers. – Adi Inbar Jul 11 '13 at 16:48
  • The function is defined in a module, and he needs the path of that module, not of the script importing the module. – Ansgar Wiechers Jul 11 '13 at 17:50
  • I suggest a more compact version: `& (Join-Path (Split-Path $script:MyInvocation.MyCommand.Path) 'myBatch.bat') $param1 $param2` – Adi Inbar Jul 11 '13 at 18:43
  • @AdiInbar My answer has separate statements, because that way it's clearer what each step does. But thanks for the suggestion. – Ansgar Wiechers Jul 11 '13 at 18:47
1

Try this:

function MyFunction {
  & (Join-Path (Split-Path $MyInvocation.MyCommand.Path) 'myBatch.bat') $param1 $param2
}
Adi Inbar
  • 12,097
  • 13
  • 56
  • 69