Why do powershell modules not import when running powershell via start process in c#?

c#, powershell, windows

Solution

So it turns out to be related to the platform target. Building as AnyCPU (with the 'prefer 32bit' checkbox checked) or building as x86 and we see this issue. Building as x64 and the issue goes away on the 64bit windows I'm installing on.

Problem

I have a c# application which uses the following code to shell out a call to a powershell script: ``` string scriptFileToExecute = "someScript.ps1; var startInfo = new ProcessStartInfo(); startInfo.FileName = @"powershell.exe"; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = false; startInfo.Arguments = string.Format(@"& '{0}' '{1}'", scriptFileToExecute, "argument"); var process = new Process { StartInfo = startInfo }; process.Start(); string output = process.StandardOutput.ReadToEnd(); ``` This works ok and runs the script. However when I include this line in the script: ``` Import-Module ServerManager ``` The script fails: `errors occurred during script execution: Import-Module : The specified module 'Servermanager' was not loaded because no valid module file was found in any module directory.` This works fine when I run the script just in powershell on the machine. Doing a Get-Module : Format-List on the machine results in: `Name : Servermanager Path : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Servermanager\ServerManager.psm1 Description : ModuleType : Script Version : 2.0.0.0 NestedModules : {Microsoft.Windows.ServerManager.PowerShell} ExportedFunctions : {Disable-ServerManagerStandardUserRemoting, Enable-ServerManagerStandardUserRemoting} ExportedCmdlets : {Get-WindowsFeature, Install-WindowsFeature, Uninstall-WindowsFeature} ExportedVariables : ExportedAliases : {Add-WindowsFeature, Remove-WindowsFeature}` and including `$env:path` in the shelled out script results in: `C:\Windows\system32; C:\Windows;C:\Windows\System32\Wbem; C:\Windows\System32\WindowsPowerShell\v1.0\; C:\Program Files\Microsoft\Web Platform Installer\; C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\; C:\Program Files\Microsoft SQL Server\110\Tools\Binn\` and `$env:PSModulePath` outputs: `C:\Users\Administrator.PORTAL\Documents\WindowsPowerShell\Modules; C:\Program Files (x86)\WindowsPowerShell\Modules; C:\Windows\system32\WindowsPowerShell\v1.0\Modules\` Which seems to imply that it should load the module, as it exists at `C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Servermanager\ServerManager.psm1` I've also checked that the script runs as the same user with the same version of powershell when invoked from the app as when run from PS directly. What could be preventing PS from loading the ServerManager module?

Original source

Related problems