1

I would like to automatically launch a powershell and run a few commands from another powershell (I want to start it from another powershell because of the advantages of functions).
I would like to do so because I'm testing a *.dll coded in C# with powershell and I have to constantly launch and quit powershell because it's not possible to unload a dll in powershell and therefore it's not possible to reload the library with its classes.

Is there a way to automate powershell just like the com-object automation with office?

wullxz
  • 17,830
  • 8
  • 32
  • 51
  • http://stackoverflow.com/questions/18143501/run-powershell-in-new-window –  Nov 14 '14 at 21:12

2 Answers2

3

What about just using a script or script blocks?

powershell {
   Add-Type foo.dll
   [Foo]::DoSomething();
}

should work.

If you need interactivity and need to try multiple commands at will, you could use

powershell -noexit { Add-Type foo.dll }

In that case it can be useful to at least change the prompt color so you know whether you're in the test sub-shell or in the parent one:

function Test-DLL {
  powershell -noexit {
    function prompt {
      Write-Host -n -fore yellow "Test $PWD>"
      ' '
    }

    Add-Type foo.dll
  }
}

I tend to define a small function in the following way too:

"function $([char]4) { exit }" | Invoke-Expression

which allows me to close PowerShell with Ctrl+D, Enter (half an analog to Unix shells).

Joey
  • 344,408
  • 85
  • 689
  • 683
  • I do use add-type. But there are two problems: powershell locks the library and it can't be reloaded with [Reflection.Assembly] (I don't know if this works with add-type because I can't recompile the dll when it's locked). – wullxz Mar 08 '12 at 15:46
  • I'm sorry. I didn't get that you're running powershell instead of a function named powershell ;) It works. Even from powershellISE where I can modify my commands easily. Thanks :) – wullxz Mar 08 '12 at 15:52
  • 1
    The point is that you start another shell that loads the library and close it after you're done testing. My try was to make the launching of the subshell (with loading the library) and optionally a few testing steps as painless as possible. – Joey Mar 08 '12 at 15:52
1

Perhaps not the most elegant solution but should do it (I'm not a PS pro):

cmd /c start powershell
rlegendi
  • 10,466
  • 3
  • 38
  • 50
  • I know this way, but I can't pass commands to the new powershell instance with this. – wullxz Mar 08 '12 at 15:47
  • +1 Passing commands works for me like this: cmd /c start powershell.exe -nologo -noexit -command "cd c:\mydir" (which I've updated above) – 79E09796 Dec 05 '12 at 10:28