4

I have a simple powershell script to enable a mailbox in Exchange called test.ps1. Here is the script:

add-pssnapin microsoft.exchange.management.powershell.admin Enable-Mailbox -Identity 'gi joe' -database 'myserver\myserver mailbox database 17'

If I go to the Powershell console and type

./test.ps1

It will run successfully. However, if I call it in VB.net using

Process.Start("powershell", "test.ps1")

the terminal flashes too quickly for me to see what it says, and it doesn't create the mailbox. Why does this happen, or how can I stop the terminal from disappearing before I can read the error?

1 Answer 1

5
+50

To see what is going wrong try this instead:

Process.Start("powershell", "-noexit -file c:\<path>\test.ps1")

I suspect the error you get is because you aren't providing a full path to test.ps1.

Another possibility is that your 32-bit VB app needs to launch 64-bit Powershell (snapin or module may only be available there). In that case you need to invoke PowerShell by path and you have to use SysNative in your path to be able to see the 64-bit PowerShell dir.

var powerShellPath = "C:\Windows\SysNative\WindowsPowerShell\v1.0\powershell.exe"
Process.Start(powerShellPath , "-noexit -file c:\<path>\test.ps1")

Sorry that's probably not proper VB syntax but should get you going.

Sign up to request clarification or add additional context in comments.

13 Comments

Thanks, it turns out the error is "no snap-ins have been registered for Windows PowerShell version 2." This is weird, because the first line of the script adds the snap in. Is there a way I can replace "powershell" to include powershell with all moduels? That way I won't need that line of code adding the snapin.
@Austin this sounds like you're running into a 32-bit vs 64-bit issue. When you register a snapin in the 32-bit shell, it isn't automatically registered for the 64-bit shell and vice-versa. Does your VB app run as 64-bit or 32-bit?
You're right, I changed the target cpu to Any CPU and it worked! However, this breaks another part of my application =( Is there a way to force Powershell to start in 32bit mode?
Yes, use the path to the 32-bit version of powershell e.g. C:\Windows\SysWow64\WindowsPowershell\v1.0\powershell.exe. Of course, you might want to use the System.Environment class to get the windir environment variable, rather than hard code c:\windows.
Hmm I still get the same error. Do you have an idea why it works when I set it to Any CPU, but not when I set it to x86?
|

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.