From 2c30cf6883839ae248d22fc34c359a7c7d11e79e Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Thu, 12 Nov 2026 00:14:59 -0700 Subject: [PATCH 1/5] Toolbox management: list, upload, delete, and elevated/silent runs - Get-CWCToolbox lists the Toolbox as one object per folder and file with its path (PageService.GetToolbox); -Raw returns the server tree - Add-CWCToolboxItem uploads a file to the shared Toolbox in chunks, or creates a folder (ToolboxService.WriteToolboxFileContent); accepts files from the pipeline - Remove-CWCToolboxItem deletes a Toolbox file or folder (ToolboxService.ProcessToolboxOperation, Delete) - Send-CWCToolboxItem gains -Elevated (QueuedElevatedTool 101) and -Silent (QueuedSilentElevatedTool 117, runs as SYSTEM); credentials connections only - Toolbox paths are normalized and checked before they are sent, so a path that could name the Toolbox root, its parent or another drive is refused - A 401 "Needs permission" on a credentials connection now suggests Connect-CWC -Force: the server stops honouring an older login's management permissions while ordinary calls keep working Event and operation numbers were read from the web client of a live server; listing, upload and the silent run were exercised against it. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 13 +- CHANGELOG.md | 17 + ConnectWiseControlAPI_Functions.md | 9 + Docs/Add-CWCToolboxItem.md | 196 +++++++++ Docs/Get-CWCToolbox.md | 77 ++++ Docs/Remove-CWCToolboxItem.md | 107 +++++ Tests/ConnectWiseControlAPI.Module.Tests.ps1 | 2 + Tests/ConnectWiseControlAPI.Private.Tests.ps1 | 22 +- Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 391 ++++++++++++++++++ source/Private/Invoke-CWCServiceMethod.ps1 | 6 +- source/Private/Invoke-CWCWebRequest.ps1 | 8 + source/Private/Resolve-CWCToolboxPath.ps1 | 41 ++ source/Public/Authentication/Connect-CWC.ps1 | 6 + source/Public/PageService/Get-CWCToolbox.ps1 | 62 +++ source/Public/RestApi/Send-CWCToolboxItem.ps1 | 55 ++- .../ToolboxService/Add-CWCToolboxItem.ps1 | 148 +++++++ .../ToolboxService/Remove-CWCToolboxItem.ps1 | 57 +++ source/prefix.ps1 | 9 +- 18 files changed, 1208 insertions(+), 18 deletions(-) create mode 100644 Docs/Add-CWCToolboxItem.md create mode 100644 Docs/Get-CWCToolbox.md create mode 100644 Docs/Remove-CWCToolboxItem.md create mode 100644 source/Private/Resolve-CWCToolboxPath.ps1 create mode 100644 source/Public/PageService/Get-CWCToolbox.ps1 create mode 100644 source/Public/ToolboxService/Add-CWCToolboxItem.ps1 create mode 100644 source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 diff --git a/AGENTS.md b/AGENTS.md index 0e44e60..ca02d98 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -118,9 +118,9 @@ The `release` artifact is kept for 30 days; re-runs need it. writes `FunctionsToExport` from the `Public/` file names (the source manifest says `'*'`). The source `.psm1` is only for development: it dot-sources the same files and is **not** used by the build, so module-level code belongs in `source/prefix.ps1`. That file holds the TLS setup and the shared constants: `$script:CWCSessionType`, - `$script:CWCSessionEventType` (live-verified numbers), `$script:CWCDefaultSessionGroup`, `$script:CWCProcessType`, - `$script:CWCAllSessionPermissions`, `$script:InternalUserSource` and the Remote Workforce and RESTful API Manager - extension IDs. + `$script:CWCSessionEventType` and `$script:CWCToolboxOperation` (live-verified numbers), + `$script:CWCDefaultSessionGroup`, `$script:CWCProcessType`, `$script:CWCAllSessionPermissions`, + `$script:InternalUserSource` and the Remote Workforce and RESTful API Manager extension IDs. - **Requests**: every public function calls `Private/Invoke-CWCServiceMethod.ps1`. It builds the endpoint (`-Service` → `Services/.ashx/`, `-RestApi` / `-ExtensionID` → `App_Extensions//Service.ashx/`) and sends the arguments as a **positional JSON array** matching the @@ -130,8 +130,8 @@ The `release` artifact is kept for 30 days; re-runs need it. commands/notes/deletes never repeat. Session events go through `Private/Add-CWCSessionEvent.ps1`. Transport errors carry an ErrorId (`CWC.NotConnected`, `CWC.AuthModeMismatch`, `CWC.Http`, `CWC.NoResponse`); an MFA login adds `CWC.MfaRequired`, `CWC.MfaCodeRejected`, `CWC.LoginFailed` and `CWC.LoginThrottled`. A failed sign-in - without MFA or with `-ApiSecret` has no `CWC.*` ErrorId. `-Sensitive` redacts the body from verbose and debug - output. + without MFA or with `-ApiSecret` has no `CWC.*` ErrorId. `-Sensitive` keeps the body (a secret, or bulk content + such as an uploaded file) out of verbose and debug output. - **Transport**: `Private/Invoke-CWCWebRequest.ps1` checks that a connection exists, **blocks calls that don't match the auth mode** (API-secret connections may only reach the RESTful API Manager), adds auth headers, handles PS 5 vs 6+ error shapes, and returns parsed JSON. @@ -140,7 +140,8 @@ The `release` artifact is kept for 30 days; re-runs need it. and `IdentityHash`. ApiSecret mode keeps the secret as a SecureString (`ApiSecret`) and sends `CTRLAuthHeader`. Connect-CWC validates the login with a test call. If that call fails, the previous connection is restored only when this was a `-Force` refresh of the same server, method and identity; a failed switch to anything else leaves - the module disconnected. + the module disconnected. While a login is being made or validated the connection carries `LoggingIn`, which + stops the transport from adding its "the login may be stale, reconnect" hints to permission errors. ## Adding New Functions diff --git a/CHANGELOG.md b/CHANGELOG.md index bd129eb..dbec81f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `Add-CWCToolboxItem` uploads a file to the shared Toolbox in chunks, or creates a Toolbox folder + (`ToolboxService.WriteToolboxFileContent`; needs the ManageSharedToolbox permission; credentials + connections only). Accepts files from the pipeline +- `Get-CWCToolbox` lists the Toolbox contents (`PageService.GetToolbox`) as one object per folder and file + with its path; `-Raw` returns the server's tree +- `Remove-CWCToolboxItem` deletes a Toolbox file or folder (`ToolboxService.ProcessToolboxOperation`, Delete); + asks for confirmation by default +- `Send-CWCToolboxItem -Elevated` runs the item with administrative privileges (QueuedElevatedTool 101) and + `-Silent` runs it elevated and silently (QueuedSilentElevatedTool 117); credentials connections only + +### Changed + +- A 401 "Needs permission" on a credentials connection now suggests `Connect-CWC -Force`: the server stops + honouring an older login's management permissions while ordinary calls keep working + ## [0.5.0] - 2026-11-10 Version numbers now have three parts (`0.5.0`). The previous release was 0.4.0.0, which had 21 commands; this diff --git a/ConnectWiseControlAPI_Functions.md b/ConnectWiseControlAPI_Functions.md index 1ca5ac1..7373b7c 100644 --- a/ConnectWiseControlAPI_Functions.md +++ b/ConnectWiseControlAPI_Functions.md @@ -17,6 +17,9 @@ Creates the security role required by the Remote Workforce extension. ### [Add-CWCSessionNote](Docs/Add-CWCSessionNote.md) Adds a note to a session. +### [Add-CWCToolboxItem](Docs/Add-CWCToolboxItem.md) +Uploads a file to the shared ScreenConnect Toolbox, or creates a Toolbox folder. + ### [Connect-CWC](Docs/Connect-CWC.md) Connects to a ConnectWise ScreenConnect server. @@ -57,6 +60,9 @@ Returns the details of a session: session info, events, connections and guest sc ### [Get-CWCSessionGroup](Docs/Get-CWCSessionGroup.md) Returns all session groups. +### [Get-CWCToolbox](Docs/Get-CWCToolbox.md) +Lists the contents of the ScreenConnect Toolbox. + ### [Initialize-CWCRemoteWorkforceSessionGroup](Docs/Initialize-CWCRemoteWorkforceSessionGroup.md) Creates or repairs the session group used by the Remote Workforce extension. @@ -90,6 +96,9 @@ Deletes sessions, optionally uninstalling the Access client first. ### [Remove-CWCSessionNote](Docs/Remove-CWCSessionNote.md) Removes notes from a session. +### [Remove-CWCToolboxItem](Docs/Remove-CWCToolboxItem.md) +Deletes a file or folder from the shared ScreenConnect Toolbox. + ### [Remove-CWCUser](Docs/Remove-CWCUser.md) Deletes an internal user. diff --git a/Docs/Add-CWCToolboxItem.md b/Docs/Add-CWCToolboxItem.md new file mode 100644 index 0000000..e6a17f6 --- /dev/null +++ b/Docs/Add-CWCToolboxItem.md @@ -0,0 +1,196 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Add-CWCToolboxItem + +## SYNOPSIS +Uploads a file to the shared ScreenConnect Toolbox, or creates a Toolbox folder. + +## SYNTAX + +### File (Default) +``` +Add-CWCToolboxItem -Path [-Name ] [-ChunkSize ] + [-WhatIf] [-Confirm] [] +``` + +### Directory +``` +Add-CWCToolboxItem -Name [-Directory] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Calls ToolboxService.WriteToolboxFileContent. +The file is sent in chunks: the first chunk creates +the item, replacing an item of the same name, and the rest are appended. +The user needs the +ManageSharedToolbox permission. + +When -Name contains a folder, that folder is created first. +If a chunk fails, a partial file is +left in the Toolbox; run the command again to replace it. + +Several files can be piped in; each keeps its own file name. + +Run the uploaded item on a session with Send-CWCToolboxItem. + +## EXAMPLES + +### EXAMPLE 1 +``` +Add-CWCToolboxItem -Path .\Cleanup.cmd +``` + +Uploads Cleanup.cmd to the top level of the Toolbox. + +### EXAMPLE 2 +``` +Add-CWCToolboxItem -Path .\Cleanup.cmd -Name 'Scripts/Cleanup.cmd' +``` + +Creates the Scripts folder if needed and uploads the file into it. + +### EXAMPLE 3 +``` +Get-ChildItem .\Tools\*.exe | Add-CWCToolboxItem +``` + +### EXAMPLE 4 +``` +Add-CWCToolboxItem -Directory -Name 'Scripts' +``` + +## PARAMETERS + +### -Path +Local file to upload. +Accepts paths and Get-Item / Get-ChildItem output from the pipeline. + +```yaml +Type: String +Parameter Sets: File +Aliases: FullName + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Name +Path of the item inside the Toolbox, e.g. +'Cleanup.cmd' or 'Scripts/Cleanup.cmd'. +Defaults to the +file name of -Path. +It names one item, so it cannot be used when several files are piped in. + +```yaml +Type: String +Parameter Sets: File +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +```yaml +Type: String +Parameter Sets: Directory +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Directory +Create the Toolbox folder -Name instead of uploading a file. + +```yaml +Type: SwitchParameter +Parameter Sets: Directory +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ChunkSize +Bytes of the file sent per request. +Defaults to 524288 (512 KB). +Lower it if the server rejects +the request as too large. + +```yaml +Type: Int32 +Parameter Sets: File +Aliases: + +Required: False +Position: Named +Default value: 524288 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot write to the Toolbox). +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Get-CWCToolbox.md b/Docs/Get-CWCToolbox.md new file mode 100644 index 0000000..981dd58 --- /dev/null +++ b/Docs/Get-CWCToolbox.md @@ -0,0 +1,77 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Get-CWCToolbox + +## SYNOPSIS +Lists the contents of the ScreenConnect Toolbox. + +## SYNTAX + +``` +Get-CWCToolbox [-Raw] [] +``` + +## DESCRIPTION +Calls PageService.GetToolbox, the same call the host client makes to list Toolbox items. +Any +signed-in user can call it. + +The server returns a tree: a root folder whose Items hold folders and files, each with a Name, +Attributes (1 for a folder, 0 for a file), a base64 icon (Image) and its own Items. +By default the tree is +flattened to one object per folder and file, with its Path inside the Toolbox and without the icon. + +Use it to find an item for Send-CWCToolboxItem, or to check an upload made with Add-CWCToolboxItem. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-CWCToolbox +``` + +Lists every folder and file in the Toolbox. + +### EXAMPLE 2 +``` +Get-CWCToolbox | Where-Object { -not $_.IsFolder -and $_.Path -like 'Scripts/*' } +``` + +## PARAMETERS + +### -Raw +Return the tree as the server sends it, including the icons. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot list the Toolbox). +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Remove-CWCToolboxItem.md b/Docs/Remove-CWCToolboxItem.md new file mode 100644 index 0000000..b101fa6 --- /dev/null +++ b/Docs/Remove-CWCToolboxItem.md @@ -0,0 +1,107 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Remove-CWCToolboxItem + +## SYNOPSIS +Deletes a file or folder from the shared ScreenConnect Toolbox. + +## SYNTAX + +``` +Remove-CWCToolboxItem [-Path] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Calls ToolboxService.ProcessToolboxOperation with the Delete operation. +The user needs the +ManageSharedToolbox permission. + +Only items stored in the server's Toolbox folder can be deleted. +Items that an extension adds +(for example Command Toolbox commands) are refused by the server with "Cannot edit virtual toolbox +item". + +## EXAMPLES + +### EXAMPLE 1 +``` +Remove-CWCToolboxItem -Path 'Scripts/Cleanup.cmd' +``` + +### EXAMPLE 2 +``` +Get-CWCToolbox | Where-Object Path -like 'API Test/*.cmd' | Remove-CWCToolboxItem -Confirm:$false +``` + +## PARAMETERS + +### -Path +Path of the item inside the Toolbox, e.g. +'Cleanup.cmd' or 'Scripts/Cleanup.cmd': the Path that +Get-CWCToolbox returns. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -WhatIf +Shows what would happen if the cmdlet runs. +The cmdlet is not run. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: wi + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Confirm +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: cf + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + + +### CommonParameters +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +## NOTES +Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot change the Toolbox). +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 index 8c34da7..dfea8c3 100644 --- a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 @@ -196,6 +196,8 @@ Describe 'Function Structure' { 'Add-CWCSessionNote' 'Send-CWCSessionMessage' 'Send-CWCToolboxItem' + 'Add-CWCToolboxItem' + 'Remove-CWCToolboxItem' 'New-CWCMFA' ) { $cmd = Get-Command $_ -Module 'ConnectWiseControlAPI' diff --git a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 index 4e6d290..511c089 100644 --- a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 @@ -398,9 +398,9 @@ Describe 'Invoke-CWCWebRequest' { InModuleScope 'ConnectWiseControlAPI' { # HTTP 500 with a server error body; the failed request (with a login cookie) as TargetObject $script:NewServerErrorRecord = { - param([string]$Body, $Request) + param([string]$Body, $Request, [int]$StatusCode = 500) $exception = [System.Net.WebException]::new('Server Error') - $exception | Add-Member -NotePropertyName Response -NotePropertyValue ([PSCustomObject]@{ StatusCode = 500 }) -Force + $exception | Add-Member -NotePropertyName Response -NotePropertyValue ([PSCustomObject]@{ StatusCode = $StatusCode }) -Force $record = [System.Management.Automation.ErrorRecord]::new($exception, 'WebError', 'InvalidResult', $Request) $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new($Body) $record @@ -455,6 +455,24 @@ Describe 'Invoke-CWCWebRequest' { } } + It 'suggests Connect-CWC -Force on a credentials connection refused with 401 ' -ForEach @( + @{ Case = 'Needs permission'; Status = 401; LoggingIn = $false; Expected = $true } + @{ Case = 'while connecting'; Status = 401; LoggingIn = $true; Expected = $false } + @{ Case = 'but not on a 500'; Status = 500; LoggingIn = $false; Expected = $false } + ) { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Status = $Status; LoggingIn = $LoggingIn; Expected = $Expected } { + param($Status, $LoggingIn, $Expected) + $script:CWCServerConnection.AuthType = 'Credentials' + if ($LoggingIn) { $script:CWCServerConnection.LoggingIn = $True } + $script:HintStatus = $Status + Mock Invoke-WebRequest { + throw (& $script:NewServerErrorRecord '{"errorType":"SecurityException","message":"Needs permission"}' $null $script:HintStatus) + } + $null = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/ToolboxService.ashx/WriteToolboxFileContent'; Method = 'Post' } -ErrorAction SilentlyContinue -ErrorVariable err + ("$err" -match 'Connect-CWC with -Force') | Should -Be $Expected + } + } + It 'does not suggest an expired login while logging in' { InModuleScope 'ConnectWiseControlAPI' { $script:CWCServerConnection.LoggingIn = $True diff --git a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 index 39be70c..22cf1b6 100644 --- a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 @@ -103,6 +103,17 @@ Describe 'Connect-CWC' { Should -Invoke Invoke-CWCWebRequest -Times 1 } } + + It 'marks the connection as logging in only during the validation call' { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ cred = $cred } { + param($cred) + $script:FlagDuringValidation = $null + Mock Invoke-CWCWebRequest { $script:FlagDuringValidation = $script:CWCServerConnection.LoggingIn } + Connect-CWC -Server 'server.example.com' -Credentials $cred + $script:FlagDuringValidation | Should -BeTrue + $script:CWCServerConnection.ContainsKey('LoggingIn') | Should -BeFalse + } + } } Context 'Server URL cleanup' { @@ -2284,6 +2295,17 @@ Describe 'Session event functions (API secret)' { } } + It 'Send-CWCToolboxItem -<_> returns CWC.AuthModeMismatch without calling the API' -ForEach @('Elevated', 'Silent') { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Switch = $_ } { + param($Switch) + $mode = @{ $Switch = $true } + Mock Invoke-CWCWebRequest {} + Send-CWCToolboxItem -GUID ([guid]::NewGuid()) -Name 'Tool.cmd' @mode -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $err[0].FullyQualifiedErrorId | Should -BeLike 'CWC.AuthModeMismatch*' + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + } Describe 'Session event functions (credentials)' { @@ -2294,6 +2316,9 @@ Describe 'Session event functions (credentials)' { @{ Command = 'Add-CWCSessionNote'; Params = @{ Note = 'hello' }; EventType = 32; Data = 'hello' } @{ Command = 'Send-CWCSessionMessage'; Params = @{ Message = 'hi' }; EventType = 45; Data = 'hi' } @{ Command = 'Send-CWCToolboxItem'; Params = @{ Name = 'Tool.ps1' }; EventType = 47; Data = 'Tool.ps1' } + @{ Command = 'Send-CWCToolboxItem'; Params = @{ Name = 'Tool.cmd'; Elevated = $true }; EventType = 101; Data = 'Tool.cmd' } + @{ Command = 'Send-CWCToolboxItem'; Params = @{ Name = 'Tool.cmd'; Silent = $true }; EventType = 117; Data = 'Tool.cmd' } + @{ Command = 'Send-CWCToolboxItem'; Params = @{ Name = 'Tool.cmd'; Silent = $true; Elevated = $true }; EventType = 117; Data = 'Tool.cmd' } ) { InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Command = $Command; Params = $Params; EventType = $EventType; Data = $Data } { param($Command, $Params, $EventType, $Data) @@ -2481,6 +2506,372 @@ Describe 'Remove-CWCSessionNote' { } } +# ============================================================================= +# Toolbox +# Signatures from Services/ToolboxService.ashx and PageService.ashx (GetToolbox) +# ============================================================================= +Describe 'Get-CWCToolbox' { + + BeforeEach { Set-CWCTestConnection } + + It 'calls PageService.GetToolbox without a body, with retry' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments, $MaxRetry) + $Arguments.Endpoint | Should -Be 'Services/PageService.ashx/GetToolbox' + $Arguments.ContainsKey('Body') | Should -BeFalse + $MaxRetry | Should -Be 3 + @() + } + Get-CWCToolbox + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + Context 'Toolbox tree' { + BeforeEach { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + '{"Name":"Toolbox","Attributes":1,"Image":"aWNvbg==","Items":[ + {"Name":"Scripts","Attributes":1,"Image":"aWNvbg==","Items":[ + {"Name":"Cleanup.ps1","Attributes":0,"Image":"aWNvbg==","Items":[]}, + {"Name":"Empty","Attributes":1,"Image":"aWNvbg==","Items":[]} + ]}, + {"Name":"Top.cmd","Attributes":0,"Image":"aWNvbg==","Items":[]} + ]}' | ConvertFrom-Json + } + } + } + + It 'flattens the tree to one object per item, with paths and without icons' { + InModuleScope 'ConnectWiseControlAPI' { + $items = @(Get-CWCToolbox) + $items.Path | Should -Be @('Scripts', 'Scripts/Cleanup.ps1', 'Scripts/Empty', 'Top.cmd') + $items.IsFolder | Should -Be @($true, $false, $true, $false) + $items[1].Name | Should -Be 'Cleanup.ps1' + $items[0].PSObject.Properties.Name | Should -Not -Contain 'Image' + } + } + + It 'treats an item with children as a folder even without Attributes' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + '{"Name":"Toolbox","Items":[{"Name":"Scripts","Items":[{"Name":"a.cmd","Attributes":"File"}]}]}' | + ConvertFrom-Json + } + $items = @(Get-CWCToolbox) + $items.Path | Should -Be @('Scripts', 'Scripts/a.cmd') + $items.IsFolder | Should -Be @($true, $false) + } + } + + It 'writes one error and no output when the request fails' -ForEach @( + @{ Case = ''; Raw = $false } + @{ Case = ' (-Raw)'; Raw = $true } + ) { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Raw = $Raw } { + param($Raw) + Mock Invoke-CWCWebRequest { Write-Error 'HTTP 401' -ErrorId 'CWC.Http401' } + $result = @(Get-CWCToolbox -Raw:$Raw -ErrorVariable err -ErrorAction SilentlyContinue) + $result.Count | Should -Be 0 + $err.Count | Should -Be 1 + $err[0].FullyQualifiedErrorId | Should -BeLike 'CWC.Http401*' + } + } + + It 'returns nothing for an empty response' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + @(Get-CWCToolbox).Count | Should -Be 0 + } + } + + It '-Raw returns the server tree' { + InModuleScope 'ConnectWiseControlAPI' { + $tree = Get-CWCToolbox -Raw + $tree.Name | Should -Be 'Toolbox' + $tree.Items[0].Items[0].Name | Should -Be 'Cleanup.ps1' + $tree.Image | Should -Be 'aWNvbg==' + } + } + } +} + +Describe 'Add-CWCToolboxItem' { + + BeforeAll { + function New-CWCTestFile([string]$Name, [byte[]]$Bytes = @()) { + [System.IO.File]::WriteAllBytes((Join-Path $TestDrive $Name), $Bytes) + } + } + + BeforeEach { + Set-CWCTestConnection + InModuleScope 'ConnectWiseControlAPI' { + $script:ToolboxCalls = New-Object System.Collections.ArrayList + Mock Invoke-CWCWebRequest { + param($Arguments, $MaxRetry, [switch]$SensitiveBody) + $null = $script:ToolboxCalls.Add([PSCustomObject]@{ + Endpoint = $Arguments.Endpoint + Body = $Arguments.Body | ConvertFrom-Json + MaxRetry = $MaxRetry + Sensitive = [bool]$SensitiveBody + }) + } + } + } + + It 'uploads a small file in one call that replaces the item, without retry' { + New-CWCTestFile 'Tool.ps1' 1, 2, 3 + InModuleScope 'ConnectWiseControlAPI' { + Add-CWCToolboxItem -Path 'TestDrive:\Tool.ps1' -Confirm:$false + $script:ToolboxCalls.Count | Should -Be 1 + $call = $script:ToolboxCalls[0] + $call.Endpoint | Should -Be 'Services/ToolboxService.ashx/WriteToolboxFileContent' + $call.MaxRetry | Should -Be 0 + $call.Sensitive | Should -BeTrue + $call.Body[0] | Should -Be 'Tool.ps1' + $call.Body[1] | Should -BeFalse + $call.Body[2] | Should -BeFalse + $call.Body[3] | Should -Be ([Convert]::ToBase64String([byte[]](1, 2, 3))) + } + } + + It 'sends later chunks as appends and keeps the bytes in order' { + New-CWCTestFile 'Big.bin' 10, 20, 30, 40, 50 + InModuleScope 'ConnectWiseControlAPI' { + Add-CWCToolboxItem -Path 'TestDrive:\Big.bin' -ChunkSize 2 -Confirm:$false + $script:ToolboxCalls.Count | Should -Be 3 + @($script:ToolboxCalls | ForEach-Object { $_.Body[2] }) | Should -Be @($false, $true, $true) + $bytes = @($script:ToolboxCalls | ForEach-Object { [Convert]::FromBase64String($_.Body[3]) }) + $bytes | Should -Be @(10, 20, 30, 40, 50) + } + } + + It 'creates the item for an empty file' { + New-CWCTestFile 'Empty.txt' + InModuleScope 'ConnectWiseControlAPI' { + Add-CWCToolboxItem -Path 'TestDrive:\Empty.txt' -Confirm:$false + $script:ToolboxCalls.Count | Should -Be 1 + $script:ToolboxCalls[0].Body[2] | Should -BeFalse + $script:ToolboxCalls[0].Body[3] | Should -Be '' + } + } + + It 'creates the folder in -Name before uploading into it' { + New-CWCTestFile 'Tool.ps1' 1 + InModuleScope 'ConnectWiseControlAPI' { + Add-CWCToolboxItem -Path 'TestDrive:\Tool.ps1' -Name 'Scripts/Sub/Cleanup.ps1' -Confirm:$false + $script:ToolboxCalls.Count | Should -Be 2 + $script:ToolboxCalls[0].Body[0] | Should -Be 'Scripts/Sub' + $script:ToolboxCalls[0].Body[1] | Should -BeTrue + $script:ToolboxCalls[1].Body[0] | Should -Be 'Scripts/Sub/Cleanup.ps1' + $script:ToolboxCalls[1].Body[1] | Should -BeFalse + } + } + + It '-Directory creates a folder' { + InModuleScope 'ConnectWiseControlAPI' { + Add-CWCToolboxItem -Directory -Name 'Scripts' -Confirm:$false + $script:ToolboxCalls.Count | Should -Be 1 + $script:ToolboxCalls[0].Body[0] | Should -Be 'Scripts' + $script:ToolboxCalls[0].Body[1] | Should -BeTrue + $script:ToolboxCalls[0].Body[3] | Should -Be '' + } + } + + It 'accepts files from the pipeline' { + New-CWCTestFile 'Piped.cmd' 1 + InModuleScope 'ConnectWiseControlAPI' { + Get-Item 'TestDrive:\Piped.cmd' | Add-CWCToolboxItem -Confirm:$false + $script:ToolboxCalls[0].Body[0] | Should -Be 'Piped.cmd' + } + } + + It 'does not call the API with -WhatIf' { + New-CWCTestFile 'Tool.ps1' 1 + InModuleScope 'ConnectWiseControlAPI' { + Add-CWCToolboxItem -Path 'TestDrive:\Tool.ps1' -WhatIf + Add-CWCToolboxItem -Directory -Name 'Scripts' -WhatIf + $script:ToolboxCalls.Count | Should -Be 0 + } + } + + It 'returns an error for a missing file without calling the API' { + InModuleScope 'ConnectWiseControlAPI' { + Add-CWCToolboxItem -Path 'TestDrive:\nope.ps1' -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $err[0].FullyQualifiedErrorId | Should -BeLike 'CWC.FileNotFound*' + $script:ToolboxCalls.Count | Should -Be 0 + } + } + + It 'warns about a partial file when a later chunk fails' { + New-CWCTestFile 'Big.bin' 1, 2, 3, 4 + InModuleScope 'ConnectWiseControlAPI' { + $script:ToolboxCallCount = 0 + Mock Invoke-CWCWebRequest { + $script:ToolboxCallCount++ + if ($script:ToolboxCallCount -gt 1) { Write-Error 'HTTP 500' -ErrorId 'CWC.Http500' } + } + Mock Write-Warning {} + Add-CWCToolboxItem -Path 'TestDrive:\Big.bin' -ChunkSize 2 -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $script:ToolboxCallCount | Should -Be 2 + $err[-1].FullyQualifiedErrorId | Should -BeLike 'CWC.Http500*' + Should -Invoke Write-Warning -Times 1 -ParameterFilter { $Message -like '*partial file*' } + } + } + + It 'sends no chunk and gives no partial-file warning when the folder cannot be created' { + New-CWCTestFile 'Tool.cmd' 1 + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { Write-Error 'HTTP 401' -ErrorId 'CWC.Http401' } + Mock Write-Warning {} + Add-CWCToolboxItem -Path 'TestDrive:\Tool.cmd' -Name 'Scripts/Tool.cmd' -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + Should -Invoke Invoke-CWCWebRequest -Times 1 + Should -Invoke Write-Warning -Times 0 + $err[-1].FullyQualifiedErrorId | Should -BeLike 'CWC.Http401*' + } + } + + It 'sends a backslash -Name with forward slashes' { + New-CWCTestFile 'Tool.cmd' 1 + InModuleScope 'ConnectWiseControlAPI' { + Add-CWCToolboxItem -Path 'TestDrive:\Tool.cmd' -Name '\Scripts\Tool.cmd' -Confirm:$false + @($script:ToolboxCalls | ForEach-Object { $_.Body[0] }) | Should -Be @('Scripts', 'Scripts/Tool.cmd') + } + } + + It 'refuses the -Name <_> without calling the API' -ForEach @( + '..\x.cmd', 'Scripts/', 'a//b.cmd', './x.cmd', '/', '.. /x.cmd', 'C:\x.cmd', 'x.cmd.', 'a*b.cmd' + ) { + New-CWCTestFile 'Tool.cmd' 1 + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ BadName = $_ } { + param($BadName) + Add-CWCToolboxItem -Path 'TestDrive:\Tool.cmd' -Name $BadName -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $err[0].FullyQualifiedErrorId | Should -BeLike 'CWC.InvalidToolboxPath*' + $script:ToolboxCalls.Count | Should -Be 0 + } + } + + It 'accepts a path string from the pipeline' { + New-CWCTestFile 'Piped.cmd' 1 + InModuleScope 'ConnectWiseControlAPI' { + 'TestDrive:\Piped.cmd' | Add-CWCToolboxItem -Confirm:$false + $script:ToolboxCalls[0].Body[0] | Should -Be 'Piped.cmd' + } + } + + It 'uploads only the first of several piped files when -Name is given' { + New-CWCTestFile 'One.cmd' 1 + New-CWCTestFile 'Two.cmd' 2 + InModuleScope 'ConnectWiseControlAPI' { + 'TestDrive:\One.cmd', 'TestDrive:\Two.cmd' | + Add-CWCToolboxItem -Name 'Tool.cmd' -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $script:ToolboxCalls.Count | Should -Be 1 + $err[0].FullyQualifiedErrorId | Should -BeLike 'CWC.NameWithSeveralFiles*' + } + } + + It 'returns CWC.AuthModeMismatch on an API secret connection' { + Set-CWCTestApiSecretConnection + InModuleScope 'ConnectWiseControlAPI' { + Add-CWCToolboxItem -Directory -Name 'Scripts' -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $err[0].FullyQualifiedErrorId | Should -BeLike 'CWC.AuthModeMismatch*' + $script:ToolboxCalls.Count | Should -Be 0 + } + } +} + +Describe 'Remove-CWCToolboxItem' { + + BeforeEach { Set-CWCTestConnection } + + It 'sends the Delete operation (3) with the path and a null originalPath, without retry' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments, $MaxRetry) + $Arguments.Endpoint | Should -Be 'Services/ToolboxService.ashx/ProcessToolboxOperation' + $MaxRetry | Should -Be 0 + ($Arguments.Body -replace '\s', '') | Should -Be '[3,"Scripts/Cleanup.cmd",null]' + } + Remove-CWCToolboxItem -Path 'Scripts/Cleanup.cmd' -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'takes the Path of Get-CWCToolbox items from the pipeline, not their Name' { + InModuleScope 'ConnectWiseControlAPI' { + $script:RemovedPaths = @() + Mock Invoke-CWCWebRequest { + param($Arguments) + $script:RemovedPaths += ($Arguments.Body | ConvertFrom-Json)[1] + } + @( + [PSCustomObject]@{ Path = 'A/one.cmd'; Name = 'one.cmd'; IsFolder = $false; Attributes = 0 } + [PSCustomObject]@{ Path = 'two.cmd'; Name = 'two.cmd'; IsFolder = $false; Attributes = 0 } + ) | Remove-CWCToolboxItem -Confirm:$false + $script:RemovedPaths | Should -Be @('A/one.cmd', 'two.cmd') + } + } + + It 'refuses the path <_> without calling the API' -ForEach @( + '/', '.', '..', ' ', 'Scripts/../..', '\', '...', '. ', ' .', '.. ', 'Scripts/.. ', 'Scripts/...', 'C:', + 'C:\Program Files (x86)\ScreenConnect\App_Data\Toolbox', 'x:y', 'Scripts/*' + ) { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ BadPath = $_ } { + param($BadPath) + Mock Invoke-CWCWebRequest {} + Remove-CWCToolboxItem -Path $BadPath -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $err[0].FullyQualifiedErrorId | Should -BeLike 'CWC.InvalidToolboxPath*' + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + + It 'sends the ordinary path <_> unchanged' -ForEach @( + 'v1.2/setup.exe', 'Account Lockout Tools/ALTools.exe', '.gitignore', 'a..b', '0' + ) { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ GoodPath = $_ } { + param($GoodPath) + $script:SentPath = $null + Mock Invoke-CWCWebRequest { + param($Arguments) + $script:SentPath = ($Arguments.Body | ConvertFrom-Json)[1] + } + Remove-CWCToolboxItem -Path $GoodPath -Confirm:$false + $script:SentPath | Should -Be $GoodPath + } + } + + It 'sends a backslash path with forward slashes' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + ($Arguments.Body | ConvertFrom-Json)[1] | Should -Be 'Scripts/Old' + } + Remove-CWCToolboxItem -Path 'Scripts\Old\' -Confirm:$false + Should -Invoke Invoke-CWCWebRequest -Times 1 + } + } + + It 'does not call the API with -WhatIf' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Remove-CWCToolboxItem -Path 'Cleanup.cmd' -WhatIf + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } + + It 'returns CWC.AuthModeMismatch on an API secret connection' { + Set-CWCTestApiSecretConnection + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Remove-CWCToolboxItem -Path 'Cleanup.cmd' -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $err[0].FullyQualifiedErrorId | Should -BeLike 'CWC.AuthModeMismatch*' + Should -Invoke Invoke-CWCWebRequest -Times 0 + } + } +} + Describe 'Enter-CWCSession pipeline binding' { It 'takes the numeric SessionType of piped sessions (Support = 0) and uses its default group' { InModuleScope 'ConnectWiseControlAPI' { diff --git a/source/Private/Invoke-CWCServiceMethod.ps1 b/source/Private/Invoke-CWCServiceMethod.ps1 index c53b647..28f2dbc 100644 --- a/source/Private/Invoke-CWCServiceMethod.ps1 +++ b/source/Private/Invoke-CWCServiceMethod.ps1 @@ -20,12 +20,14 @@ function Invoke-CWCServiceMethod { wake or delete). .PARAMETER Sensitive - The arguments contain a secret (password). The body is left out of verbose and debug output. + The body must not be logged or kept: it holds a secret (password) or bulk content (an uploaded + file). It is left out of verbose and debug output. #> [CmdletBinding(DefaultParameterSetName = 'Service')] param( [Parameter(Mandatory = $True, ParameterSetName = 'Service')] - [ValidateSet('PageService', 'SecurityService', 'AuditService', 'SessionGroupService', 'AuthenticationService')] + [ValidateSet('PageService', 'SecurityService', 'AuditService', 'SessionGroupService', 'AuthenticationService', + 'ToolboxService')] [string]$Service, [Parameter(Mandatory = $True, ParameterSetName = 'RestApi')] diff --git a/source/Private/Invoke-CWCWebRequest.ps1 b/source/Private/Invoke-CWCWebRequest.ps1 index 17d6e32..d49c3c1 100644 --- a/source/Private/Invoke-CWCWebRequest.ps1 +++ b/source/Private/Invoke-CWCWebRequest.ps1 @@ -127,6 +127,14 @@ ("$ServerErrorType" -match 'Security' -or "$ServerMessage" -match 'anti-?forgery|Needs permission')) { $ErrorMessage += 'If the MFA login has expired, run Connect-CWC again.' } + # A credentials login keeps working for ordinary calls after the server stops honouring its + # management permissions: ToolboxService and SessionGroupService answered 401 "Needs permission" + # until Connect-CWC -Force signed in again (seen live, 2026-11-11). + elseif ($StatusCode -eq 401 -and $script:CWCServerConnection.AuthType -notin 'Mfa', 'ApiSecret' -and + -not $script:CWCServerConnection.LoggingIn -and "$ServerMessage" -match 'Needs permission') { + $ErrorMessage += 'If the account has this permission, the login may be too old for it:' + $ErrorMessage += 'run Connect-CWC with -Force to sign in again.' + } if ($StatusCode -gt 0) { $ErrorId = "CWC.Http$StatusCode"; $Category = 'InvalidResult' } else { $ErrorId = 'CWC.NoResponse'; $Category = 'ConnectionError' } diff --git a/source/Private/Resolve-CWCToolboxPath.ps1 b/source/Private/Resolve-CWCToolboxPath.ps1 new file mode 100644 index 0000000..dcfe651 --- /dev/null +++ b/source/Private/Resolve-CWCToolboxPath.ps1 @@ -0,0 +1,41 @@ +function Resolve-CWCToolboxPath { + <# + .SYNOPSIS + Normalizes a path inside the Toolbox, or writes a CWC.InvalidToolboxPath error and returns nothing. + + .DESCRIPTION + Backslashes become forward slashes (the separator Get-CWCToolbox returns) and leading slashes are + removed. A path is refused here rather than sent when it could name something other than an item + inside the Toolbox, such as the Toolbox root, its parent or another drive: an empty path, or a + part that is empty, ends in a dot or whitespace (Windows drops those, so '.', '..', '...' and + '. ' all resolve to a folder above the item), or holds a character Windows does not allow in a + file name (which covers 'C:'). A file path ending in a slash is refused too. + + .PARAMETER Path + Path of the item inside the Toolbox. + + .PARAMETER Folder + The path names a folder, or may name one: a trailing slash is allowed and removed. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory = $True)] + [AllowEmptyString()] + [string]$Path, + + [switch]$Folder + ) + + $Clean = ($Path -replace '\\', '/').TrimStart('/') + if ($Folder) { $Clean = $Clean.TrimEnd('/') } + + $BadParts = @($Clean -split '/' | Where-Object { + [string]::IsNullOrWhiteSpace($_) -or $_ -match '[.\s]$' -or $_ -match '[:*?"<>|\x00-\x1f]' + }) + if ($BadParts.Count -gt 0) { + $Message = "'$Path' is not a valid Toolbox path." + return Write-Error $Message -ErrorId 'CWC.InvalidToolboxPath' -Category InvalidArgument + } + $Clean +} diff --git a/source/Public/Authentication/Connect-CWC.ps1 b/source/Public/Authentication/Connect-CWC.ps1 index b85afd4..4ad9cff 100644 --- a/source/Public/Authentication/Connect-CWC.ps1 +++ b/source/Public/Authentication/Connect-CWC.ps1 @@ -299,6 +299,8 @@ function Connect-CWC { AuthType = 'Credentials' Headers = $Headers WebSession = $WebSession + # Until the validation call passes: keeps Invoke-CWCWebRequest from suggesting a stale login + LoggingIn = $True } Write-Verbose "Connected to ScreenConnect server: https://$Server" @@ -324,6 +326,10 @@ function Connect-CWC { Write-Error "Connecting to 'https://$Server' failed before authentication could be checked: $_" } } + finally { + # Also when interrupted (Ctrl+C); after a failure this is the restored connection, or none + if ($script:CWCServerConnection) { $script:CWCServerConnection.Remove('LoggingIn') } + } } } } diff --git a/source/Public/PageService/Get-CWCToolbox.ps1 b/source/Public/PageService/Get-CWCToolbox.ps1 new file mode 100644 index 0000000..6598260 --- /dev/null +++ b/source/Public/PageService/Get-CWCToolbox.ps1 @@ -0,0 +1,62 @@ +function Get-CWCToolbox { + <# + .SYNOPSIS + Lists the contents of the ScreenConnect Toolbox. + + .DESCRIPTION + Calls PageService.GetToolbox, the same call the host client makes to list Toolbox items. Any + signed-in user can call it. + + The server returns a tree: a root folder whose Items hold folders and files, each with a Name, + Attributes (1 for a folder, 0 for a file), a base64 icon (Image) and its own Items. By default the tree is + flattened to one object per folder and file, with its Path inside the Toolbox and without the icon. + + Use it to find an item for Send-CWCToolboxItem, or to check an upload made with Add-CWCToolboxItem. + + .PARAMETER Raw + Return the tree as the server sends it, including the icons. + + .EXAMPLE + Get-CWCToolbox + + Lists every folder and file in the Toolbox. + + .EXAMPLE + Get-CWCToolbox | Where-Object { -not $_.IsFolder -and $_.Path -like 'Scripts/*' } + + .NOTES + Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot list the Toolbox). + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding()] + param ( + [switch]$Raw + ) + + # On an error there is no response, and the walk below returns nothing + $Toolbox = Invoke-CWCServiceMethod -Service PageService -Method GetToolbox -Idempotent + if ($Raw) { return $Toolbox } + + # Depth-first, in the server's order. The root folder itself is not part of an item's path. + $Walk = { + param($Items, $Parent) + foreach ($Item in $Items) { + if (-not $Item) { continue } + $ItemPath = "$Parent$($Item.Name)" + # Attributes is 1 for a folder and 0 for a file (seen live, 2026-11-11). Files also carry an + # Items list, but an empty one; anything with items in it is a folder whatever its Attributes. + $IsFolder = [bool](($Item.Attributes -as [int]) -band 1) -or [bool]$Item.Items + [PSCustomObject]@{ + Path = $ItemPath + Name = $Item.Name + IsFolder = $IsFolder + Attributes = $Item.Attributes + } + if ($IsFolder) { & $Walk $Item.Items "$ItemPath/" } + } + } + & $Walk $Toolbox.Items '' +} diff --git a/source/Public/RestApi/Send-CWCToolboxItem.ps1 b/source/Public/RestApi/Send-CWCToolboxItem.ps1 index 822a88e..e8c4659 100644 --- a/source/Public/RestApi/Send-CWCToolboxItem.ps1 +++ b/source/Public/RestApi/Send-CWCToolboxItem.ps1 @@ -4,26 +4,45 @@ function Send-CWCToolboxItem { Queues a Toolbox item to run on a session. .DESCRIPTION - Queues a QueuedTool session event naming the Toolbox item. + Queues a QueuedTool session event naming the Toolbox item. -Elevated queues a QueuedElevatedTool + event instead, which runs the item with administrative privileges; -Silent queues a + QueuedSilentElevatedTool event, which runs it elevated and silently. + + The machine opens the item the way Windows opens a file, so use a file type that runs when opened + (.exe, .msi, .cmd, .bat): a .ps1 opens in its default program instead of running. Credentials connections: PageService.AddSessionEvents; the user needs the RunSharedTool permission in -Group. API secret connections: the RESTful API Manager extension's SendToolboxItemToSession. The event is attributed to the extension's RESTfulUserName setting ("RESTful API" unless renamed); -Group - is ignored. + is ignored. -Elevated and -Silent are not available: the extension only queues the standard event. .PARAMETER GUID Session ID. .PARAMETER Name - Toolbox item name as shown in the ScreenConnect Toolbox. + Toolbox item name as shown in the ScreenConnect Toolbox. For an item in a folder, the Path that + Get-CWCToolbox returns. + + .PARAMETER Elevated + Run the item with administrative privileges (QueuedElevatedTool). Credentials connections only. + + .PARAMETER Silent + Run the item elevated and silently (QueuedSilentElevatedTool): it runs as NT AUTHORITY\SYSTEM + (seen live, 2026-11-11). Implies -Elevated. Credentials connections only. .PARAMETER Group Session group containing the session (credentials connections only). Defaults to 'All Machines'. .EXAMPLE - Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.ps1' + Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.cmd' + + .EXAMPLE + Send-CWCToolboxItem -GUID $SessionID -Name 'Installers/Setup.exe' -Elevated + + .EXAMPLE + Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.cmd' -Silent .NOTES Author: Chris Taylor @@ -42,11 +61,33 @@ function Send-CWCToolboxItem { [string]$Name, [ValidateNotNullOrEmpty()] - [string[]]$Group = 'All Machines' + [string[]]$Group = 'All Machines', + + [switch]$Elevated, + + [switch]$Silent ) process { - if (-not $PSCmdlet.ShouldProcess("$GUID", "Run toolbox item '$Name'")) { return } + if (($Elevated -or $Silent) -and (Test-CWCApiSecretConnection)) { + $Message = @( + "$($MyInvocation.MyCommand.Name) -Elevated and -Silent are not available when connected with" + '-ApiSecret (the RESTful API Manager only queues the standard event).' + "Connect with 'Connect-CWC -Credentials'." + ) -join ' ' + return Write-Error $Message -ErrorId 'CWC.AuthModeMismatch' -Category InvalidOperation + } + + $EventType = $script:CWCSessionEventType.QueuedTool + $Action = "Run toolbox item '$Name'" + if ($Silent) { + $EventType = $script:CWCSessionEventType.QueuedSilentElevatedTool + $Action = "Run toolbox item '$Name' elevated and silent" + } elseif ($Elevated) { + $EventType = $script:CWCSessionEventType.QueuedElevatedTool + $Action = "Run toolbox item '$Name' elevated" + } + if (-not $PSCmdlet.ShouldProcess("$GUID", $Action)) { return } # Adding an event is not idempotent: never retried if (Test-CWCApiSecretConnection) { @@ -54,7 +95,7 @@ function Send-CWCToolboxItem { $null = Invoke-CWCServiceMethod -RestApi -Method SendToolboxItemToSession -Arguments @($GUID.ToString(), $Name) } else { - Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $GUID; EventType = $script:CWCSessionEventType.QueuedTool; Data = $Name } + Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $GUID; EventType = $EventType; Data = $Name } } } } diff --git a/source/Public/ToolboxService/Add-CWCToolboxItem.ps1 b/source/Public/ToolboxService/Add-CWCToolboxItem.ps1 new file mode 100644 index 0000000..429c6bc --- /dev/null +++ b/source/Public/ToolboxService/Add-CWCToolboxItem.ps1 @@ -0,0 +1,148 @@ +function Add-CWCToolboxItem { + <# + .SYNOPSIS + Uploads a file to the shared ScreenConnect Toolbox, or creates a Toolbox folder. + + .DESCRIPTION + Calls ToolboxService.WriteToolboxFileContent. The file is sent in chunks: the first chunk creates + the item, replacing an item of the same name, and the rest are appended. The user needs the + ManageSharedToolbox permission. + + When -Name contains a folder, that folder is created first. If a chunk fails, a partial file is + left in the Toolbox; run the command again to replace it. + + Several files can be piped in; each keeps its own file name. + + Run the uploaded item on a session with Send-CWCToolboxItem. + + .PARAMETER Path + Local file to upload. Accepts paths and Get-Item / Get-ChildItem output from the pipeline. + + .PARAMETER Name + Path of the item inside the Toolbox, e.g. 'Cleanup.cmd' or 'Scripts/Cleanup.cmd'. Defaults to the + file name of -Path. It names one item, so it cannot be used when several files are piped in. + + .PARAMETER Directory + Create the Toolbox folder -Name instead of uploading a file. + + .PARAMETER ChunkSize + Bytes of the file sent per request. Defaults to 524288 (512 KB). Lower it if the server rejects + the request as too large. + + .EXAMPLE + Add-CWCToolboxItem -Path .\Cleanup.cmd + + Uploads Cleanup.cmd to the top level of the Toolbox. + + .EXAMPLE + Add-CWCToolboxItem -Path .\Cleanup.cmd -Name 'Scripts/Cleanup.cmd' + + Creates the Scripts folder if needed and uploads the file into it. + + .EXAMPLE + Get-ChildItem .\Tools\*.exe | Add-CWCToolboxItem + + .EXAMPLE + Add-CWCToolboxItem -Directory -Name 'Scripts' + + .NOTES + Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot write to the Toolbox). + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'File')] + param( + [Parameter(Mandatory = $True, ParameterSetName = 'File', ValueFromPipeline = $True, + ValueFromPipelineByPropertyName = $True)] + [Alias('FullName')] + [ValidateNotNullOrEmpty()] + [string]$Path, + + [Parameter(ParameterSetName = 'File')] + [Parameter(Mandatory = $True, ParameterSetName = 'Directory')] + [ValidateNotNullOrEmpty()] + [string]$Name, + + [Parameter(Mandatory = $True, ParameterSetName = 'Directory')] + [switch]$Directory, + + [Parameter(ParameterSetName = 'File')] + [ValidateRange(1, 2147483647)] + [int]$ChunkSize = 524288 + ) + + begin { + $FileCount = 0 + } + + process { + # Checked up front: the transport would only refuse after the confirmation prompt and the file check + if (Test-CWCApiSecretConnection) { + $Message = Get-CWCAuthModeMessage -Command $MyInvocation.MyCommand.Name -Required Credentials + return Write-Error $Message -ErrorId 'CWC.AuthModeMismatch' -Category InvalidOperation + } + + # WriteToolboxFileContent(string path, bool isDirectory, bool appendOrReplace, string base64Content) + # appendOrReplace: true appends to the file, false creates or replaces it. + # Never retried: repeating an append would duplicate the chunk. + $Write = @{ Service = 'ToolboxService'; Method = 'WriteToolboxFileContent' } + + if ($PSCmdlet.ParameterSetName -eq 'Directory') { + $Folder = Resolve-CWCToolboxPath -Path $Name -Folder + if ($Folder -and $PSCmdlet.ShouldProcess($Folder, 'Create Toolbox folder')) { + $null = Invoke-CWCServiceMethod @Write -Arguments @($Folder, $True, $False, '') + } + return + } + + $LocalPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) + if (-not (Test-Path -LiteralPath $LocalPath -PathType Leaf)) { + return Write-Error "File not found: $LocalPath" -ErrorId 'CWC.FileNotFound' -Category ObjectNotFound + } + + $FileCount++ + if ($Name -and $FileCount -gt 1) { + # Each file would replace the one before it + $Message = "-Name names one Toolbox item, so it cannot be used with several files. Not uploaded: $LocalPath" + return Write-Error $Message -ErrorId 'CWC.NameWithSeveralFiles' -Category InvalidArgument + } + + $ItemName = $Name + if (-not $ItemName) { $ItemName = Split-Path -Path $LocalPath -Leaf } + $ItemName = Resolve-CWCToolboxPath -Path $ItemName + if (-not $ItemName) { return } + + if (-not $PSCmdlet.ShouldProcess($ItemName, "Upload '$LocalPath' to the Toolbox")) { return } + + $Append = $False + try { + $Stream = [System.IO.File]::OpenRead($LocalPath) + try { + # The server writes the file with File.Open, which fails when the folder doesn't exist. + # Created once the local file is open, so a file that can't be read leaves no empty folder. + $SeparatorIndex = $ItemName.LastIndexOf('/') + if ($SeparatorIndex -gt 0) { + $Folder = $ItemName.Substring(0, $SeparatorIndex) + $null = Invoke-CWCServiceMethod @Write -Arguments @($Folder, $True, $False, '') -ErrorAction Stop + } + + $Buffer = New-Object byte[] $ChunkSize + # -not $Append: an empty file still needs one call to create the item + while (($BytesRead = $Stream.Read($Buffer, 0, $Buffer.Length)) -gt 0 -or -not $Append) { + $Chunk = @($ItemName, $False, $Append, [Convert]::ToBase64String($Buffer, 0, $BytesRead)) + # -Sensitive keeps the file content out of verbose and debug output + $null = Invoke-CWCServiceMethod @Write -Arguments $Chunk -Sensitive -ErrorAction Stop + $Append = $True + } + } finally { + $Stream.Dispose() + } + } catch { + if ($Append) { Write-Warning "Upload of '$ItemName' stopped part way; a partial file is in the Toolbox." } + # WriteError keeps the transport's ErrorId (CWC.Http401, ...); Write-Error $_ loses it on PS 5.1 + $PSCmdlet.WriteError($_) + } + } +} diff --git a/source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 b/source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 new file mode 100644 index 0000000..cd32efc --- /dev/null +++ b/source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 @@ -0,0 +1,57 @@ +function Remove-CWCToolboxItem { + <# + .SYNOPSIS + Deletes a file or folder from the shared ScreenConnect Toolbox. + + .DESCRIPTION + Calls ToolboxService.ProcessToolboxOperation with the Delete operation. The user needs the + ManageSharedToolbox permission. + + Only items stored in the server's Toolbox folder can be deleted. Items that an extension adds + (for example Command Toolbox commands) are refused by the server with "Cannot edit virtual toolbox + item". + + .PARAMETER Path + Path of the item inside the Toolbox, e.g. 'Cleanup.cmd' or 'Scripts/Cleanup.cmd': the Path that + Get-CWCToolbox returns. + + .EXAMPLE + Remove-CWCToolboxItem -Path 'Scripts/Cleanup.cmd' + + .EXAMPLE + Get-CWCToolbox | Where-Object Path -like 'API Test/*.cmd' | Remove-CWCToolboxItem -Confirm:$false + + .NOTES + Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot change the Toolbox). + Author: Chris Taylor + + .LINK + https://github.com/christaylorcodes/ConnectWiseControlAPI + #> + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] + param( + [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] + [ValidateNotNullOrEmpty()] + [string]$Path + ) + + process { + # Checked up front: the transport would only refuse after the confirmation prompt + if (Test-CWCApiSecretConnection) { + $Message = Get-CWCAuthModeMessage -Command $MyInvocation.MyCommand.Name -Required Credentials + return Write-Error $Message -ErrorId 'CWC.AuthModeMismatch' -Category InvalidOperation + } + + # Refuses a path that could name the Toolbox root or something outside it ('/', '..', '...', 'C:') + $ItemPath = Resolve-CWCToolboxPath -Path $Path -Folder + if (-not $ItemPath) { return } + + # ConfirmImpact High: a deleted item can't be restored, and a folder takes its contents with it + if (-not $PSCmdlet.ShouldProcess($ItemPath, 'Delete Toolbox item')) { return } + + # ProcessToolboxOperation(ToolboxOperation operation, string path, string originalPath); + # originalPath is only used by Move. Never retried. + $Delete = @($script:CWCToolboxOperation.Delete, $ItemPath, $null) + $null = Invoke-CWCServiceMethod -Service ToolboxService -Method ProcessToolboxOperation -Arguments $Delete + } +} diff --git a/source/prefix.ps1 b/source/prefix.ps1 index f45b01c..c65bba8 100644 --- a/source/prefix.ps1 +++ b/source/prefix.ps1 @@ -22,7 +22,7 @@ $script:CWCProcessType = @{ Host = 1; Guest = 2 } $script:CWCAllSessionPermissions = 268435455 # ScreenConnect.SessionEventType values used by this module (verified live from the web client's -# SC.types.SessionEventType, 2026-11-10) +# SC.types.SessionEventType, 2026-11-10; the tool events above 100 2026-11-11) $script:CWCSessionEventType = @{ DeletedEvent = 1 Connected = 10 @@ -36,8 +36,15 @@ $script:CWCSessionEventType = @{ QueuedForceDisconnect = 48 RanCommand = 70 QueuedUninstallAndDelete = 100 + QueuedElevatedTool = 101 + QueuedSilentElevatedTool = 117 } +# ScreenConnect.ToolboxOperation value used by this module, for ToolboxService.ProcessToolboxOperation +# (verified live from the web client's SC.types.ToolboxOperation, 2026-11-11). The full enum: RunTool 0, +# CreateDirectory 1, Move 2, Delete 3, RunToolElevated 4, RunToolSilentElevated 5. +$script:CWCToolboxOperation = @{ Delete = 3 } + # Remote Workforce extension ID (App_Extensions//Service.ashx) $script:CWCRemoteWorkforceExtensionID = '2c4f522f-b39a-413a-8807-dc52a2fce13e' From da9c495b91ca9efadeaa8557b8139be8608be33d Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Thu, 12 Nov 2026 10:14:25 -0700 Subject: [PATCH 2/5] Toolbox: address review findings Add-CWCToolboxItem deletes an incomplete item when a later chunk fails or the upload is stopped, says that it replaces an item, and caps -ChunkSize at 4 MB. Toolbox paths refuse device names and long parts. Send-CWCToolboxItem -Elevated and -Silent ask for confirmation. A confirmation prompt that cannot be shown now stops the command in Remove-CWCToolboxItem, Add-CWCToolboxItem, Send-CWCToolboxItem, Remove-CWCHostFromSession, Add-CWCSessionNote and Send-CWCSessionMessage; they went on and sent the request. The 401 hint on an MFA connection names Connect-CWC -Force. Co-Authored-By: Claude Fable 5.2 --- Tests/ConnectWiseControlAPI.Private.Tests.ps1 | 12 +++ Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 85 ++++++++++++++++++- source/Private/Invoke-CWCWebRequest.ps1 | 5 ++ source/Private/Resolve-CWCToolboxPath.ps1 | 7 +- .../PageService/Remove-CWCHostFromSession.ps1 | 5 +- source/Public/RestApi/Add-CWCSessionNote.ps1 | 5 +- .../Public/RestApi/Send-CWCSessionMessage.ps1 | 5 +- source/Public/RestApi/Send-CWCToolboxItem.ps1 | 19 ++++- .../ToolboxService/Add-CWCToolboxItem.ps1 | 39 +++++++-- .../ToolboxService/Remove-CWCToolboxItem.ps1 | 5 +- 10 files changed, 168 insertions(+), 19 deletions(-) diff --git a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 index 511c089..80eccaa 100644 --- a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 @@ -438,6 +438,18 @@ Describe 'Invoke-CWCWebRequest' { } } + It 'suggests Connect-CWC -Force on an MFA connection refused with 401 Needs permission, not on a 500' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { throw (& $script:NewServerErrorRecord '{"errorType":"SecurityException","message":"Needs permission"}' $null 401) } + $null = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/ToolboxService.ashx/WriteToolboxFileContent'; Method = 'Post' } -ErrorAction SilentlyContinue -ErrorVariable err + "$err" | Should -Match 'MFA login has expired' + "$err" | Should -Match 'Connect-CWC with -Force' + Mock Invoke-WebRequest { throw (& $script:NewServerErrorRecord '{"errorType":"SecurityException","message":"Needs permission"}' $null) } + $null = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/ToolboxService.ashx/WriteToolboxFileContent'; Method = 'Post' } -ErrorAction SilentlyContinue -ErrorVariable err + "$err" | Should -Not -Match 'Connect-CWC with -Force' + } + } + It 'says the login may have expired on an anti-forgery error' { InModuleScope 'ConnectWiseControlAPI' { Mock Invoke-WebRequest { throw (& $script:NewServerErrorRecord '{"errorType":"InvalidOperationException","message":"Invalid anti-forgery token"}' $null) } diff --git a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 index 22cf1b6..7f4e396 100644 --- a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 @@ -2339,6 +2339,31 @@ Describe 'Session event functions (credentials)' { } } + # A prompt cannot be answered in a test. A runspace without a host UI fails at the prompt (HostException) + # and the command must stop there. A call that does not prompt goes on to the next check: there is no + # connection in that runspace, so it reports CWC.NotConnected. + It '' -ForEach @( + @{ Case = 'Send-CWCToolboxItem -Silent asks for confirmation'; Call = "Send-CWCToolboxItem -GUID ([guid]::NewGuid()) -Name 'Tool.cmd' -Silent"; Prompts = $true } + @{ Case = 'Send-CWCToolboxItem -Elevated asks for confirmation'; Call = "Send-CWCToolboxItem -GUID ([guid]::NewGuid()) -Name 'Tool.cmd' -Elevated"; Prompts = $true } + @{ Case = 'Send-CWCToolboxItem does not ask for a standard run'; Call = "Send-CWCToolboxItem -GUID ([guid]::NewGuid()) -Name 'Tool.cmd'"; Prompts = $false } + @{ Case = 'Send-CWCToolboxItem -Silent -Confirm:$false does not ask'; Call = "Send-CWCToolboxItem -GUID ([guid]::NewGuid()) -Name 'Tool.cmd' -Silent -Confirm:`$false"; Prompts = $false } + @{ Case = 'Send-CWCToolboxItem -Silent does not ask when $ConfirmPreference is None'; Call = "`$ConfirmPreference = 'None'; Send-CWCToolboxItem -GUID ([guid]::NewGuid()) -Name 'Tool.cmd' -Silent"; Prompts = $false } + @{ Case = 'Remove-CWCToolboxItem stops when it cannot ask'; Call = "Remove-CWCToolboxItem -Path 'Tool.cmd'"; Prompts = $true } + @{ Case = 'Remove-CWCHostFromSession stops when it cannot ask'; Call = "Remove-CWCHostFromSession -SessionID ([guid]::NewGuid()) -ConnectionID ([guid]::NewGuid()) -Group 'All Machines'"; Prompts = $true } + @{ Case = 'Add-CWCSessionNote -Confirm stops when it cannot ask'; Call = "Add-CWCSessionNote -GUID ([guid]::NewGuid()) -Note 'n' -Confirm"; Prompts = $true } + @{ Case = 'Send-CWCSessionMessage -Confirm stops when it cannot ask'; Call = "Send-CWCSessionMessage -GUID ([guid]::NewGuid()) -Message 'm' -Confirm"; Prompts = $true } + ) { + $ModulePath = (Get-Module 'ConnectWiseControlAPI').Path + $Shell = [powershell]::Create() + try { + $null = $Shell.AddScript("Import-Module '$ModulePath'; $Call").Invoke() + $Ids = @($Shell.Streams.Error | ForEach-Object { $_.FullyQualifiedErrorId.Split(',')[0] }) + if ($Prompts) { $Ids | Should -Be @('HostException') } else { $Ids | Should -Be @('CWC.NotConnected') } + } finally { + $Shell.Dispose() + } + } + It 'Send-CWCSessionMessage warns that -From is ignored' { InModuleScope 'ConnectWiseControlAPI' { Mock Invoke-CWCWebRequest {} @@ -2705,7 +2730,30 @@ Describe 'Add-CWCToolboxItem' { } } - It 'warns about a partial file when a later chunk fails' { + It 'deletes the incomplete item when a later chunk fails' { + New-CWCTestFile 'Big.bin' 1, 2, 3, 4, 5, 6 + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { + param($Arguments) + $null = $script:ToolboxCalls.Add([PSCustomObject]@{ + Endpoint = $Arguments.Endpoint + Body = $Arguments.Body | ConvertFrom-Json + }) + if ($script:ToolboxCalls.Count -eq 3) { Write-Error 'HTTP 500' -ErrorId 'CWC.Http500' } + } + Mock Write-Warning {} + Add-CWCToolboxItem -Path 'TestDrive:\Big.bin' -Name 'Scripts\Big.bin' -ChunkSize 2 -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + # folder, chunk 1, chunk 2 (fails), delete: the third chunk is never sent + $script:ToolboxCalls.Count | Should -Be 4 + $script:ToolboxCalls[3].Endpoint | Should -Be 'Services/ToolboxService.ashx/ProcessToolboxOperation' + $script:ToolboxCalls[3].Body[0] | Should -Be 3 + $script:ToolboxCalls[3].Body[1] | Should -Be 'Scripts/Big.bin' + $err[-1].FullyQualifiedErrorId | Should -BeLike 'CWC.Http500*' + Should -Invoke Write-Warning -Times 1 -ParameterFilter { $Message -like '*asked to delete the incomplete item*' } + } + } + + It 'says so when the incomplete item cannot be deleted' { New-CWCTestFile 'Big.bin' 1, 2, 3, 4 InModuleScope 'ConnectWiseControlAPI' { $script:ToolboxCallCount = 0 @@ -2715,9 +2763,37 @@ Describe 'Add-CWCToolboxItem' { } Mock Write-Warning {} Add-CWCToolboxItem -Path 'TestDrive:\Big.bin' -ChunkSize 2 -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue - $script:ToolboxCallCount | Should -Be 2 - $err[-1].FullyQualifiedErrorId | Should -BeLike 'CWC.Http500*' - Should -Invoke Write-Warning -Times 1 -ParameterFilter { $Message -like '*partial file*' } + $script:ToolboxCallCount | Should -Be 3 + @($err | Where-Object { $_.FullyQualifiedErrorId -like 'CWC.Http500,Add-CWCToolboxItem' }).Count | Should -Be 1 + Should -Invoke Write-Warning -Times 1 -ParameterFilter { $Message -like '*could not be deleted*Remove-CWCToolboxItem*' } + } + } + + It 'does not delete anything when the first chunk fails (an existing item may be untouched)' { + New-CWCTestFile 'Tool.cmd' 1, 2 + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { Write-Error 'HTTP 500' -ErrorId 'CWC.Http500' } + Mock Write-Warning {} + Add-CWCToolboxItem -Path 'TestDrive:\Tool.cmd' -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + Should -Invoke Invoke-CWCWebRequest -Times 1 -Exactly + Should -Invoke Write-Warning -Times 0 + } + } + + It 'sends a file that is an exact multiple of the chunk size without an empty last chunk' { + New-CWCTestFile 'Even.bin' 1, 2, 3, 4 + InModuleScope 'ConnectWiseControlAPI' { + Add-CWCToolboxItem -Path 'TestDrive:\Even.bin' -ChunkSize 2 -Confirm:$false + $script:ToolboxCalls.Count | Should -Be 2 + @($script:ToolboxCalls | ForEach-Object { $_.Endpoint }) | Should -Not -Contain 'Services/ToolboxService.ashx/ProcessToolboxOperation' + } + } + + It 'refuses a -ChunkSize above 4 MB' { + New-CWCTestFile 'Tool.cmd' 1 + InModuleScope 'ConnectWiseControlAPI' { + { Add-CWCToolboxItem -Path 'TestDrive:\Tool.cmd' -ChunkSize 4194305 -Confirm:$false } | Should -Throw + $script:ToolboxCalls.Count | Should -Be 0 } } @@ -2743,6 +2819,7 @@ Describe 'Add-CWCToolboxItem' { It 'refuses the -Name <_> without calling the API' -ForEach @( '..\x.cmd', 'Scripts/', 'a//b.cmd', './x.cmd', '/', '.. /x.cmd', 'C:\x.cmd', 'x.cmd.', 'a*b.cmd' + 'CON', 'nul.txt', 'Scripts/com1.cmd', 'LPT9/x.cmd', ('a' * 256) ) { New-CWCTestFile 'Tool.cmd' 1 InModuleScope 'ConnectWiseControlAPI' -Parameters @{ BadName = $_ } { diff --git a/source/Private/Invoke-CWCWebRequest.ps1 b/source/Private/Invoke-CWCWebRequest.ps1 index d49c3c1..0ff07ab 100644 --- a/source/Private/Invoke-CWCWebRequest.ps1 +++ b/source/Private/Invoke-CWCWebRequest.ps1 @@ -126,6 +126,11 @@ if ($StatusCode -gt 0 -and $script:CWCServerConnection.AuthType -eq 'Mfa' -and -not $script:CWCServerConnection.LoggingIn -and ("$ServerErrorType" -match 'Security' -or "$ServerMessage" -match 'anti-?forgery|Needs permission')) { $ErrorMessage += 'If the MFA login has expired, run Connect-CWC again.' + # Connect-CWC reuses a cached MFA login that still answers ordinary calls, which is the case + # described below, so only -Force signs in again. + if ($StatusCode -eq 401 -and "$ServerMessage" -match 'Needs permission') { + $ErrorMessage += 'If the error stays and the account has this permission, run Connect-CWC with -Force.' + } } # A credentials login keeps working for ordinary calls after the server stops honouring its # management permissions: ToolboxService and SessionGroupService answered 401 "Needs permission" diff --git a/source/Private/Resolve-CWCToolboxPath.ps1 b/source/Private/Resolve-CWCToolboxPath.ps1 index dcfe651..b4dfbdc 100644 --- a/source/Private/Resolve-CWCToolboxPath.ps1 +++ b/source/Private/Resolve-CWCToolboxPath.ps1 @@ -9,7 +9,9 @@ function Resolve-CWCToolboxPath { inside the Toolbox, such as the Toolbox root, its parent or another drive: an empty path, or a part that is empty, ends in a dot or whitespace (Windows drops those, so '.', '..', '...' and '. ' all resolve to a folder above the item), or holds a character Windows does not allow in a - file name (which covers 'C:'). A file path ending in a slash is refused too. + file name (which covers 'C:'). A file path ending in a slash is refused too, and so is a part that + is a Windows device name (CON, NUL, COM1, with or without an extension) or longer than 255 + characters. .PARAMETER Path Path of the item inside the Toolbox. @@ -31,7 +33,8 @@ function Resolve-CWCToolboxPath { if ($Folder) { $Clean = $Clean.TrimEnd('/') } $BadParts = @($Clean -split '/' | Where-Object { - [string]::IsNullOrWhiteSpace($_) -or $_ -match '[.\s]$' -or $_ -match '[:*?"<>|\x00-\x1f]' + [string]::IsNullOrWhiteSpace($_) -or $_ -match '[.\s]$' -or $_ -match '[:*?"<>|\x00-\x1f]' -or + $_ -match '^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(\.|$)' -or $_.Length -gt 255 }) if ($BadParts.Count -gt 0) { $Message = "'$Path' is not a valid Toolbox path." diff --git a/source/Public/PageService/Remove-CWCHostFromSession.ps1 b/source/Public/PageService/Remove-CWCHostFromSession.ps1 index 6748651..6a81c4c 100644 --- a/source/Public/PageService/Remove-CWCHostFromSession.ps1 +++ b/source/Public/PageService/Remove-CWCHostFromSession.ps1 @@ -45,7 +45,10 @@ function Remove-CWCHostFromSession { [string[]]$Group ) - if (-not $PSCmdlet.ShouldProcess("Connection $ConnectionID in session $SessionID", 'Force disconnect')) { return } + # A prompt that cannot be shown throws: the assignment then never happens and nothing is sent + $Proceed = $False + $Proceed = $PSCmdlet.ShouldProcess("Connection $ConnectionID in session $SessionID", 'Force disconnect') + if (-not $Proceed) { return } Add-CWCSessionEvent -Group $Group -Entry @{ SessionID = $SessionID diff --git a/source/Public/RestApi/Add-CWCSessionNote.ps1 b/source/Public/RestApi/Add-CWCSessionNote.ps1 index 11f8723..1dd1284 100644 --- a/source/Public/RestApi/Add-CWCSessionNote.ps1 +++ b/source/Public/RestApi/Add-CWCSessionNote.ps1 @@ -45,7 +45,10 @@ function Add-CWCSessionNote { ) process { - if (-not $PSCmdlet.ShouldProcess("$GUID", 'Add note')) { return } + # A prompt that cannot be shown throws: the assignment then never happens and nothing is sent + $Proceed = $False + $Proceed = $PSCmdlet.ShouldProcess("$GUID", 'Add note') + if (-not $Proceed) { return } # Adding an event is not idempotent: never retried if (Test-CWCApiSecretConnection) { diff --git a/source/Public/RestApi/Send-CWCSessionMessage.ps1 b/source/Public/RestApi/Send-CWCSessionMessage.ps1 index 70a49f8..948e038 100644 --- a/source/Public/RestApi/Send-CWCSessionMessage.ps1 +++ b/source/Public/RestApi/Send-CWCSessionMessage.ps1 @@ -54,7 +54,10 @@ function Send-CWCSessionMessage { ) process { - if (-not $PSCmdlet.ShouldProcess("$GUID", 'Send message')) { return } + # A prompt that cannot be shown throws: the assignment then never happens and nothing is sent + $Proceed = $False + $Proceed = $PSCmdlet.ShouldProcess("$GUID", 'Send message') + if (-not $Proceed) { return } # Adding an event is not idempotent: never retried if (Test-CWCApiSecretConnection) { diff --git a/source/Public/RestApi/Send-CWCToolboxItem.ps1 b/source/Public/RestApi/Send-CWCToolboxItem.ps1 index e8c4659..1910966 100644 --- a/source/Public/RestApi/Send-CWCToolboxItem.ps1 +++ b/source/Public/RestApi/Send-CWCToolboxItem.ps1 @@ -8,6 +8,10 @@ function Send-CWCToolboxItem { event instead, which runs the item with administrative privileges; -Silent queues a QueuedSilentElevatedTool event, which runs it elevated and silently. + -Elevated and -Silent ask for confirmation, like the Remove-* commands: the item runs with + administrative rights, and with -Silent nobody at the machine sees it. Pass -Confirm:$false in + unattended scripts. + The machine opens the item the way Windows opens a file, so use a file type that runs when opened (.exe, .msi, .cmd, .bat): a .ps1 opens in its default program instead of running. @@ -41,8 +45,12 @@ function Send-CWCToolboxItem { .EXAMPLE Send-CWCToolboxItem -GUID $SessionID -Name 'Installers/Setup.exe' -Elevated + Asks for confirmation, then runs the item with administrative privileges. + .EXAMPLE - Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.cmd' -Silent + Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.cmd' -Silent -Confirm:$false + + Runs the item elevated and silently, without asking. .NOTES Author: Chris Taylor @@ -87,7 +95,14 @@ function Send-CWCToolboxItem { $EventType = $script:CWCSessionEventType.QueuedElevatedTool $Action = "Run toolbox item '$Name' elevated" } - if (-not $PSCmdlet.ShouldProcess("$GUID", $Action)) { return } + # An elevated run is treated as high impact, a standard run is not. The command's impact is Medium, + # so lowering the default preference (High) to Medium makes ShouldProcess ask. -Confirm:$false and a + # caller's own $ConfirmPreference arrive here as other values and are left alone. + if (($Silent -or $Elevated) -and $ConfirmPreference -eq 'High') { $ConfirmPreference = 'Medium' } + # A prompt that cannot be shown throws: the assignment then never happens and nothing is sent + $Proceed = $False + $Proceed = $PSCmdlet.ShouldProcess("$GUID", $Action) + if (-not $Proceed) { return } # Adding an event is not idempotent: never retried if (Test-CWCApiSecretConnection) { diff --git a/source/Public/ToolboxService/Add-CWCToolboxItem.ps1 b/source/Public/ToolboxService/Add-CWCToolboxItem.ps1 index 429c6bc..742e24c 100644 --- a/source/Public/ToolboxService/Add-CWCToolboxItem.ps1 +++ b/source/Public/ToolboxService/Add-CWCToolboxItem.ps1 @@ -8,8 +8,11 @@ function Add-CWCToolboxItem { the item, replacing an item of the same name, and the rest are appended. The user needs the ManageSharedToolbox permission. - When -Name contains a folder, that folder is created first. If a chunk fails, a partial file is - left in the Toolbox; run the command again to replace it. + When -Name contains a folder, that folder is created first. + + The first chunk replaces an existing item at once. If a later chunk fails, or the upload is + stopped with Ctrl+C, the incomplete item is deleted so it cannot be run; an item it was replacing + is gone. Run the command again to upload it. Several files can be piped in; each keeps its own file name. @@ -26,8 +29,8 @@ function Add-CWCToolboxItem { Create the Toolbox folder -Name instead of uploading a file. .PARAMETER ChunkSize - Bytes of the file sent per request. Defaults to 524288 (512 KB). Lower it if the server rejects - the request as too large. + Bytes of the file sent per request, up to 4194304 (4 MB). Defaults to 524288 (512 KB). Lower it + if the server rejects the request as too large. .EXAMPLE Add-CWCToolboxItem -Path .\Cleanup.cmd @@ -69,7 +72,7 @@ function Add-CWCToolboxItem { [switch]$Directory, [Parameter(ParameterSetName = 'File')] - [ValidateRange(1, 2147483647)] + [ValidateRange(1, 4194304)] [int]$ChunkSize = 524288 ) @@ -114,9 +117,14 @@ function Add-CWCToolboxItem { $ItemName = Resolve-CWCToolboxPath -Path $ItemName if (-not $ItemName) { return } - if (-not $PSCmdlet.ShouldProcess($ItemName, "Upload '$LocalPath' to the Toolbox")) { return } + $Action = "Upload '$LocalPath' to the Toolbox, replacing an item of that name" + # A prompt that cannot be shown throws: the assignment then never happens and nothing is sent + $Proceed = $False + $Proceed = $PSCmdlet.ShouldProcess($ItemName, $Action) + if (-not $Proceed) { return } $Append = $False + $Completed = $False try { $Stream = [System.IO.File]::OpenRead($LocalPath) try { @@ -136,13 +144,30 @@ function Add-CWCToolboxItem { $null = Invoke-CWCServiceMethod @Write -Arguments $Chunk -Sensitive -ErrorAction Stop $Append = $True } + $Completed = $True } finally { $Stream.Dispose() } } catch { - if ($Append) { Write-Warning "Upload of '$ItemName' stopped part way; a partial file is in the Toolbox." } # WriteError keeps the transport's ErrorId (CWC.Http401, ...); Write-Error $_ loses it on PS 5.1 $PSCmdlet.WriteError($_) + } finally { + # Runs after an error and on Ctrl+C. Once the first chunk is written, the item under that name is + # incomplete (the item it replaced is already gone) and Send-CWCToolboxItem could still run it. + # Not deleted when the first chunk failed: an existing item may be untouched then. + if ($Append -and -not $Completed) { + # ProcessToolboxOperation(ToolboxOperation operation, string path, string originalPath) + $Delete = @($script:CWCToolboxOperation.Delete, $ItemName, $null) + try { + $null = Invoke-CWCServiceMethod -Service ToolboxService -Method ProcessToolboxOperation ` + -Arguments $Delete -ErrorAction Stop + Write-Warning ("Upload of '$ItemName' stopped part way; the server was asked to delete the " + + 'incomplete item. Check with Get-CWCToolbox.') + } catch { + Write-Warning ("Upload of '$ItemName' stopped part way and the incomplete item could not be " + + 'deleted. Remove it with Remove-CWCToolboxItem.') + } + } } } } diff --git a/source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 b/source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 index cd32efc..3fc9d46 100644 --- a/source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 +++ b/source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 @@ -47,7 +47,10 @@ function Remove-CWCToolboxItem { if (-not $ItemPath) { return } # ConfirmImpact High: a deleted item can't be restored, and a folder takes its contents with it - if (-not $PSCmdlet.ShouldProcess($ItemPath, 'Delete Toolbox item')) { return } + # A prompt that cannot be shown throws: the assignment then never happens and nothing is sent + $Proceed = $False + $Proceed = $PSCmdlet.ShouldProcess($ItemPath, 'Delete Toolbox item') + if (-not $Proceed) { return } # ProcessToolboxOperation(ToolboxOperation operation, string path, string originalPath); # originalPath is only used by Move. Never retried. From 4e9d942c5485f4eb12ca96c406cff41f14a86fcc Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Thu, 12 Nov 2026 10:17:12 -0700 Subject: [PATCH 3/5] Toolbox: ship in 0.5.0; regenerate help on master Move the Toolbox notes into the 0.5.0 section (35 commands), list the commands that ask for confirmation in the README and the about topic, and regenerate the help after the rebase. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 37 +- Docs/Add-CWCToolboxItem.md | 14 +- Docs/Send-CWCToolboxItem.md | 67 ++- README.md | 5 +- source/en-US/ConnectWiseControlAPI-help.xml | 511 +++++++++++++++++- .../about_ConnectWiseControlAPI.help.txt | 8 +- 6 files changed, 604 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbec81f..71f5564 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,33 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -### Added - -- `Add-CWCToolboxItem` uploads a file to the shared Toolbox in chunks, or creates a Toolbox folder - (`ToolboxService.WriteToolboxFileContent`; needs the ManageSharedToolbox permission; credentials - connections only). Accepts files from the pipeline -- `Get-CWCToolbox` lists the Toolbox contents (`PageService.GetToolbox`) as one object per folder and file - with its path; `-Raw` returns the server's tree -- `Remove-CWCToolboxItem` deletes a Toolbox file or folder (`ToolboxService.ProcessToolboxOperation`, Delete); - asks for confirmation by default -- `Send-CWCToolboxItem -Elevated` runs the item with administrative privileges (QueuedElevatedTool 101) and - `-Silent` runs it elevated and silently (QueuedSilentElevatedTool 117); credentials connections only - -### Changed - -- A 401 "Needs permission" on a credentials connection now suggests `Connect-CWC -Force`: the server stops - honouring an older login's management permissions while ordinary calls keep working - ## [0.5.0] - 2026-11-10 Version numbers now have three parts (`0.5.0`). The previous release was 0.4.0.0, which had 21 commands; this -release has 32. +release has 35. ### Breaking changes -- `Remove-CWCSession`, `Remove-CWCSessionNote` and `Remove-CWCHostFromSession` ask for confirmation by default. +- `Remove-CWCSession`, `Remove-CWCSessionNote`, `Remove-CWCHostFromSession` and the new `Remove-CWCToolboxItem` + ask for confirmation by default, and so does `Send-CWCToolboxItem` with the new `-Elevated` or `-Silent`. Unattended scripts must add `-Confirm:$false`. Without it, a session started with `-NonInteractive` fails at - the prompt and removes nothing; other unattended hosts may wait at the prompt or take its default answer (Yes) + the prompt and does nothing; other unattended hosts may wait at the prompt or take its default answer (Yes) - `Connect-CWC` without `-Force` switches to a different server, sign-in method or user instead of keeping the old connection - `Get-CWCLastContact` returns an error when no connection event is found, instead of the current time @@ -92,6 +76,17 @@ Details are in the sections below. (`InitiatedJoin`). `-UrlOnly` returns the URL instead (for macOS/Linux or custom launchers), using a 5-minute delegated token when the role allows it. The token is never written to any output stream. Credentials connections only; launching is Windows only +- `Get-CWCToolbox` lists the Toolbox contents (`PageService.GetToolbox`) as one object per folder and file + with its path; `-Raw` returns the server's tree. Credentials connections only +- `Add-CWCToolboxItem` uploads a file to the shared Toolbox in chunks, or creates a Toolbox folder + (`ToolboxService.WriteToolboxFileContent`; needs the ManageSharedToolbox permission; credentials + connections only). Accepts files from the pipeline. It replaces an item of the same name. If the upload + fails or is stopped part way, the incomplete item is deleted so it cannot be run +- `Remove-CWCToolboxItem` deletes a Toolbox file or folder (`ToolboxService.ProcessToolboxOperation`, Delete); + asks for confirmation by default. Credentials connections only +- `Send-CWCToolboxItem -Elevated` runs the item with administrative privileges (QueuedElevatedTool 101) and + `-Silent` runs it elevated and silently (QueuedSilentElevatedTool 117). Both ask for confirmation unless + `-Confirm:$false` is passed; credentials connections only ### Deprecated @@ -131,6 +126,8 @@ Details are in the sections below. - `Invoke-CWCCommand` waits 1, 2, 3 … up to 5 seconds between polls of the rate-limited session details - `Enter-CWCSession` takes `-Name` from the pipeline (e.g. from `Get-CWCSession`) and then skips its session lookup +- A 401 "Needs permission" on a credentials or MFA connection suggests `Connect-CWC -Force` (#31): the server + stops honouring an older login's management permissions while ordinary calls keep working ### Fixed diff --git a/Docs/Add-CWCToolboxItem.md b/Docs/Add-CWCToolboxItem.md index e6a17f6..4dca6cb 100644 --- a/Docs/Add-CWCToolboxItem.md +++ b/Docs/Add-CWCToolboxItem.md @@ -32,8 +32,12 @@ The user needs the ManageSharedToolbox permission. When -Name contains a folder, that folder is created first. -If a chunk fails, a partial file is -left in the Toolbox; run the command again to replace it. + +The first chunk replaces an existing item at once. +If a later chunk fails, or the upload is +stopped with Ctrl+C, the incomplete item is deleted so it cannot be run; an item it was replacing +is gone. +Run the command again to upload it. Several files can be piped in; each keeps its own file name. @@ -130,10 +134,10 @@ Accept wildcard characters: False ``` ### -ChunkSize -Bytes of the file sent per request. +Bytes of the file sent per request, up to 4194304 (4 MB). Defaults to 524288 (512 KB). -Lower it if the server rejects -the request as too large. +Lower it +if the server rejects the request as too large. ```yaml Type: Int32 diff --git a/Docs/Send-CWCToolboxItem.md b/Docs/Send-CWCToolboxItem.md index 2205420..5e961d4 100644 --- a/Docs/Send-CWCToolboxItem.md +++ b/Docs/Send-CWCToolboxItem.md @@ -13,12 +13,22 @@ Queues a Toolbox item to run on a session. ## SYNTAX ``` -Send-CWCToolboxItem [-GUID] [-Name] [[-Group] ] - [-WhatIf] [-Confirm] [] +Send-CWCToolboxItem [-GUID] [-Name] [[-Group] ] [-Elevated] [-Silent] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION Queues a QueuedTool session event naming the Toolbox item. +-Elevated queues a QueuedElevatedTool +event instead, which runs the item with administrative privileges; -Silent queues a +QueuedSilentElevatedTool event, which runs it elevated and silently. + +-Elevated and -Silent ask for confirmation, like the Remove-* commands: the item runs with +administrative rights, and with -Silent nobody at the machine sees it. +Pass -Confirm:$false in +unattended scripts. + +The machine opens the item the way Windows opens a file, so use a file type that runs when opened +(.exe, .msi, .cmd, .bat): a .ps1 opens in its default program instead of running. Credentials connections: PageService.AddSessionEvents; the user needs the RunSharedTool permission in -Group. @@ -27,14 +37,29 @@ API secret connections: the RESTful API Manager extension's SendToolboxItemToSes The event is attributed to the extension's RESTfulUserName setting ("RESTful API" unless renamed); -Group is ignored. +-Elevated and -Silent are not available: the extension only queues the standard event. ## EXAMPLES ### EXAMPLE 1 ``` -Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.ps1' +Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.cmd' +``` + +### EXAMPLE 2 +``` +Send-CWCToolboxItem -GUID $SessionID -Name 'Installers/Setup.exe' -Elevated +``` + +Asks for confirmation, then runs the item with administrative privileges. + +### EXAMPLE 3 +``` +Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.cmd' -Silent -Confirm:$false ``` +Runs the item elevated and silently, without asking. + ## PARAMETERS ### -GUID @@ -54,6 +79,8 @@ Accept wildcard characters: False ### -Name Toolbox item name as shown in the ScreenConnect Toolbox. +For an item in a folder, the Path that +Get-CWCToolbox returns. ```yaml Type: String @@ -83,6 +110,40 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -Elevated +Run the item with administrative privileges (QueuedElevatedTool). +Credentials connections only. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Silent +Run the item elevated and silently (QueuedSilentElevatedTool): it runs as NT AUTHORITY\SYSTEM +(seen live, 2026-11-11). +Implies -Elevated. +Credentials connections only. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. diff --git a/README.md b/README.md index 34e1f5d..a9c576f 100644 --- a/README.md +++ b/README.md @@ -52,9 +52,10 @@ Install-Module 'ConnectWiseControlAPI' 0.5.0 changes some behaviour. Check your scripts before you update: -* `Remove-CWCSession`, `Remove-CWCSessionNote` and `Remove-CWCHostFromSession` ask for confirmation by default. +* `Remove-CWCSession`, `Remove-CWCSessionNote`, `Remove-CWCHostFromSession` and `Remove-CWCToolboxItem` ask for + confirmation by default, and so does `Send-CWCToolboxItem` with `-Elevated` or `-Silent`. Unattended scripts must add `-Confirm:$false`. Without it, a session started with `-NonInteractive` fails at the - prompt and removes nothing; other unattended hosts may wait at the prompt or take its default answer (Yes). + prompt and does nothing; other unattended hosts may wait at the prompt or take its default answer (Yes). * `Connect-CWC` without `-Force` now switches to a different server, sign-in method or user. Before, it kept the old connection. * `Get-CWCLastContact` returns an error when it finds no connection event. Before, it returned the current time. diff --git a/source/en-US/ConnectWiseControlAPI-help.xml b/source/en-US/ConnectWiseControlAPI-help.xml index 39977a2..8b5a46f 100644 --- a/source/en-US/ConnectWiseControlAPI-help.xml +++ b/source/en-US/ConnectWiseControlAPI-help.xml @@ -251,6 +251,251 @@ + + + Add-CWCToolboxItem + Add + CWCToolboxItem + + Uploads a file to the shared ScreenConnect Toolbox, or creates a Toolbox folder. + + + + Calls ToolboxService.WriteToolboxFileContent. The file is sent in chunks: the first chunk creates the item, replacing an item of the same name, and the rest are appended. The user needs the ManageSharedToolbox permission. + When -Name contains a folder, that folder is created first. + The first chunk replaces an existing item at once. If a later chunk fails, or the upload is stopped with Ctrl+C, the incomplete item is deleted so it cannot be run; an item it was replacing is gone. Run the command again to upload it. + Several files can be piped in; each keeps its own file name. + Run the uploaded item on a session with Send-CWCToolboxItem. + + + + Add-CWCToolboxItem + + Path + + Local file to upload. Accepts paths and Get-Item / Get-ChildItem output from the pipeline. + + String + + String + + + None + + + Name + + Path of the item inside the Toolbox, e.g. 'Cleanup.cmd' or 'Scripts/Cleanup.cmd'. Defaults to the file name of -Path. It names one item, so it cannot be used when several files are piped in. + + String + + String + + + None + + + ChunkSize + + Bytes of the file sent per request, up to 4194304 (4 MB). Defaults to 524288 (512 KB). Lower it if the server rejects the request as too large. + + Int32 + + Int32 + + + 524288 + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + Add-CWCToolboxItem + + Name + + Path of the item inside the Toolbox, e.g. 'Cleanup.cmd' or 'Scripts/Cleanup.cmd'. Defaults to the file name of -Path. It names one item, so it cannot be used when several files are piped in. + + String + + String + + + None + + + Directory + + Create the Toolbox folder -Name instead of uploading a file. + + + SwitchParameter + + + False + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + + + Path + + Local file to upload. Accepts paths and Get-Item / Get-ChildItem output from the pipeline. + + String + + String + + + None + + + Name + + Path of the item inside the Toolbox, e.g. 'Cleanup.cmd' or 'Scripts/Cleanup.cmd'. Defaults to the file name of -Path. It names one item, so it cannot be used when several files are piped in. + + String + + String + + + None + + + Directory + + Create the Toolbox folder -Name instead of uploading a file. + + SwitchParameter + + SwitchParameter + + + False + + + ChunkSize + + Bytes of the file sent per request, up to 4194304 (4 MB). Defaults to 524288 (512 KB). Lower it if the server rejects the request as too large. + + Int32 + + Int32 + + + 524288 + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + SwitchParameter + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot write to the Toolbox). Author: Chris Taylor + + + + + -------------------------- EXAMPLE 1 -------------------------- + Add-CWCToolboxItem -Path .\Cleanup.cmd + + Uploads Cleanup.cmd to the top level of the Toolbox. + + + + -------------------------- EXAMPLE 2 -------------------------- + Add-CWCToolboxItem -Path .\Cleanup.cmd -Name 'Scripts/Cleanup.cmd' + + Creates the Scripts folder if needed and uploads the file into it. + + + + -------------------------- EXAMPLE 3 -------------------------- + Get-ChildItem .\Tools\*.exe | Add-CWCToolboxItem + + + + + + -------------------------- EXAMPLE 4 -------------------------- + Add-CWCToolboxItem -Directory -Name 'Scripts' + + + + + + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + + Connect-CWC @@ -2123,6 +2368,80 @@ open $Url # macOS + + + Get-CWCToolbox + Get + CWCToolbox + + Lists the contents of the ScreenConnect Toolbox. + + + + Calls PageService.GetToolbox, the same call the host client makes to list Toolbox items. Any signed-in user can call it. + The server returns a tree: a root folder whose Items hold folders and files, each with a Name, Attributes (1 for a folder, 0 for a file), a base64 icon (Image) and its own Items. By default the tree is flattened to one object per folder and file, with its Path inside the Toolbox and without the icon. + Use it to find an item for Send-CWCToolboxItem, or to check an upload made with Add-CWCToolboxItem. + + + + Get-CWCToolbox + + Raw + + Return the tree as the server sends it, including the icons. + + + SwitchParameter + + + False + + + + + + Raw + + Return the tree as the server sends it, including the icons. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot list the Toolbox). Author: Chris Taylor + + + + + -------------------------- EXAMPLE 1 -------------------------- + Get-CWCToolbox + + Lists every folder and file in the Toolbox. + + + + -------------------------- EXAMPLE 2 -------------------------- + Get-CWCToolbox | Where-Object { -not $_.IsFolder -and $_.Path -like 'Scripts/*' } + + + + + + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + + Initialize-CWCRemoteWorkforceSessionGroup @@ -3971,6 +4290,126 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { + + + Remove-CWCToolboxItem + Remove + CWCToolboxItem + + Deletes a file or folder from the shared ScreenConnect Toolbox. + + + + Calls ToolboxService.ProcessToolboxOperation with the Delete operation. The user needs the ManageSharedToolbox permission. + Only items stored in the server's Toolbox folder can be deleted. Items that an extension adds (for example Command Toolbox commands) are refused by the server with "Cannot edit virtual toolbox item". + + + + Remove-CWCToolboxItem + + Path + + Path of the item inside the Toolbox, e.g. 'Cleanup.cmd' or 'Scripts/Cleanup.cmd': the Path that Get-CWCToolbox returns. + + String + + String + + + None + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + SwitchParameter + + + False + + + + + + Path + + Path of the item inside the Toolbox, e.g. 'Cleanup.cmd' or 'Scripts/Cleanup.cmd': the Path that Get-CWCToolbox returns. + + String + + String + + + None + + + WhatIf + + Shows what would happen if the cmdlet runs. The cmdlet is not run. + + SwitchParameter + + SwitchParameter + + + False + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + SwitchParameter + + SwitchParameter + + + False + + + + + + + Requires Connect-CWC -Credentials (the RESTful API Manager extension cannot change the Toolbox). Author: Chris Taylor + + + + + -------------------------- EXAMPLE 1 -------------------------- + Remove-CWCToolboxItem -Path 'Scripts/Cleanup.cmd' + + + + + + -------------------------- EXAMPLE 2 -------------------------- + Get-CWCToolbox | Where-Object Path -like 'API Test/*.cmd' | Remove-CWCToolboxItem -Confirm:$false + + + + + + + + https://github.com/christaylorcodes/ConnectWiseControlAPI + https://github.com/christaylorcodes/ConnectWiseControlAPI + + + Remove-CWCUser @@ -4279,9 +4718,11 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { - Queues a QueuedTool session event naming the Toolbox item. + Queues a QueuedTool session event naming the Toolbox item. -Elevated queues a QueuedElevatedTool event instead, which runs the item with administrative privileges; -Silent queues a QueuedSilentElevatedTool event, which runs it elevated and silently. + -Elevated and -Silent ask for confirmation, like the Remove-* commands: the item runs with administrative rights, and with -Silent nobody at the machine sees it. Pass -Confirm:$false in unattended scripts. + The machine opens the item the way Windows opens a file, so use a file type that runs when opened (.exe, .msi, .cmd, .bat): a .ps1 opens in its default program instead of running. Credentials connections: PageService.AddSessionEvents; the user needs the RunSharedTool permission in -Group. - API secret connections: the RESTful API Manager extension's SendToolboxItemToSession. The event is attributed to the extension's RESTfulUserName setting ("RESTful API" unless renamed); -Group is ignored. + API secret connections: the RESTful API Manager extension's SendToolboxItemToSession. The event is attributed to the extension's RESTfulUserName setting ("RESTful API" unless renamed); -Group is ignored. -Elevated and -Silent are not available: the extension only queues the standard event. @@ -4301,7 +4742,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Name - Toolbox item name as shown in the ScreenConnect Toolbox. + Toolbox item name as shown in the ScreenConnect Toolbox. For an item in a folder, the Path that Get-CWCToolbox returns. String @@ -4322,6 +4763,28 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { All Machines + + Elevated + + Run the item with administrative privileges (QueuedElevatedTool). Credentials connections only. + + + SwitchParameter + + + False + + + Silent + + Run the item elevated and silently (QueuedSilentElevatedTool): it runs as NT AUTHORITY\SYSTEM (seen live, 2026-11-11). Implies -Elevated. Credentials connections only. + + + SwitchParameter + + + False + WhatIf @@ -4362,7 +4825,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Name - Toolbox item name as shown in the ScreenConnect Toolbox. + Toolbox item name as shown in the ScreenConnect Toolbox. For an item in a folder, the Path that Get-CWCToolbox returns. String @@ -4383,6 +4846,30 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { All Machines + + Elevated + + Run the item with administrative privileges (QueuedElevatedTool). Credentials connections only. + + SwitchParameter + + SwitchParameter + + + False + + + Silent + + Run the item elevated and silently (QueuedSilentElevatedTool): it runs as NT AUTHORITY\SYSTEM (seen live, 2026-11-11). Implies -Elevated. Credentials connections only. + + SwitchParameter + + SwitchParameter + + + False + WhatIf @@ -4418,11 +4905,25 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { -------------------------- EXAMPLE 1 -------------------------- - Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.ps1' + Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.cmd' + + -------------------------- EXAMPLE 2 -------------------------- + Send-CWCToolboxItem -GUID $SessionID -Name 'Installers/Setup.exe' -Elevated + + Asks for confirmation, then runs the item with administrative privileges. + + + + -------------------------- EXAMPLE 3 -------------------------- + Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.cmd' -Silent -Confirm:$false + + Runs the item elevated and silently, without asking. + + diff --git a/source/en-US/about_ConnectWiseControlAPI.help.txt b/source/en-US/about_ConnectWiseControlAPI.help.txt index cee8559..25b20fb 100644 --- a/source/en-US/about_ConnectWiseControlAPI.help.txt +++ b/source/en-US/about_ConnectWiseControlAPI.help.txt @@ -78,9 +78,11 @@ ERRORS } REMOVING THINGS - Remove-CWCSession, Remove-CWCSessionNote and Remove-CWCHostFromSession ask - for confirmation. In an unattended script add -Confirm:$false. Without it, - a session started with -NonInteractive fails at the prompt and removes + Remove-CWCSession, Remove-CWCSessionNote, Remove-CWCHostFromSession and + Remove-CWCToolboxItem ask for confirmation. So does Send-CWCToolboxItem + with -Elevated or -Silent, which runs a Toolbox item with administrative + rights. In an unattended script add -Confirm:$false. Without it, a + session started with -NonInteractive fails at the prompt and does nothing. Other unattended hosts may wait at the prompt, or take its default answer (Yes) when they read answers from redirected input. From a34c5a7f45bc7d03a62ded6fcb23c25c44de7691 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Thu, 12 Nov 2026 10:22:51 -0700 Subject: [PATCH 4/5] Toolbox: address second review Add-CWCToolboxItem warns when the first chunk fails with the item's state unknown, and refuses -Directory:$false instead of creating a folder. A module test rejects an early return on a negated ShouldProcess call. Co-Authored-By: Claude Fable 5.2 --- Tests/ConnectWiseControlAPI.Module.Tests.ps1 | 11 +++++++++++ Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 14 +++++++++++--- source/Public/RestApi/Send-CWCToolboxItem.ps1 | 3 ++- .../Public/ToolboxService/Add-CWCToolboxItem.ps1 | 12 ++++++++++++ 4 files changed, 36 insertions(+), 4 deletions(-) diff --git a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 index dfea8c3..b1e99f1 100644 --- a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 @@ -396,6 +396,17 @@ Describe 'Repository' { $Ignored = @(git -C $RepoRoot check-ignore --no-index -- $SourceFiles | Where-Object { $_ }) $Ignored | Should -BeNullOrEmpty } + + # ShouldProcess throws when it has to ask and the host cannot prompt. The error ends only that statement, + # so 'if (-not $PSCmdlet.ShouldProcess(...)) { return }' goes on and sends the request. Use + # 'if ($PSCmdlet.ShouldProcess(...)) { ... }', or assign the result to a variable that starts as $false. + It 'has no early return on a negated ShouldProcess call' { + $SourceFolder = Join-Path (Split-Path $PSScriptRoot -Parent) 'source' + $Hits = @(Get-ChildItem $SourceFolder -Filter '*.ps1' -Recurse | + Select-String -Pattern '-not\s+\$PSCmdlet\.ShouldProcess' | + ForEach-Object { "$($_.Filename):$($_.LineNumber)" }) + $Hits | Should -BeNullOrEmpty + } } Describe 'Generated help' { diff --git a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 index 7f4e396..f15abef 100644 --- a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 @@ -2347,7 +2347,7 @@ Describe 'Session event functions (credentials)' { @{ Case = 'Send-CWCToolboxItem -Elevated asks for confirmation'; Call = "Send-CWCToolboxItem -GUID ([guid]::NewGuid()) -Name 'Tool.cmd' -Elevated"; Prompts = $true } @{ Case = 'Send-CWCToolboxItem does not ask for a standard run'; Call = "Send-CWCToolboxItem -GUID ([guid]::NewGuid()) -Name 'Tool.cmd'"; Prompts = $false } @{ Case = 'Send-CWCToolboxItem -Silent -Confirm:$false does not ask'; Call = "Send-CWCToolboxItem -GUID ([guid]::NewGuid()) -Name 'Tool.cmd' -Silent -Confirm:`$false"; Prompts = $false } - @{ Case = 'Send-CWCToolboxItem -Silent does not ask when $ConfirmPreference is None'; Call = "`$ConfirmPreference = 'None'; Send-CWCToolboxItem -GUID ([guid]::NewGuid()) -Name 'Tool.cmd' -Silent"; Prompts = $false } + @{ Case = 'Send-CWCToolboxItem -Silent does not ask when the session $ConfirmPreference is None'; Call = "`$ConfirmPreference = 'None'; Send-CWCToolboxItem -GUID ([guid]::NewGuid()) -Name 'Tool.cmd' -Silent"; Prompts = $false } @{ Case = 'Remove-CWCToolboxItem stops when it cannot ask'; Call = "Remove-CWCToolboxItem -Path 'Tool.cmd'"; Prompts = $true } @{ Case = 'Remove-CWCHostFromSession stops when it cannot ask'; Call = "Remove-CWCHostFromSession -SessionID ([guid]::NewGuid()) -ConnectionID ([guid]::NewGuid()) -Group 'All Machines'"; Prompts = $true } @{ Case = 'Add-CWCSessionNote -Confirm stops when it cannot ask'; Call = "Add-CWCSessionNote -GUID ([guid]::NewGuid()) -Note 'n' -Confirm"; Prompts = $true } @@ -2769,14 +2769,22 @@ Describe 'Add-CWCToolboxItem' { } } - It 'does not delete anything when the first chunk fails (an existing item may be untouched)' { + It 'does not delete anything when the first chunk fails (an existing item may be untouched), but warns' { New-CWCTestFile 'Tool.cmd' 1, 2 InModuleScope 'ConnectWiseControlAPI' { Mock Invoke-CWCWebRequest { Write-Error 'HTTP 500' -ErrorId 'CWC.Http500' } Mock Write-Warning {} Add-CWCToolboxItem -Path 'TestDrive:\Tool.cmd' -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue Should -Invoke Invoke-CWCWebRequest -Times 1 -Exactly - Should -Invoke Write-Warning -Times 0 + Should -Invoke Write-Warning -Times 1 -ParameterFilter { $Message -like '*failed on its first chunk*' } + } + } + + It 'creates nothing with -Directory:$false' { + InModuleScope 'ConnectWiseControlAPI' { + Add-CWCToolboxItem -Name 'Tool.cmd' -Directory:$false -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $err[0].FullyQualifiedErrorId | Should -BeLike 'CWC.NothingToUpload*' + $script:ToolboxCalls.Count | Should -Be 0 } } diff --git a/source/Public/RestApi/Send-CWCToolboxItem.ps1 b/source/Public/RestApi/Send-CWCToolboxItem.ps1 index 1910966..ccd00f2 100644 --- a/source/Public/RestApi/Send-CWCToolboxItem.ps1 +++ b/source/Public/RestApi/Send-CWCToolboxItem.ps1 @@ -97,7 +97,8 @@ function Send-CWCToolboxItem { } # An elevated run is treated as high impact, a standard run is not. The command's impact is Medium, # so lowering the default preference (High) to Medium makes ShouldProcess ask. -Confirm:$false and a - # caller's own $ConfirmPreference arrive here as other values and are left alone. + # session-wide (global) $ConfirmPreference arrive here as other values and are left alone. As with + # every module command, a preference set only in the caller's script scope is not seen: use -Confirm. if (($Silent -or $Elevated) -and $ConfirmPreference -eq 'High') { $ConfirmPreference = 'Medium' } # A prompt that cannot be shown throws: the assignment then never happens and nothing is sent $Proceed = $False diff --git a/source/Public/ToolboxService/Add-CWCToolboxItem.ps1 b/source/Public/ToolboxService/Add-CWCToolboxItem.ps1 index 742e24c..74d3f2d 100644 --- a/source/Public/ToolboxService/Add-CWCToolboxItem.ps1 +++ b/source/Public/ToolboxService/Add-CWCToolboxItem.ps1 @@ -93,6 +93,11 @@ function Add-CWCToolboxItem { $Write = @{ Service = 'ToolboxService'; Method = 'WriteToolboxFileContent' } if ($PSCmdlet.ParameterSetName -eq 'Directory') { + if (-not $Directory) { + # -Directory:$false still selects this parameter set; a folder is not what was asked for + $Message = 'Nothing to do: pass -Path to upload a file, or -Directory to create a folder.' + return Write-Error $Message -ErrorId 'CWC.NothingToUpload' -Category InvalidArgument + } $Folder = Resolve-CWCToolboxPath -Path $Name -Folder if ($Folder -and $PSCmdlet.ShouldProcess($Folder, 'Create Toolbox folder')) { $null = Invoke-CWCServiceMethod @Write -Arguments @($Folder, $True, $False, '') @@ -124,6 +129,7 @@ function Add-CWCToolboxItem { if (-not $Proceed) { return } $Append = $False + $FirstChunkSent = $False $Completed = $False try { $Stream = [System.IO.File]::OpenRead($LocalPath) @@ -140,6 +146,7 @@ function Add-CWCToolboxItem { # -not $Append: an empty file still needs one call to create the item while (($BytesRead = $Stream.Read($Buffer, 0, $Buffer.Length)) -gt 0 -or -not $Append) { $Chunk = @($ItemName, $False, $Append, [Convert]::ToBase64String($Buffer, 0, $BytesRead)) + $FirstChunkSent = $True # -Sensitive keeps the file content out of verbose and debug output $null = Invoke-CWCServiceMethod @Write -Arguments $Chunk -Sensitive -ErrorAction Stop $Append = $True @@ -167,6 +174,11 @@ function Add-CWCToolboxItem { Write-Warning ("Upload of '$ItemName' stopped part way and the incomplete item could not be " + 'deleted. Remove it with Remove-CWCToolboxItem.') } + } elseif ($FirstChunkSent -and -not $Completed) { + # The first chunk got no confirmed answer: the server may have refused it and left an existing + # item alone, or may have written it. Deleting here could destroy an intact item, so only warn. + Write-Warning ("Upload of '$ItemName' failed on its first chunk. If the server wrote that chunk, " + + 'the Toolbox holds an incomplete item of that name: check with Get-CWCToolbox before running it.') } } } From 7d97b840611112b9720263e43ca9e7d578270bb6 Mon Sep 17 00:00:00 2001 From: Chris Taylor Date: Thu, 12 Nov 2026 12:03:34 -0700 Subject: [PATCH 5/5] Toolbox: report a delete the server did not carry out Remove-CWCToolboxItem lists the Toolbox after the delete and returns CWC.ToolboxItemNotRemoved when the item is still there. Seen live: the server answers success and keeps a file it has open. Document that an -Elevated item did not start without a host connected. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 7 ++- Docs/Remove-CWCToolboxItem.md | 4 ++ Docs/Send-CWCToolboxItem.md | 4 ++ Tests/ConnectWiseControlAPI.Public.Tests.ps1 | 44 ++++++++++++++++++- source/Public/RestApi/Send-CWCToolboxItem.ps1 | 3 ++ .../ToolboxService/Remove-CWCToolboxItem.ps1 | 24 +++++++++- source/en-US/ConnectWiseControlAPI-help.xml | 2 + 7 files changed, 84 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 71f5564..da916c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -83,10 +83,13 @@ Details are in the sections below. connections only). Accepts files from the pipeline. It replaces an item of the same name. If the upload fails or is stopped part way, the incomplete item is deleted so it cannot be run - `Remove-CWCToolboxItem` deletes a Toolbox file or folder (`ToolboxService.ProcessToolboxOperation`, Delete); - asks for confirmation by default. Credentials connections only + asks for confirmation by default. Credentials connections only. It checks the Toolbox afterwards and + returns `CWC.ToolboxItemNotRemoved` when the item is still there: the server answers success even when it + could not delete a file it has open - `Send-CWCToolboxItem -Elevated` runs the item with administrative privileges (QueuedElevatedTool 101) and `-Silent` runs it elevated and silently (QueuedSilentElevatedTool 117). Both ask for confirmation unless - `-Confirm:$false` is passed; credentials connections only + `-Confirm:$false` is passed; credentials connections only. Use `-Silent` for unattended runs: an + `-Elevated` item did not start on a machine with no host connected ### Deprecated diff --git a/Docs/Remove-CWCToolboxItem.md b/Docs/Remove-CWCToolboxItem.md index b101fa6..8cb62a7 100644 --- a/Docs/Remove-CWCToolboxItem.md +++ b/Docs/Remove-CWCToolboxItem.md @@ -27,6 +27,10 @@ Items that an extension adds (for example Command Toolbox commands) are refused by the server with "Cannot edit virtual toolbox item". +After the delete the command lists the Toolbox and returns CWC.ToolboxItemNotRemoved when the item, +or something inside a deleted folder, is still there: the server can answer success and leave a file +it has open, for example one that is queued to run. + ## EXAMPLES ### EXAMPLE 1 diff --git a/Docs/Send-CWCToolboxItem.md b/Docs/Send-CWCToolboxItem.md index 5e961d4..b93d7fe 100644 --- a/Docs/Send-CWCToolboxItem.md +++ b/Docs/Send-CWCToolboxItem.md @@ -27,6 +27,10 @@ administrative rights, and with -Silent nobody at the machine sees it. Pass -Confirm:$false in unattended scripts. +For an unattended run use -Silent. +With -Elevated the server queued the event, but the item did not +start on a machine that had no host connected (seen live, 2026-11-12). + The machine opens the item the way Windows opens a file, so use a file type that runs when opened (.exe, .msi, .cmd, .bat): a .ps1 opens in its default program instead of running. diff --git a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 index f15abef..337642d 100644 --- a/Tests/ConnectWiseControlAPI.Public.Tests.ps1 +++ b/Tests/ConnectWiseControlAPI.Public.Tests.ps1 @@ -2869,7 +2869,49 @@ Describe 'Add-CWCToolboxItem' { Describe 'Remove-CWCToolboxItem' { - BeforeEach { Set-CWCTestConnection } + BeforeEach { + Set-CWCTestConnection + # The check after the delete: nothing left + Mock -ModuleName ConnectWiseControlAPI Get-CWCToolbox {} + } + + It 'returns CWC.ToolboxItemNotRemoved when ' -ForEach @( + @{ Case = 'the item is still listed'; Path = 'Scripts/Cleanup.cmd'; Left = 'scripts/cleanup.cmd' } + @{ Case = 'a deleted folder still holds a file'; Path = 'Scripts'; Left = 'Scripts/Open.cmd' } + ) { + InModuleScope 'ConnectWiseControlAPI' -Parameters @{ Path = $Path; Left = $Left } { + param($Path, $Left) + Mock Invoke-CWCWebRequest {} + Mock Get-CWCToolbox { + [PSCustomObject]@{ Path = 'Scripts2/Other.cmd' } + [PSCustomObject]@{ Path = $Left } + } + Remove-CWCToolboxItem -Path $Path -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -Be 1 + $err[0].FullyQualifiedErrorId | Should -BeLike 'CWC.ToolboxItemNotRemoved*' + $err[0].TargetObject | Should -Be $Path + } + } + + It 'does not mistake a neighbour with the same prefix for a leftover' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest {} + Mock Get-CWCToolbox { [PSCustomObject]@{ Path = 'Scripts2/Other.cmd' }; [PSCustomObject]@{ Path = 'Scripts.cmd' } } + Remove-CWCToolboxItem -Path 'Scripts' -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $err.Count | Should -Be 0 + Should -Invoke Get-CWCToolbox -Times 1 + } + } + + It 'does not check the Toolbox when the delete itself fails' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-CWCWebRequest { Write-Error 'HTTP 500' -ErrorId 'CWC.Http500' } + Mock Get-CWCToolbox {} + Remove-CWCToolboxItem -Path 'Cleanup.cmd' -Confirm:$false -ErrorVariable err -ErrorAction SilentlyContinue + $err[0].FullyQualifiedErrorId | Should -BeLike 'CWC.Http500*' + Should -Invoke Get-CWCToolbox -Times 0 + } + } It 'sends the Delete operation (3) with the path and a null originalPath, without retry' { InModuleScope 'ConnectWiseControlAPI' { diff --git a/source/Public/RestApi/Send-CWCToolboxItem.ps1 b/source/Public/RestApi/Send-CWCToolboxItem.ps1 index ccd00f2..187c258 100644 --- a/source/Public/RestApi/Send-CWCToolboxItem.ps1 +++ b/source/Public/RestApi/Send-CWCToolboxItem.ps1 @@ -12,6 +12,9 @@ function Send-CWCToolboxItem { administrative rights, and with -Silent nobody at the machine sees it. Pass -Confirm:$false in unattended scripts. + For an unattended run use -Silent. With -Elevated the server queued the event, but the item did not + start on a machine that had no host connected (seen live, 2026-11-12). + The machine opens the item the way Windows opens a file, so use a file type that runs when opened (.exe, .msi, .cmd, .bat): a .ps1 opens in its default program instead of running. diff --git a/source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 b/source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 index 3fc9d46..3aeee66 100644 --- a/source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 +++ b/source/Public/ToolboxService/Remove-CWCToolboxItem.ps1 @@ -11,6 +11,10 @@ function Remove-CWCToolboxItem { (for example Command Toolbox commands) are refused by the server with "Cannot edit virtual toolbox item". + After the delete the command lists the Toolbox and returns CWC.ToolboxItemNotRemoved when the item, + or something inside a deleted folder, is still there: the server can answer success and leave a file + it has open, for example one that is queued to run. + .PARAMETER Path Path of the item inside the Toolbox, e.g. 'Cleanup.cmd' or 'Scripts/Cleanup.cmd': the Path that Get-CWCToolbox returns. @@ -55,6 +59,24 @@ function Remove-CWCToolboxItem { # ProcessToolboxOperation(ToolboxOperation operation, string path, string originalPath); # originalPath is only used by Move. Never retried. $Delete = @($script:CWCToolboxOperation.Delete, $ItemPath, $null) - $null = Invoke-CWCServiceMethod -Service ToolboxService -Method ProcessToolboxOperation -Arguments $Delete + $DeleteError = $null + $null = Invoke-CWCServiceMethod -Service ToolboxService -Method ProcessToolboxOperation ` + -Arguments $Delete -ErrorVariable DeleteError + if ($DeleteError) { return } + + # The server can answer success and delete nothing or only part of a folder (seen live, 2026-11-12: + # a folder kept a file the server had open after it was queued to run), so the result is checked + $Left = @(Get-CWCToolbox | Where-Object { + $_.Path -eq $ItemPath -or + "$($_.Path)".StartsWith("$ItemPath/", [System.StringComparison]::OrdinalIgnoreCase) + }) + if ($Left.Count -gt 0) { + $Message = @( + "The server reported success, but '$ItemPath' is still in the Toolbox" + "($($Left.Count) item(s) left, for example '$($Left[-1].Path)')." + 'The server cannot delete a file it has open, for example one queued to run. Try again later.' + ) -join ' ' + Write-Error $Message -ErrorId 'CWC.ToolboxItemNotRemoved' -Category ResourceBusy -TargetObject $ItemPath + } } } diff --git a/source/en-US/ConnectWiseControlAPI-help.xml b/source/en-US/ConnectWiseControlAPI-help.xml index 8b5a46f..9795c48 100644 --- a/source/en-US/ConnectWiseControlAPI-help.xml +++ b/source/en-US/ConnectWiseControlAPI-help.xml @@ -4302,6 +4302,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Calls ToolboxService.ProcessToolboxOperation with the Delete operation. The user needs the ManageSharedToolbox permission. Only items stored in the server's Toolbox folder can be deleted. Items that an extension adds (for example Command Toolbox commands) are refused by the server with "Cannot edit virtual toolbox item". + After the delete the command lists the Toolbox and returns CWC.ToolboxItemNotRemoved when the item, or something inside a deleted folder, is still there: the server can answer success and leave a file it has open, for example one that is queued to run. @@ -4720,6 +4721,7 @@ $Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { Queues a QueuedTool session event naming the Toolbox item. -Elevated queues a QueuedElevatedTool event instead, which runs the item with administrative privileges; -Silent queues a QueuedSilentElevatedTool event, which runs it elevated and silently. -Elevated and -Silent ask for confirmation, like the Remove-* commands: the item runs with administrative rights, and with -Silent nobody at the machine sees it. Pass -Confirm:$false in unattended scripts. + For an unattended run use -Silent. With -Elevated the server queued the event, but the item did not start on a machine that had no host connected (seen live, 2026-11-12). The machine opens the item the way Windows opens a file, so use a file type that runs when opened (.exe, .msi, .cmd, .bat): a .ps1 opens in its default program instead of running. Credentials connections: PageService.AddSessionEvents; the user needs the RunSharedTool permission in -Group. API secret connections: the RESTful API Manager extension's SendToolboxItemToSession. The event is attributed to the extension's RESTfulUserName setting ("RESTful API" unless renamed); -Group is ignored. -Elevated and -Silent are not available: the extension only queues the standard event.