This project is read-only.

ps2exe compiled exe showing a console along with the initiated GUI

Nov 29, 2011 at 7:25 PM

Hi,

we are able to compile our ps1 script with the ps2exe, but when we execute the exe a console is being shown along with our GUI app.

How do we hide the console screen ?

 

Thanks

Raaj

 

Jan 17, 2013 at 4:26 PM

A solution to hiding the console window was posted here in the comments:  http://www.aspnet-answers.com/microsoft/Powershell/30523953/invisible-windows.aspx

Using that code, I use it as a function in my scripts. I call it ConsoleWindow. ConsoleWindow -hidden  will hide the window. ConsoleWindow with no switch will show it again. Here is the code:

 

function ConsoleWindow {
param ([switch] $hidden)

$code = @'
using System;
using System.Runtime.InteropServices;
public class ConsoleHelper
{
private const Int32 SW_HIDE = 0;
private const Int32 SW_SHOW = 5;

[DllImport("user32.dll")]
private static extern Boolean ShowWindow(
IntPtr hWnd,
Int32 nCmdShow);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool AllocConsole();

[DllImport("Kernel32.dll")]
private static extern IntPtr GetConsoleWindow();

public static void HideConsole()
{
IntPtr hwnd = GetConsoleWindow();
if (hwnd != IntPtr.Zero)
{
ShowWindow(hwnd, SW_HIDE);
}
}

public static void ShowConsole()
{
IntPtr hwnd = GetConsoleWindow();
if (hwnd != IntPtr.Zero)
{
ShowWindow(hwnd, SW_SHOW);
}
}
}
'@

[ConsoleHelper] > $null
$ch = [ConsoleHelper]
trap {
# Get an instance of the CSharp code provider
$cp = new-object Microsoft.CSharp.CSharpCodeProvider
# And compiler parameters...
$cpar = New-Object System.CodeDom.Compiler.CompilerParameters
$cpar.GenerateInMemory = $true
$cpar.GenerateExecutable = $false
$cpar.OutputAssembly = "custom"
$cr = $cp.CompileAssemblyFromSource($cpar, $code)
# display any errors (there should be none...)
if ( $cr.Errors.Count)
{
$codeLines = $code.Split("`n");
foreach ($ce in $cr.Errors)
{
write-host "Error: $($codeLines[$($ce.Line - 1)])"
$ce | out-default
}
Throw "Compile failed..."
}
else
{
# don't report the exception
continue
}
}

if ($hidden)
{
$ch::HideConsole()
}
else
{
$ch::ShowConsole()
}
}