How to run a PowerShell command silently?

I want to execute a PowerShell command silently with no blue screen.

How can I do this from the PowerShell command?

I tried this. . .

PowerShell.exe -windowstyle hidden 

but it didn't work—the command was executed but with the blue screen still.


Solution 1:

Run a PowerShell Command Silently from a Prompt

As stated. . .

"You can use PowerShell.exe to start a PowerShell session from the command line of another tool, such as Cmd.exe, or use it at the PowerShell command line to start a new session. Use the parameters to customize the session."


-WindowStyle

Sets the window style for the session. Valid values are Normal, Minimized, Maximized and Hidden.

-Command

Executes the specified commands (and any parameters) as though they were typed at the PowerShell command prompt, and then exits, unless the NoExit parameter is specified. Essentially, any text after -Command is sent as a single command line to PowerShell


Syntax

powershell -windowstyle hidden -command <PowerShell Command String>

Verifiable Examples

1. Command Prompt (cmd)

powershell -windowstyle hidden -command get-childitem -path c:\ ^| out-file "C:\Folder\Log\log.txt"

enter image description here

Note: With cmd the [|] pipe symbol needs escaped with the [^] caret symbol so "^|".


2. PowerShell Prompt

powershell -windowstyle hidden -command get-childitem -path c:\ | out-file "C:\Folder\Log\log.txt"

enter image description here

Note: After running, open log.txt to verify its content since out-file directs it the output.


Further Resources

  • PowerShell.exe Command-Line Help

Solution 2:

Not sure where I picked these lines up at but some nice functions to show and hide the console.

Show/Hide Powershell Window

Function Show-Console {
$consolePtr = [Console.Window]::GetConsoleWindow()
[Console.Window]::ShowWindow($consolePtr, 5)
}

Function Hide-Console {
$consolePtr = [Console.Window]::GetConsoleWindow()
[Console.Window]::ShowWindow($consolePtr, 0)
}

I use it for my gui apps when I want to hide the ps in background:

Map: Show/Hide Powershell Windows Checkbox

$cb_PSCheckbox.Add_Checked({Show-Console})
$cb_PSCheckbox.Add_UnChecked({Hide-Console})