Unable to import Powershell module started from boot process

advertisements

I have a powershell script: MyPSScript.ps1:

function DoFoo() {
  $Powershell = "C:\windows\System32\WindowsPowerShell\v1.0\Powershell.exe"
  $Command = "& C:\Temp\myscript.ps1"
  Start-Process $Powershell -ArgumentList ("-noexit", "-noprofile", "-Command", $Command)
}

In myscript.ps1 I have:

Import-Module "C:\Temp\myscript2.ps1"
DoSomething()

In myscript2.ps1 I have:

function DoSomething() {
  Write-Output "Hello World"
}

The problem is that myscript.ps1 is correctly executed, but the module is not imported as nothing is printed. Also, since I open the new powershell window using -noexit, I can type in it and if I try to call DoSomething, Powershell complains because it cannot find the command.

The funny thing is that, if I try to type manually the same import directive, then it imports the file corrently...

Are there any issues in importing a module from a Powershell which has been called from another process as I am doing?


Beside the typo I fixed (missing "=") in your question, there are several problems in the script you provided. The first one (MyPSScript.ps1) defines a function DoFoo but never calls it. The second one (myscript.ps1) wrongly calls DoSometing() with parentheses. If you fix those two problems, you'll see your "Hello World".

MyPSScript.ps1:

function DoFoo() {
  $Powershell = "C:\windows\System32\WindowsPowerShell\v1.0\Powershell.exe"
  $Command = "& C:\Temp\myscript.ps1"
  Start-Process $Powershell -ArgumentList ("-noexit", "-noprofile", "-Command", $Command)
}

DoFoo

myscript.ps1:

Import-Module "C:\Temp\myscript2.ps1"
DoSomething