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?

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
The function is defined in a module, and he needs the path of that module, not of the script importing the module.
I suggest a more compact version: & (Join-Path (Split-Path $script:MyInvocation.MyCommand.Path) 'myBatch.bat') $param1 $param2
@AdiInbar My answer has separate statements, because that way it's clearer what each step does. But thanks for the suggestion.
1

Try this:

function MyFunction {
  & (Join-Path (Split-Path $MyInvocation.MyCommand.Path) 'myBatch.bat') $param1 $param2
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.