Coder Social home page Coder Social logo

mscholtes / psvirtualdesktop Goto Github PK

View Code? Open in Web Editor NEW
294.0 294.0 18.0 229 KB

VirtualDesktop is a Powershell module that provides commandlets to manage virtual desktops of Windows 10.

License: MIT License

PowerShell 98.91% Batchfile 1.09%
desktop powershell virtualdesktop

psvirtualdesktop's People

Contributors

mscholtes avatar sirandros avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

psvirtualdesktop's Issues

problem when try to move virtualbox machine

Hello,

I have no problem to move notepad to my 1 virtual screen (see Bellow)

Move-Window -Desktop (Desktop 1) -Hwnd ((Get-Process "notepad")[0].MainWindowHandle)

but when trying with the process of vbox with the following command :

Move-Window -Desktop (Desktop 1) -Hwnd ((Get-Process "VirtualBoxVM")[0].MainWindowHandle)

but i have the following error :

PS C:\Users\lasag> Move-Window -Desktop (Desktop 1) -Hwnd ((Get-Process "VirtualBoxVM")[0].MainWindowHandle)
MethodInvocationException: C:\Program Files\WindowsPowerShell\Modules\VirtualDesktop\1.5.1\VirtualDesktop.ps1:2305:3
Line |
2305 |          $Desktop.MoveWindow($Hwnd)
     |          ~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "MoveWindow" with "1" argument(s): "Value cannot be null."

IsVisible Left                   Right
--------- ----                   -----
    False VirtualDesktop.Desktop
   

"Get-DesktopList" not recognized

Hey, just started getting this error while using the SyncVirtualDesktop add on. It was working fine before.
image
I believe it started after a recent Windows update... Windows info is below!

Edition Windows 11 Home
Version 22H2
Installed on ‎6/‎9/‎2023
OS build 22621.2215
Experience Windows Feature Experience Pack 1000.22662.1000.0

Let me know if I can provide any further info to help!

Problem with switch

Hi,
i tried with a simple script to switch between two desktops every x seconds. It works only for a few switches and than it will be lagging on one screen and not switch correctly. Any suggestion?

while($true) { Get-Desktop 1 | Switch-Desktop Start-Sleep 5 Get-Desktop 0 | Switch-Desktop }

Set-DesktopName -Name "Name" only changes the GUI name

When using Set-DesktopName -Name "Name" the name is not shown in Get-DesktopList.
The name is shown when viewing available desktops by the GUI.
The set name cannot be used by switch-Desktop but the name shown in Get-DesktopList can be used.

Command run as Local admin and RunAs Administrator
Version tested: 1.5.7, 2024-02-15

PS C:\Users\LocalAdmin> Get-DesktopList

Number Name      Wallpaper Visible
------ ----      --------- -------
     0 Desktop 1              True


PS C:\Users\LocalAdmin> New-Desktop | Set-DesktopName -Name "TheNewOne"
PS C:\Users\LocalAdmin> Get-DesktopList

Number Name      Wallpaper Visible
------ ----      --------- -------
     0 Desktop 1              True
     1 Desktop 2             False

PS C:\Users\LocalAdmin> Switch-Desktop -name "TheNewOne"
Switch-Desktop : A parameter cannot be found that matches parameter name 'name'.
At line:1 char:16
+ Switch-Desktop -name "TheNewOne"
+                ~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Switch-Desktop], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Switch-Desktop

PS C:\Users\LocalAdmin> Switch-Desktop  "TheNewOne"
Switch-Desktop : No desktop with name part 'TheNewOne' found
At line:1 char:1
+ Switch-Desktop  "TheNewOne"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Switch-Desktop

PS C:\Users\LocalAdmin> Switch-Desktop  "Desktop 2"
Desktop Switched 

Set-DesktopName no longer functional

I caught the comment in another open issue that Set-DesktopName was not functioning in Powershell Core. It seems that Set-DesktopName is no longer functional for older versions of Powershell either. No errors whatsoever, the cmdlet acts as if it has made a change, but never actually does so.

PS C:\Users> Set-DesktopName -Name "Excel" -desktop 1
PS C:\Users> Get-DesktopList

Number Name Visible


 0 Desktop 1    True
 1 Desktop 2   False
 2 Desktop 3   False
 3 Desktop 4   False
 4 Desktop 5   False
 5 Desktop 6   False

PS C:\Users> get-host | select version

Version

5.1.18362.1171

PS C:\Users> get-module virtualdesktop | select version

Version

1.3.0

Automation of Desktop Management for a devops Geek

I would like to get feedback on the Desktop automation.
I have 7 desktops and I want to launch 50 apps when my desktop starts

Here is the repo
https://github.com/rifaterdemsahin/workstation/blob/master/starttheengines.ps1

cls
write-host "Most methods are here https://github.com/MScholtes/PSVirtualDesktop#remove-desktop--desktop-desktop"

Import-Module VirtualDesktop

function startminiprocess {

param (
   [string]$processpath,
   [int]$desktopIndex
   )

write-host "Switch started desktop" $desktopIndex
Switch-Desktop -Desktop $desktopIndex


write-host "If it is allready on find the process and switch" 
write-host "TODO" 


$proc = Start-Process $processpath -PassThru

while ( ($myhandlepointer = $proc.MainWindowHandle) -eq 0 ) {
    write-host "0 the process handle is not ready for : " $processpath
}
write-host "Handler after waiting for the handler id: $myhandlepointer"

$mycurrentDesktop = Get-CurrentDesktop
write-host "1 move started to " $desktopIndex
Move-Window -Desktop $mycurrentDesktop -Hwnd $myhandlepointer

}

Write-Host "Imported modules"

Write-Host "Start the machine"

Write-Host "Cleanup previous action"
Write-Host "DesktopList"
Get-DesktopList
Start-Sleep -s 6

$i=0
$desktopCount=Get-DesktopCount
Write-Host "Desktop Count" $desktopCount

Write-Host "Delete Virtual Desktops"
--$desktopCount

if ($desktopCount -gt 1) {
$desktopCount=$desktopCount
for ($i = $desktopCount; $i -ge 0; $i--)
{
Write-Host "Deleting Desktop Index " $i

    if($i -ne 0)
        {Remove-Desktop $i}
    Start-Sleep -s 1
    Write-Host "Deleted Desktop" $i
}

}

Write-Host "Create all the Desktops and switch to them than start to create the apps"
New-Desktop | Set-DesktopName -Name "Desktop"
New-Desktop | Set-DesktopName -Name "Editting"
New-Desktop | Set-DesktopName -Name "Tweet"
New-Desktop | Set-DesktopName -Name "Notion"
New-Desktop | Set-DesktopName -Name "Code"
New-Desktop | Set-DesktopName -Name "Instant Message"
New-Desktop | Set-DesktopName -Name "Watch"
New-Desktop | Set-DesktopName -Name "Operating System"
New-Desktop | Set-DesktopName -Name "Contracting"

Start-Sleep 5
write-host "Left over desktop messes it up"

$desktopindex =( Get-DesktopIndex -Desktop "Instant Message")
startminiprocess -processpath "C:\Program Files (x86)\Microsoft\Skype for Desktop\Skype.exe" -desktop $desktopindex
startminiprocess -processpath "C:\Users\erdem\AppData\Roaming\Telegram Desktop\Telegram.exe" -desktop $desktopindex
startminiprocess -processpath "C:\Users\erdem\AppData\Local\Programs\signal-desktop\Signal.exe" -desktop $desktopindex
startminiprocess -processpath "C:\Program Files\WindowsApps\5319275A.WhatsAppDesktop_2.2126.11.0_x64__cv1g1gvanyjgm\app\Whatsapp.exe" -desktop $desktopindex
startminiprocess -processpath "C:\Users\erdem\AppData\Local\Discord\Update.exe --processStart Discord.exe" -desktop $desktopindex

Start-Sleep 5
return
$processpath = "C:\Program Files\Microsoft VS Code\Code.exe"
$proc = Start-Process $processpath -PassThru
while ( ($myhandlepointernew = $proc.MainWindowHandle) -eq 0 ) {
write-host "the process handle is not ready:" $processpath
}
Move-Window -Desktop $mydesktop -Hwnd $myhandlepointernew
write-host "Handler after waiting for the handler id: $myhandlepointernew"

Write-Host "Open Stream Labs"
Start-Process "C:\Program Files\Streamlabs OBS\Streamlabs OBS.exe"
Write-Host "XSplit"
Write-Host "VCam"

Write-Host "Start programs ended"

Switch-Desktop -Desktop desktop

Write-Host "DesktopCount"
Get-DesktopCount

Write-Host "DesktopList"
Get-DesktopList

Write-Host "Ended Start Machine"
Write-Host "References wait issue https://www.reddit.com/r/PowerShell/comments/or9ee9/why_cant_i_get_the_windows_handle_id_from_the/"
Write-Host "References Erdem github https://github.com/rifaterdemsahin/workstation/blob/master/starttheengines.ps1"
Write-Host "References Virtual Desktop Library Reference https://github.com/MScholtes/PSVirtualDesktop"

Find-WindowHandle returns 0

Hello. When I use a Find-WindowHandle on an explorer window that has a disk selected (under This PC), it returns 0. Change the selection to a folder, and it worlk as expected. easy to replicate. Open an explorer window, click the > next to This PC, and select the C: drive, run this code. Then select a folder on the left navigation pane in explorer, and run this code.

# source the Virtual Desktops modules
. C:\Users\allan\Documents\WindowsPowerShell\Scripts\VirtualDesktop.ps1

# assume there are explorer windows open, and we need to move them to the new Desktop
$explorerObject = New-Object -com "Shell.Application"
$explorerWindowTitles = $explorerObject.windows() | select-object LocationName
foreach ($i in $explorerWindowTitles) {
  $wh = Find-WindowHandle $i.LocationName
  write-host " location:" $i.LocationName " handle: $wh"
}

Get-DesktopFromWindow does not work

I am on Windows 11 and I can't seem to get the Get-DesktopFromWindow function to work. It always gives me the value "VirtualDesktop.Desktop even though my notepad window is placed on the second virtual screen (called Playnite). Am I doing something wrong? See my code below.

$OldDesktop = Get-CurrentDesktop
$OldDesktop | Set-DesktopName -Name "Desktop"
$NewDesktop = New-Desktop
$NewDesktop | Set-DesktopName -Name "Playnite"

Add-Type -AssemblyName PresentationCore,PresentationFramework
$msgBody = Get-DesktopFromWindow ((Get-Process "notepad")[0].MainWindowHandle)
[System.Windows.MessageBox]::Show($msgBody)``

how do I get a "mainwindowhandle" for an electron app?

I'm running multiple instances of VS Code, but I see this:

PS C:\WINDOWS\system32> Get-Process "code"

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    346      19    34004      82132       4.78   3284   1 Code
    182      13    19284      72712       0.23   3400   1 Code
    175      12    18808      72200       0.19   3688   1 Code
    387      24   568032     544560      11.17   3828   1 Code
    855      36    34464      83340       2.23   4352   1 Code
    303      12     9684      24924       0.00   7388   1 Code
    180      13    21512      71600       0.19   8040   1 Code
    170      13    58880     110720       2.05  12164   1 Code
    178      13    35220      87004       1.58  13584   1 Code
    291      20    12500      37916       0.06  14556   1 Code
    198      14   181940     233804      13.02  17004   1 Code
    466      15    32148      75732       0.38  18000   1 Code
    180      13    21464      72452       0.27  18044   1 Code
    190      13   200424     253308      13.61  18408   1 Code
    458      26   123692     156188       9.55  18456   1 Code
    357      30   502188     481352       9.33  19620   1 Code
    169      12    17696      69844       0.14  19960   1 Code
    671      36   190372     104872       4.72  20648   1 Code
    501      25   114704     158452       8.64  21320   1 Code
    184      13    34308      87296       9.41  21444   1 Code
    184      13    46372      93752      13.00  21480   1 Code
    171      12    17416      70808       0.16  23036   1 Code

Similarly, if I do this:

PS C:\WINDOWS\system32> (Get-Process "code").MainWindowHandle
0
0
0
0
1640298
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

Now, I've figured out that I can do something like this to load a main window handle from a window title name: (Get-Process | Where-Object { $_.MainWindowTitle -like '*code*' }).MainWindowHandle

However, if I run multiple VS Code instances, there's only ever one active at a time.

My goal is to script 5 VS Code instances across multiple virtual desktops (and ideally, chrome too, but I got stuck here), as well as pin a few applications.

Is there any way to do this?

new-desktop causes exception "attempted to read or write protected memory"

Hi, I'm getting this issue. I'm not exactly sure why its happening.

Windows 22h2 (os build 22621.2215)

virtualdesktop version 1.5.4

Unhandled Exception: System. AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
process exited with code 3221225477 (0xc0000005)]

IMG_8733

22H2 - MS breaking compatibility once again

Hi,

After update to 22H2, the API is unfortunately broken again, and throwing an exception when trying to create a new virtual desktop:

virtualDesktop_fault

Hope you have time to take a look at it.

Thanks,
Morten

Is there an offline install?

I see that you provide a link to a nupkg file but I'm not sure what to do with that? Is there a powershell command that can take a nupkg and install it?

When switching desktops there are no active windows.

When switching desktops all windows are deselected. It would be best to be able to switch to a desktop and have the topmost application already selected. Right now if I switch desktops I have to still use my mouse to select a window or alt-tab.

How hard would it be to add shortcuts?

I'd like to be able to switch desktops by using shortcuts.
By default, we can use CTRL + WINDOWS + Right/Left in order to switch between desktops but I'd like to also be able to use numbers.

CTRL + WINDOWS + would go to desktop

Any idea on how I could implement this? Would it be fast to run your PowerShell commands after pressing a key?

`Move-Window` run-time error

> Move-Window -Desktop (Get-CurrentDesktop) -Hwnd 328668 -Verbose # NOTE: the handle provided is valid.
VERBOSE: Moving window to desktop number 0 ('Desktop 1')
MethodInvocationException: C:\Users\Boss\Documents\PowerShell\Modules\VirtualDesktop\1.3.0\VirtualDesktop.ps1:1799
Line |
1799 |          $Desktop.MoveWindow([IntPtr]$Hwnd)
     |          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "MoveWindow" with "1" argument(s): "Marshalling as IInspectable is not supported in
     | the .NET runtime."
> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      7.1.0
PSEdition                      Core
GitCommitId                    7.1.0
OS                             Microsoft Windows 10.0.19042
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Given valid values for both parameters, this commandlet always crashes with this error.

The type initializer for 'VirtualDesktop.DesktopManager' threw an exception.

MethodInvocationException: C:\Users\bedalus\Documents\PowerShell\Modules\VirtualDesktop\1.5.6\VirtualDesktop.ps1:2725
Line |
2725 | [VirtualDesktop.Desktop]::PinWindow([IntPtr]$Hwnd)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Exception calling "PinWindow" with "1" argument(s): "The type initializer for 'VirtualDesktop.DesktopManager'
| threw an exception."

Error above. This is on Windows 11 after the last OS update, this error was new. Tried to resolve by updating powershell, but did not help.

Great tool by the way, thanks!

PowerShell Core incompatibility with V1.2.0

Hi,

Error occurs on Get-Desktop 1 call in v1.2.0. Below is the dump of the error.

OS Info:
Version: 20H2
Build: 19042.630
Arch: x64

Add-Type: C:\Users\shmshd\Desktop\Module\VirtualDesktop.ps1:45
Line |
  45 |  Add-Type -Language CSharp -TypeDefinition @"
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | (351,27): error CS1069: The type name 'Registry' could not be found in the namespace
     | 'Microsoft.Win32'. This type has been forwarded to assembly 'Microsoft.Win32.Registry,
     | Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' Consider adding a reference to that
     | assembly.     desktopName =
     | (string)Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\VirtualDesktops\\Desktops\\{" + guid.ToString() + "}", "Name", null);                           ^

Add-Type: C:\Users\shmshd\Desktop\Module\VirtualDesktop.ps1:45
Line |
  45 |  Add-Type -Language CSharp -TypeDefinition @"
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | (367,27): error CS1069: The type name 'Registry' could not be found in the namespace
     | 'Microsoft.Win32'. This type has been forwarded to assembly 'Microsoft.Win32.Registry,
     | Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' Consider adding a reference to that
     | assembly.     desktopName =
     | (string)Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\VirtualDesktops\\Desktops\\{" + guid.ToString() + "}", "Name", null);                           ^

Add-Type: C:\Users\shmshd\Desktop\Module\VirtualDesktop.ps1:45
Line |
  45 |  Add-Type -Language CSharp -TypeDefinition @"
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot add type. Compilation errors occurred.

InvalidOperation: C:\Users\shmshd\Desktop\Module\VirtualDesktop.ps1:1003
Line |
1003 |      [OutputType([VirtualDesktop.Desktop])]
     |                  ~~~~~~~~~~~~~~~~~~~~~~~~
     | Unable to find type [VirtualDesktop.Desktop].

InvalidOperation: C:\Users\shmshd\Desktop\Module\VirtualDesktop.ps1:1003
Line |
1003 |      [OutputType([VirtualDesktop.Desktop])]
     |                  ~~~~~~~~~~~~~~~~~~~~~~~~
     | Unable to find type [VirtualDesktop.Desktop].

InvalidOperation: C:\Users\shmshd\Desktop\Module\VirtualDesktop.ps1:1003
Line |
1003 |      [OutputType([VirtualDesktop.Desktop])]
     |                  ~~~~~~~~~~~~~~~~~~~~~~~~
     | Unable to find type [VirtualDesktop.Desktop].

InvalidOperation: C:\Users\shmshd\Desktop\Module\VirtualDesktop.ps1:1003
Line |
1003 |      [OutputType([VirtualDesktop.Desktop])]
     |                  ~~~~~~~~~~~~~~~~~~~~~~~~
     | Unable to find type [VirtualDesktop.Desktop].

Bug in Get-DesktopIndex

When calling Get-DesktopIndex without arguments, the current desktop index should be returned, instead we get an error message. To fix this, the body of the first condition should be changed from:

$Desktop = [VirtualDesktop.Desktop]::FromDesktop(([VirtualDesktop.Desktop]::Current))
To:
$Desktop = [VirtualDesktop.Desktop]::Current

I just stared looking at PS yesterday, so take this with a gain of salt.

Error moving window (Teams App)

I'm trying to move the Microsoft Teams App window to one of my desktops with this command:

Get-desktop 3 | Move-Window (Find-WindowHandle "Microsoft Teams") | Switch-Desktop

This works OK for other apps like Outlook, but I get the following error when I try with Microsoft Teams:

MethodInvocationException: D:\OneDrive\Documents\PowerShell\Modules\VirtualDesktop\1.5.8\VirtualDesktop.ps1:2471
Line |
2471 | $Hwnd.MoveWindow([IntPtr]$Desktop)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Exception calling "MoveWindow" with "1" argument(s): "Element not found. (0x8002802B (TYPE_E_ELEMENTNOTFOUND))"

Find-WindowHandle "Microsoft Teams" does return a handle correctly
--> name of window changes depending on whats showing in TEAMS but it always ends with "Microsoft Teams" so Find-WindowHandle returns same handle every time.

Find desktop with given name or create if necessary

For my use case, I needed a function that, for a given name, either finds a pre-existing desktop with that name or creates a new one with that name if none could be found.

I have written such a function below and just wanted to share it with you 😄
I leave it to you to decide what to do with it.
(Not sure if the functionality is needed often enough to merit addition to your module, so perhaps, just linking this issue code from the readme as an example might be good enough 😄)

PS: Thank you very much for this module! It's highly useful for automating my daily workflows.

function Request-NamedDesktop {
	<#
		.SYNOPSIS
			Retrieves or creates (if non-existing) the virtual desktop with the given name.
		
		.INPUTS
			The desktop name can be piped into this function.

		.OUTPUTS
			A virtual desktop with the given name.

		.EXAMPLE
			Request-NamedDesktop "My Secret Desktop"
		.EXAMPLE
			"My Secret Desktop" | Request-NamedDesktop | Switch-Desktop
		
		.NOTES
			The function assumes that the PSVirtualDesktop module [0] is installed.

			[0]: https://github.com/MScholtes/PSVirtualDesktop
	#>
	param(
		<#
			The name of the virtual desktop to retrieve or create (if non-existing)
		#>
		[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
		[ValidateNotNullOrEmpty()]	
		[string]$name
	)

	$desktop = Get-DesktopList | Where-Object Name -eq $name | Select-Object -First 1

	# The if condition below is susceptible to a TOCTOU bug (https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use).
	# But this is probably okay since virtual desktops aren't something that is created every second.
	if ($desktop) {
		Get-Desktop -Index $desktop.Number
	} else {
		$desktop = New-Desktop
		$desktop | Set-DesktopName -Name $name
		$desktop
	}
}

support DSC

it would be great if this module provided a DSC commands out of the box to enable management of virtual desktops as code.

possible workaround is to use the PSDscResources/Script and call the functions.

The things that make sense to me are

  1. create desktop with a name (or perhaps require the ID)
  2. set wallpaper for a speciifc desktop
  3. set name for a specific desktop (depending on how the desktops are identified - GUID vs naming)

Feedback and Request

This is absolutely wonderful and going to save me a lot of time 😁

Would there be a way to move a window to a particular screen within the Virtual Desktop?

Issue when moving windows with multiple processes/tabs

I'm having a difficulty moving a window with multiple processes, like Chrome and Explorer, to another virtual desktop using the samples in the Github Readme.

Expected behavior: The sample command is input a Powershell session, and the window (e.g Chrome) is moved to the desired desktop (The third one, number 2).

Actual Behavior: The command gives an error in parameters akin to this (The second command is to prove Chrome exists, being a window with two tabs)

Screenshot_39

Edit: I think it has to do with how MainWindowHandle gets the Handle number, as this StackOverflow post puts it (https://stackoverflow.com/questions/4727023/why-cant-get-the-main-window-handle-for-a-started-process). It may also happen with fullscreen apps.

The type initializer for 'VirtualDesktop.DesktopManager' threw an exception

Two days ago, my Windows 11 was upgraded to version 23H2. Now I get the following error:

get-desktoplist

Der Typeninitialisierer für "VirtualDesktop.DesktopManager" hat eine Ausnahme verursacht.
In C:\Program Files\WindowsPowerShell\Modules\VirtualDesktop\1.5.6\VirtualDesktop.ps1:1227 Zeichen:16

  •     for ($I = 0; $I -lt [VirtualDesktop.Desktop]::Count; $I++)
    
  •                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : OperationStopped: (:) [], TypeInitializationException
    • FullyQualifiedErrorId : System.TypeInitializationException

My Windows Version:
Edition Windows 11 Enterprise
Version 23H2
Installiert am ‎26.‎11.‎2023
Betriebssystembuild 22631.3085
Leistung Windows Feature Experience Pack 1000.22684.1000.0

Windows 11 24H2 Update broke the wallpaper functionality again 😔

The Windows 11 24H2 update was released to the Insider 'Release Preview' channel and seems to have broken this module.

Also it causes some strange behavior in renaming the virtual desktops.

For example, if I use this command:
Set-DesktopWallpaper -Desktop General -Path 'C:\Users\Joe\Desktop\Test.png' -PassThru

It doesn't change the wallpaper, but strangely changes the name of the virtual desktop to the image path

Here's a short screen recording demonstrating this behavior (on Google Drive because it's a bit too big for GitHub):
https://drive.google.com/file/d/1w5N5zhmJuprU-VgUGR8Qe2EEGeLv6Z-J/view?usp=sharing

Here's notes for the video:
0:03 - Showing the initial name of the first virtual desktop as "General"
0:10 - Entering the command above
0:15 - Command seems to run without error
0:17 - Virtual desktop name has changed to the image path


If I run it with -verbose this is the output:

PS C:\Windows\System32> Set-DesktopWallpaper -Desktop General -Path 'C:\Users\Joe\Desktop\Test.png' -PassThru -Verbose
VERBOSE: Set name of desktop number 0 ('General') to 'C:\Users\Joe\Desktop\Test.png'

IsVisible Left Right
--------- ---- -----
     True      VirtualDesktop.Desktop

Some additional things I've tried with the same result:

Running without -PassThru:

PS C:\Windows\System32> Set-DesktopWallpaper -Desktop General -Path 'C:\Users\Joe\Desktop\Test.png' -Verbose
VERBOSE: Set name of desktop number 0 ('General') to 'C:\Users\Joe\Desktop\Test.png'

Running by specifying the desktop index (0) instead of name (Also both with and without -Passthru)

PS C:\Windows\System32> Set-DesktopWallpaper -Desktop 0 -Path 'C:\Users\Joe\Desktop\Test.png' -Verbose
VERBOSE: Set name of desktop number 0 ('General') to 'C:\Users\Joe\Desktop\Test.png'

Windows 11 22H2 2261.2283 Breaks Functionality on v1.5.2

Synopsis

Updated my PC last night to Windows 11 22H2 22621.2283, went to run my work startup script this morning and the desktop switch errored out. Update-Module fixed my issue.
This is the output from Switch-Desktop 1

VirtualDesktop.DesktopManager' threw an exception."
At C:\Program 
Files\WindowsPowerShell\Modules\VirtualDesktop\1.5.2\VirtualDesktop.ps1:1226 
char:4
+             $TempDesktop = [VirtualDesktop.Desktop]::FromIndex($Deskt ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : TypeInitializationException

Tried doing a Get-DesktopList and that returned

The type initializer for 'VirtualDesktop.DesktopManager' threw an exception.
At C:\Program
Files\WindowsPowerShell\Modules\VirtualDesktop\1.5.2\VirtualDesktop.ps1:1085   
char:16
+         for ($I = 0; $I -lt [VirtualDesktop.Desktop]::Count; $I++)
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], TypeInitializationExc  
   eption
    + FullyQualifiedErrorId : System.TypeInitializationException

Updating fixed my issue, may be worth calling out in the readme for users to run Update-Module if they experience any issues.

Windows 11: The type initializer for 'VirtualDesktop.DesktopManager' threw an exception

Commands from the module fail for me on Powershell 5.1 on Windows 11 but not on Windows 10.

OS:

  • Windows 11 Home
  • Version 21H2
  • OS build 22000.120

$PSVersionTable:

Name Value
PSVersion 5.1.22000.65
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.22000.65
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1

Output of Get-CurrentDesktop:

The type initializer for 'VirtualDesktop.DesktopManager' threw an exception.
At C:\Program Files\WindowsPowerShell\Modules\VirtualDesktop\1.3.1\VirtualDesktop.ps1:1091 char:2
+     $Desktop = [VirtualDesktop.Desktop]::Current
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], TypeInitializationException
    + FullyQualifiedErrorId : System.TypeInitializationException

Exception calling "FromDesktop" with "1" argument(s): "Object reference not set to an instance of an object."
At C:\Program Files\WindowsPowerShell\Modules\VirtualDesktop\1.3.1\VirtualDesktop.ps1:1092 char:42
+ ... ktop number $([VirtualDesktop.Desktop]::FromDesktop($Desktop)) ('$([V ...
+                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NullReferenceException

Exception calling "DesktopNameFromDesktop" with "1" argument(s): "Object reference not set to an instance of an
object."
At C:\Program Files\WindowsPowerShell\Modules\VirtualDesktop\1.3.1\VirtualDesktop.ps1:1092 char:95
+ ... sktop)) ('$([VirtualDesktop.Desktop]::DesktopNameFromDesktop($Desktop ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NullReferenceException

Pin-Application $Var

I'm writing a script to pin an app using a stored hwnd value.
I can do this by entering the hwnd value however when using a $var I am unable to and I receive this error:
image

image

PS Script
image

Machine Info: Windows 10
image

Thanks in advance for your help, I'm most definitely over looking some simple :3

Switch desktop animations

In Windows there is an animation for switching to the left and right desktop if you use the keyboard shortcut or touchpad gesture. At the moment the module doesn't make any difference between switching to one or another desktop.

Is it possible to switch to the left and right desktop in the same animated way Windows does it when pressing the shortcut? Does the API provide any way to achieve that result programatically?

FR: Pin application by process

Hello!
Unfortunately, some applications create windows on demand and to pin them you should write watcher to query their windows.
I found, that it's possible to get AppIds for process: MSDN.
I concern that for some (may be most) apps it may not work, because not all apps are modern and not all Win32 app developers explicitly set app id, but its the same for application windows, used in current implementation of Pin-Application cmdlet, I think.
I will create pull request if I found enough time to test it by myself, but I think its not a near future. But if you have some free time - it will be great if you could implement that idea.
Thank you!

[Bug Report] The type initializer for 'VirtualDesktop.DesktopManager' threw an exception.

Title: [Bug Report] The type initializer for 'VirtualDesktop.DesktopManager' threw an exception.

Hello,

I encountered an error when running the SyncVirtualDesktops.ps1 script on my Windows 11 22H2 (OS build 22621.1702) machine.

This is the error message I received:

---------------------------
Script Error
---------------------------
Error(s) running PowerShell script 'scripts\SyncVirtualDesktops.ps1':

�[31;1mOperationStopped: �[0mC:\Users\adam\OneDrive\Documents\PowerShell\Modules\VirtualDesktop\1.5.2\VirtualDesktop.ps1:1085�[0m
�[31;1m�[0m�[36;1mLine |�[0m
�[31;1m�[0m�[36;1m�[36;1m1085 | �[0m         for ($I = 0; �[36;1m$I -lt [VirtualDesktop.Desktop]::Count�[0m; $I++)�[0m
�[31;1m�[0m�[36;1m�[36;1m�[0m�[36;1m�[0m�[36;1m     | �[31;1m                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~�[0m
�[31;1m�[0m�[36;1m�[36;1m�[0m�[36;1m�[0m�[36;1m�[31;1m�[31;1m�[36;1m     | �[31;1mThe type initializer for 'VirtualDesktop.DesktopManager' threw an exception.�[0m

---------------------------
OK   
---------------------------

This is the PowerShell script that I was trying to run:

param (
    [Parameter(Mandatory=$true)][int]$daySegment2,  # 0 = Day, 1 = Night
    [Parameter(Mandatory=$true)][int]$daySegment4,  # -1 = N/A, 0 = Sunrise, 1 = Day, 2 = Sunset, 3 = Night
    [Parameter(Mandatory=$true)][bool]$nightMode,   # True if night mode is enabled
    [Parameter(Mandatory=$false)][string]$imagePath # Path to current wallpaper image
)

If (-Not ($PSBoundParameters.ContainsKey("imagePath"))) {
    Break
}

$currentWinVer = (Get-CimInstance Win32_OperatingSystem).version
$settingsFile = "$((Get-Item $PSCommandPath).BaseName).dat"
$settingsUpdated = $false
if (-Not (Get-Module -ListAvailable -Name VirtualDesktop)) {
    Install-PackageProvider -Name NuGet -Force -Scope CurrentUser
    Install-Module -Name VirtualDesktop -Force -Scope CurrentUser
    $settingsUpdated = $true
} elseif (-Not (Test-Path -Path $settingsFile -PathType Leaf) -Or ($currentWinVer -Ne (Import-Clixml -Path $settingsFile))) {
    Update-Module -Name VirtualDesktop -Force
    $settingsUpdated = $true
}

Get-DesktopList | ForEach-Object {
    if (-Not (Test-CurrentDesktop -Desktop $_.Number)) {
        Set-DesktopWallpaper -Desktop $_.Number -Path $imagePath
    }
}

if ($settingsUpdated) {
    $currentWinVer | Export-Clixml -Path $settingsFile
}

Could you please help me resolve this issue?

Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.