# Define the path to the log file
$logFile = "$env:TEMP\ConsoleWindowScript.log"
# Function to log messages
function Log-Message {
param (
[string]$message
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"$timestamp - $message" | Out-File -FilePath $logFile -Append -Encoding utf8
}
# Import necessary namespaces for P/Invoke
Add-Type -Name Window -Namespace Console -MemberDefinition @'
using System;
using System.Runtime.InteropServices;
public class Window {
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
}
'@
try {
# Get the handle to the console window
$consoleHandle = [Console.Window]::GetConsoleWindow()
if ($consoleHandle -eq [IntPtr]::Zero) {
throw "Failed to get console window handle."
}
# Hide the console window
$result = [Console.Window]::ShowWindow($consoleHandle, 0)
if (-not $result) {
throw "Failed to hide the console window."
}
# Log success
Log-Message "Console window hidden successfully."
# Place the rest of your code here
# =================================
# Example of additional code to be executed
Write-Output "The console window is now hidden. Executing additional code..."
# Add your actual code below
# ...
} catch {
# Log the error message
Log-Message "Error: $_"
}