1

I have found these two scripts to set the PowerShell windows state and from the experience from other users the scripts are working it happens that I'm not being able to run it

The script 1 is

function Set-WindowState {
param(
    [Parameter()]
    [ValidateSet('FORCEMINIMIZE', 'HIDE', 'MAXIMIZE', 'MINIMIZE', 'RESTORE', 
                 'SHOW', 'SHOWDEFAULT', 'SHOWMAXIMIZED', 'SHOWMINIMIZED', 
                 'SHOWMINNOACTIVE', 'SHOWNA', 'SHOWNOACTIVATE', 'SHOWNORMAL')]
    [Alias('Style')]
    [String] $State = 'SHOW',
    
    [Parameter(ValueFromPipelineByPropertyname='True')]
    [System.IntPtr] $MainWindowHandle = (Get-Process –id $pid).MainWindowHandle,

    [Parameter()]
    [switch] $PassThru

)
BEGIN
{

$WindowStates = @{
    'FORCEMINIMIZE'   = 11
    'HIDE'            = 0
    'MAXIMIZE'        = 3
    'MINIMIZE'        = 6
    'RESTORE'         = 9
    'SHOW'            = 5
    'SHOWDEFAULT'     = 10
    'SHOWMAXIMIZED'   = 3
    'SHOWMINIMIZED'   = 2
    'SHOWMINNOACTIVE' = 7
    'SHOWNA'          = 8
    'SHOWNOACTIVATE'  = 4
    'SHOWNORMAL'      = 1
}
    
$Win32ShowWindowAsync = Add-Type –memberDefinition @” 
[DllImport("user32.dll")] 
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); 
“@ -name “Win32ShowWindowAsync” -namespace Win32Functions –passThru

}
PROCESS
{
    $Win32ShowWindowAsync::ShowWindowAsync($MainWindowHandle, $WindowStates[$State]) | Out-Null
    Write-Verbose ("Set Window State on '{0}' to '{1}' " -f $MainWindowHandle, $State)

    if ($PassThru)
    {
        Write-Output $MainWindowHandle
    }

}
END
{
}

}

Set-Alias -Name 'Set-WindowStyle' -Value 'Set-WindowState'

and when I run it I get

Set-WindowState.ps1:36 char:58
+ $Win32ShowWindowAsync = Add-Type –memberDefinition @† 

if I run .\Set-WindowState.ps1

tried too

Set-WindowStyle -Name Set-WindowStyle -Value 6

but here I get the error

Set-WindowStyle : The term 'Set-WindowStyle' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1
+ Set-WindowStyle -Name Set-WindowStyle -Value 6
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Set-WindowStyle:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

the script 2 is

<#
.Synopsis
   Set the Window State of the Powershell Console Window
.DESCRIPTION
   Enables PowerShell scripts to set the visibility and various states of the PowerShell Console Window
.EXAMPLE
   Set-ConsoleWindowState -WindowState Minimized
.NOTES
   Author: Richard Bunker
   Version History:-
   1.0 - 08/06/2016 - Richard Bunker - Initial Version
.FUNCTIONALITY
   Enables PowerShell scripts to hide and set the various window states of the PowerShell console
#>

$DebugPreference="SilentlyContinue"

$script:showWindowAsync=Add-Type -MemberDefinition @"
[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
"@ -Name "Win32ShowWindowAsync" -Namespace Win32Functions -PassThru

Add-Type @"
    using System;
    using System.Runtime.InteropServices;
    public class SetWindowToFront {
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
    }
"@

function Set-ConsoleWindowState {

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, Position=0)]
        [ValidateSet("Normal", "Maximized","Minimized","Default","Hidden","SetWindowToFront")]
        [String]
        $WindowState="Normal"
    )

    switch ($WindowState)
    {
        'Normal' {$null = $script:showWindowAsync::ShowWindowAsync((Get-Process -id $pid).MainWindowHandle, 1)}
        'Maximized' {$null = $script:showWindowAsync::ShowWindowAsync((Get-Process -id $pid).MainWindowHandle, 3)}
        'Minimized' {$null = $script:showWindowAsync::ShowWindowAsync((Get-Process -id $pid).MainWindowHandle, 2)}
        'Default' {$script:showWindowAsync::ShowWindowAsync((Get-Process -id $pid).MainWindowHandle, 10)}
        'Hidden' {$null = $script:showWindowAsync::ShowWindowAsync((Get-Process -id $pid).MainWindowHandle, 0)}
        'SetWindowToFront' {[void][SetWindowToFront]::SetForegroundWindow((Get-Process -id $pid).MainWindowHandle)}
    }

}

# Export Module Functions:
Export-ModuleMember -Function Set-ConsoleWindowState

running .\SetConsoleWindowState.psm1 -WindowState Minimized I get

Set-ConsoleWindowState : The term 'Set-ConsoleWindowState' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
At line:1 char:1
+ Set-ConsoleWindowState -WindowState Minimized
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Set-ConsoleWindowState:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Can you provide some guidance on how these scripts can be run?

Thanks

EDIT:

On the script 1 I have replaced the " and when run .\Set-WindowState.ps1

I get now

At C:\Desktop\Folder\Set-WindowState.ps1:36 char:54
+ $Win32ShowWindowAsync = Add-Type –memberDefinition @"
+                                                      ~~
The string is missing the terminator: "@.
At C:\Desktop\Folder\Set-WindowState.ps1:59 char:59
+ Set-Alias -Name 'Set-WindowStyle' -Value 'Set-WindowState'
+                                                           ~
Missing closing ')' in expression.
At C:\Desktop\Folder\Set-WindowState.ps1:59 char:59
+ Set-Alias -Name 'Set-WindowStyle' -Value 'Set-WindowState'
+                                                           ~
Missing ')' in function parameter list.
At C:\Desktop\Folder\Set-WindowState.ps1:1 char:26
+ function Set-WindowState {
+                          ~
Missing closing '}' in statement block or type definition.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

On the script 2 the " are the regular ones

dmyx
  • 21
  • 2

1 Answers1

2

Regarding the 1st error, replace all typographic quotes like by ". This is necessary because the C# compiler, which is invoked by Add-Type -TypeDefinition, uses stricter quoting rules than PowerShell.

Regarding the 2nd error, a ".psm1" file is a module that you can't call directly. Use Import-Module first and then call a function that is contained in the module:

Import-Module .\SetConsoleWindowState.psm1
Set-ConsoleWindowState -WindowState Minimized
zett42
  • 25,437
  • 3
  • 35
  • 72
  • Thank you. Regarding the script 2 I'm not getting errors anymore. About this script maybe I misunderstood how it works but when running any command at all from a simple ipconfig to other commands, if doing Set-ConsoleWindowState -WindowState Minimized, shouldn't the console run minimized. Because I have done that but the window hasn't minimized. – dmyx Sep 02 '22 at 11:41
  • @dmyx When you call `Set-ConsoleWindowState -WindowState Minimized` the console window should immediately go into minimized state. It does for me. – zett42 Sep 02 '22 at 12:01
  • I have done that, but nothing happened with any of the windows states. I even tried as admin too but the same. Have you tested the module? Have you succeeded? – dmyx Sep 02 '22 at 21:01
  • @dmyx Yes, I have successfully tested the module with `-WindowState Minimized` and `-WindowState Hidden`. Works for me with PS 5.1 and PS 7.2.6. – zett42 Sep 02 '22 at 21:21
  • Thank you. I was trying with version 10.0.22000.1 It seems that with this version its not working so. – dmyx Sep 02 '22 at 23:21
  • @dmyx That looks like the Windows version. What is shown for `PSVersion` when you enter `$PSVersionTable` in the console? – zett42 Sep 03 '22 at 07:55