diff --git a/.PSScriptAnalyzerSettings.psd1 b/.PSScriptAnalyzerSettings.psd1 new file mode 100644 index 0000000..ad43b15 --- /dev/null +++ b/.PSScriptAnalyzerSettings.psd1 @@ -0,0 +1,141 @@ +@{ + # Severity levels: Error, Warning, Information + Severity = @('Error', 'Warning') + + IncludeRules = @( + # Code Style + 'PSAvoidDefaultValueForMandatoryParameter', + 'PSAvoidDefaultValueSwitchParameter', + 'PSAvoidGlobalVars', + 'PSAvoidUsingCmdletAliases', + 'PSAvoidUsingComputerNameHardcoded', + 'PSAvoidUsingConvertToSecureStringWithPlainText', + 'PSAvoidUsingDeprecatedManifestFields', + 'PSAvoidUsingEmptyCatchBlock', + 'PSAvoidUsingInvokeExpression', + 'PSAvoidUsingPlainTextForPassword', + 'PSAvoidUsingPositionalParameters', + 'PSAvoidUsingUsernameAndPasswordParams', + 'PSAvoidUsingWMICmdlet', + 'PSAvoidUsingWriteHost', + + # Best Practices + 'PSAlignAssignmentStatement', + 'PSAvoidAssignmentToAutomaticVariable', + 'PSAvoidLongLines', + 'PSAvoidOverwritingBuiltInCmdlets', + 'PSAvoidShouldContinueWithoutForce', + 'PSAvoidTrailingWhitespace', + 'PSAvoidUsingBrokenHashAlgorithms', + 'PSAvoidUsingDoubleQuotesForConstantString', + + # Functions + 'PSAvoidMultipleTypeAttributes', + 'PSMisleadingBacktick', + 'PSMissingModuleManifestField', + 'PSPlaceCloseBrace', + 'PSPlaceOpenBrace', + 'PSProvideCommentHelp', + 'PSReservedCmdletChar', + 'PSReservedParams', + 'PSReviewUnusedParameter', + 'PSShouldProcess', + 'PSUseApprovedVerbs', + 'PSUseBOMForUnicodeEncodedFile', + 'PSUseCmdletCorrectly', + 'PSUseCompatibleCmdlets', + 'PSUseCompatibleSyntax', + 'PSUseCompatibleTypes', + 'PSUseConsistentIndentation', + 'PSUseConsistentWhitespace', + 'PSUseCorrectCasing', + 'PSUseDeclaredVarsMoreThanAssignments', + 'PSUseLiteralInitializerForHashtable', + 'PSUseOutputTypeCorrectly', + 'PSUsePSCredentialType', + 'PSUseProcessBlockForPipelineCommand', + 'PSUseShouldProcessForStateChangingFunctions', + 'PSUseSingularNouns', + 'PSUseSupportsShouldProcess', + 'PSUseToExportFieldsInManifest', + 'PSUseUTF8EncodingForHelpFile', + 'PSUseUsingScopeModifierInNewRunspaces' + ) + + Rules = @{ + PSPlaceOpenBrace = @{ + Enable = $true + OnSameLine = $true + NewLineAfter = $true + IgnoreOneLineBlock = $true + } + + PSPlaceCloseBrace = @{ + Enable = $true + NewLineAfter = $false + IgnoreOneLineBlock = $true + NoEmptyLineBefore = $false + } + + PSUseConsistentIndentation = @{ + Enable = $true + Kind = 'space' + PipelineIndentation = 'IncreaseIndentationForFirstPipeline' + IndentationSize = 4 + } + + PSUseConsistentWhitespace = @{ + Enable = $true + CheckInnerBrace = $true + CheckOpenBrace = $true + CheckOpenParen = $true + CheckOperator = $true + CheckPipe = $true + CheckPipeForRedundantWhitespace = $false + CheckSeparator = $true + CheckParameter = $false + # Let PSAlignAssignmentStatement own hashtable alignment (otherwise aligned '=' is flagged here) + IgnoreAssignmentOperatorInsideHashTable = $true + } + + PSAlignAssignmentStatement = @{ + Enable = $true + CheckHashtable = $true + } + + PSUseCorrectCasing = @{ + Enable = $true + } + + PSAvoidLongLines = @{ + Enable = $true + MaximumLineLength = 120 + } + + # The module manifest says PowerShell 3.0 and MSPs run it on Windows PowerShell 5.1 (RMM agents). + # Build and test tooling runs on PowerShell 7, but the module itself must stay 3.0/5.1-compatible. + PSUseCompatibleSyntax = @{ + Enable = $true + TargetVersions = @( + '3.0', + '5.1', + '7.6' + ) + } + + # PSUseCompatibleCommands is disabled because the PSSA compatibility + # profile catalog is often outdated. + # PSUseCompatibleCommands = @{ + # Enable = $true + # TargetProfiles = @() + # } + + PSProvideCommentHelp = @{ + Enable = $true + ExportedOnly = $true + BlockComment = $true + VSCodeSnippetCorrection = $false + Placement = 'before' + } + } +} diff --git a/.build/required-modules.ps1 b/.build/required-modules.ps1 new file mode 100644 index 0000000..c96e4ca --- /dev/null +++ b/.build/required-modules.ps1 @@ -0,0 +1,84 @@ +# Custom build task: verifies resolved build dependencies (loaded automatically by +# build.ps1 from the .build/ folder). +# +# Resolve-Dependency.ps1 only WARNS when Save-PSResource fails, and GitHub runners ship +# their own Pester/PSScriptAnalyzer. Without this check a bad or unavailable pin leaves +# the build silently running on whatever version the machine happens to have. + +function Test-VersionInRange { + <# + .SYNOPSIS + Tests a version against a NuGet-style range ('[1.0,2.0)'), an exact version, or 'latest'. + #> + param( + [Parameter(Mandatory)][version]$Version, + [Parameter(Mandatory)][string]$Range + ) + + if ($Range -eq 'latest') { return $true } + + if ($Range -match '^\s*([\[\(])\s*([^,]*?)\s*,\s*([^\]\)]*?)\s*([\]\)])\s*$') { + $minInclusive = $Matches[1] -eq '[' + $maxInclusive = $Matches[4] -eq ']' + $min = if ($Matches[2]) { [version]$Matches[2] } else { $null } + $max = if ($Matches[3]) { [version]$Matches[3] } else { $null } + + if ($min -and ($(if ($minInclusive) { $Version -lt $min } else { $Version -le $min }))) { return $false } + if ($max -and ($(if ($maxInclusive) { $Version -gt $max } else { $Version -ge $max }))) { return $false } + return $true + } + + # Exact version ('5.6.1' or '[5.6.1]') + return $Version -eq [version]($Range.Trim('[', ']', ' ')) +} + +# Synopsis: Fails if a required module is missing, has more than one version, or is outside its pinned range. +task Assert_RequiredModule_Versions { + $requiredModulesFile = Join-Path -Path $BuildRoot -ChildPath 'RequiredModules.psd1' + $requiredModulesDir = if ($RequiredModulesDirectory) { $RequiredModulesDirectory } else { Join-Path 'output' 'RequiredModules' } + $requiredModulesPath = Get-SamplerAbsolutePath -Path $requiredModulesDir -RelativeTo $BuildRoot + + if (-not (Test-Path -Path $requiredModulesPath)) { + throw "Required modules folder '$requiredModulesPath' not found. Run './build.ps1 -ResolveDependency -Tasks noop'." + } + + $requirements = Import-PowerShellDataFile -Path $requiredModulesFile + $problems = [System.Collections.Generic.List[string]]::new() + + foreach ($name in ($requirements.Keys | Where-Object { $_ -ne 'PSDependOptions' } | Sort-Object)) { + $spec = $requirements[$name] + $range = if ($spec -is [hashtable]) { "$($spec.Version)" } else { "$spec" } + if (-not $range) { $range = 'latest' } + + $moduleFolder = Get-ChildItem -Path $requiredModulesPath -Directory | + Where-Object Name -EQ $name | + Select-Object -First 1 + if (-not $moduleFolder) { + $problems.Add("${name}: not found in $requiredModulesPath") + continue + } + + $versions = @(Get-ChildItem -Path $moduleFolder.FullName -Directory | + Where-Object { $_.Name -as [version] } | + ForEach-Object { [version]$_.Name }) + + if ($versions.Count -ne 1) { + $problems.Add("${name}: expected exactly one version, found $($versions.Count) ($($versions -join ', '))") + continue + } + + if (-not (Test-VersionInRange -Version $versions[0] -Range $range)) { + $problems.Add("${name}: version $($versions[0]) is outside the required range '$range'") + continue + } + + Write-Build Green (" {0,-22} {1,-12} (required: {2})" -f $name, $versions[0], $range) + } + + if ($problems.Count -gt 0) { + $problems | ForEach-Object { Write-Build Red " $_" } + throw ('Required module check failed. Delete output/RequiredModules and run ' + + "'./build.ps1 -ResolveDependency -Tasks noop' from a NEW PowerShell session.") + } + # (The template's Pester pre-load is omitted: this repo runs Pester through Tests/test-local.ps1, not Sampler.) +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..b765df0 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,52 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# Top-most EditorConfig file +root = true + +# Default settings for all files +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +# Markdown files +[*.md] +# Markdown uses trailing spaces for line breaks +trim_trailing_whitespace = false +max_line_length = off + +# YAML files (GitHub workflows, config files) +[*.{yml,yaml}] +indent_size = 2 + +# JSON files +[*.json] +indent_size = 2 + +# XML files (MAML help, config) +[*.xml] +indent_size = 2 + +# PowerShell files +[*.{ps1,psm1,psd1}] +# EditorConfig does not allow inline comments after values. +# PowerShell prefers UTF-8 with BOM (Windows PowerShell reads BOM-less files as ANSI) +charset = utf-8-bom +indent_size = 4 +# Windows line endings for PowerShell +end_of_line = crlf + +# Batch files (Windows) +[*.{bat,cmd}] +end_of_line = crlf + +# Documentation files +[*.{txt,rst}] +max_line_length = off + +# License and changelog files +[{LICENSE,CHANGELOG,CONTRIBUTING,CODE_OF_CONDUCT,SECURITY}] +max_line_length = off diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..19e0f9b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,94 @@ +# Git Attributes Configuration +# https://git-scm.com/docs/gitattributes + +# Set default behavior to automatically normalize line endings +* text=auto + +############################### +# Text Files (Auto-normalize) # +############################### + +# PowerShell +*.ps1 text eol=crlf diff=powershell +*.psm1 text eol=crlf diff=powershell +*.psd1 text eol=crlf +*.ps1xml text eol=crlf +*.pssc text eol=crlf +*.psrc text eol=crlf +*.cdxml text eol=crlf + +# Scripts +*.bash text eol=lf +*.sh text eol=lf +*.bat text eol=crlf +*.cmd text eol=crlf + +# Documentation +*.md text diff=markdown +*.txt text + +# Config files +*.json text +*.yaml text +*.yml text +*.xml text +.editorconfig text +.gitattributes text +.gitconfig text +.gitignore text + +# Special files +AUTHORS text +CHANGELOG text +CONTRIBUTING text +LICENSE text +README text + +############################### +# Binary Files # +############################### + +# Graphics +*.gif binary +*.ico binary +*.jpg binary +*.jpeg binary +*.png binary +*.webp binary +*.svg text + +# Archives +*.7z binary +*.gz binary +*.tar binary +*.zip binary + +# Executables +*.exe binary +*.dll binary + +#################### +# Merge Strategies # +#################### + +# For changelog files, prefer union merge +CHANGELOG* merge=union + +#################### +# Linguist # +#################### + +# Documentation +Docs/** linguist-documentation +*.md linguist-documentation + +#################### +# Export Ignore # +#################### +# Files to exclude from export archives (git archive) + +.gitattributes export-ignore +.gitignore export-ignore +.editorconfig export-ignore +.github export-ignore +Tests export-ignore diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..0473ac6 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,101 @@ +# Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community +* Using welcoming and inclusive language +* Being patient with newcomers and those learning +* Recognizing and respecting different skill levels and contributions + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Spamming, excessive self-promotion, or off-topic posts +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +This includes: + +- GitHub repositories (issues, pull requests, discussions, code reviews) +- Community Slack channels +- Project-related social media +- Community events and meetups +- Email communications + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at: + +- **Email:** conduct@christaylor.codes +- **Slack:** @CTaylor on [MSPGeek Slack](https://join.mspgeek.com/) +- **GitHub:** Open a confidential issue via the Security Advisory feature + +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact:** Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence:** A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact:** A violation through a single incident or series of actions. + +**Consequence:** A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact:** A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence:** A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact:** Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence:** A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..507d304 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,130 @@ +# Contributing to ConnectWiseControlAPI + +:+1::tada: First off, thanks for taking the time to contribute! :tada::+1: + +The following is a set of guidelines for contributing. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document, or anything else in a pull request. + +## Table Of Contents + +[I don't want to read this whole thing, I just have a question!!!](#i-don't-want-to-read-this-whole-thing-i-just-have-a-question) + +[How Can I Contribute?](#how-can-i-contribute) + +- [Reporting Bugs](#reporting-bugs) +- [Suggesting Enhancements](#suggesting-enhancements) +- [Your First Code Contribution](#your-first-code-contribution) +- [Pull Requests](#pull-requests) + +[AI Contributors](#ai-contributors) + +[Styleguides](#styleguides) + +- [Git Commit Messages](#git-commit-messages) +- [Powershell Styleguide](#powershell-styleguide) +- [Documentation Styleguide](#documentation-styleguide) + +## I don't want to read this whole thing I just have a question + +> **Note:** *Please don't file an issue to ask a question.* You'll get faster results by using the resources below. + +Join a community Slack team: + +- [Join the MSPGeek Slack Team](https://join.mspgeek.com/) +- [Join the PowerShell Slack Team](https://powershell.slack.com/join/shared_invite/zt-eodd93as-RHYl6s~9XH8FNyE09M7zmA#/) + + - Even though Slack is a chat service, sometimes it takes several hours for community members to respond — please be patient! + - Use a channel that looks appropriate for general questions or discussion + - There are many other channels available, check the channel list + - Send me a DM if you want, @CTaylor + +## How Can I Contribute + +### Reporting Bugs + +This section guides you through submitting a bug report. Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behavior :computer: :computer:, and find related reports :mag_right:. + +Before creating bug reports, please check existing issues as you might find out that you don't need to create one. When you are creating a bug report, please include as many details as possible. Fill out template, the information it asks for helps us resolve issues faster. + +> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one. + +#### Before Submitting A Bug Report + +- **Check the Wiki.** You might be able to find the cause of the problem and fix things yourself. +- **Check the [MSPGeek Slack Team](https://join.mspgeek.com/)** for help from the community. + +#### How Do I Submit A (Good) Bug Report + +Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined which repository your bug is related to, create an issue on that repository and provide the following information by filling in the template. + +Explain the problem and include additional details to help maintainers reproduce the problem: + +- **Use a clear and descriptive title** for the issue to identify the problem. +- **Describe the exact steps which reproduce the problem** in as many details as possible. +- **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). +- **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior. +- **Explain which behavior you expected to see instead and why.** + +Provide more context by answering these questions: + +- **Did the problem start happening recently** (e.g. after updating to a new version) or was this always a problem? +- **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens. + +### Suggesting Enhancements + +This section guides you through submitting an enhancement suggestion, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion :pencil: and find related suggestions :mag_right:. + +Before creating enhancement suggestions, please check existing suggestions as you might find out that you don't need to create one. When you are creating an enhancement suggestion, please include as many details as possible. Fill in the template, including the steps that you imagine you would take if the feature you're requesting existed. + +#### How Do I Submit A (Good) Enhancement Suggestion + +Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). Create an issue and provide the following information: + +- **Use a clear and descriptive title** for the issue to identify the suggestion. +- **Provide a step-by-step description of the suggested enhancement** in as many details as possible. +- **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). +- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. +- **Explain why this enhancement would be useful** to most users and isn't something that can or should be implemented as a [community package](<>). +- **List some other text examples where this enhancement exists.** +- **Specify which version of the module you're using.** +- **Specify the name and version of the OS you're using.** + +## AI Contributors + +This project welcomes contributions from AI coding agents. AI agents follow the same quality standards as human contributors. See [CLAUDE.md](../CLAUDE.md) for development instructions and conventions. + +## Styleguides + +### Git Commit Messages + +- Use the present tense ("Add feature" not "Added feature") + +- Use the imperative mood ("Move cursor to..." not "Moves cursor to...") + +- Limit the first line to 72 characters or less + +- Reference issues and pull requests liberally after the first line + +- When only changing documentation, include `[ci skip]` in the commit title + +- Consider starting the commit message with an applicable emoji: + - :art: `:art:` when improving the format/structure of the code + - :racehorse: `:racehorse:` when improving performance + - :non-potable_water: `:non-potable_water:` when plugging memory leaks + - :memo: `:memo:` when writing docs + - :checkered_flag: `:checkered_flag:` when fixing something on Windows + - :bug: `:bug:` when fixing a bug + - :fire: `:fire:` when removing code or files + - :green_heart: `:green_heart:` when fixing the CI build + - :white_check_mark: `:white_check_mark:` when adding tests + - :lock: `:lock:` when dealing with security + - :arrow_up: `:arrow_up:` when upgrading dependencies + - :arrow_down: `:arrow_down:` when downgrading dependencies + - :shirt: `:shirt:` when removing linter warnings + +### PowerShell Styleguide + +- Refer to the [unofficial guide](https://github.com/PoshCode/PowerShellPracticeAndStyle). + +### Documentation Styleguide + +- Documentation is built with [platyPS](https://github.com/PowerShell/platyPS). diff --git a/.github/ISSUE_TEMPLATE/ai_task.md b/.github/ISSUE_TEMPLATE/ai_task.md new file mode 100644 index 0000000..546db32 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/ai_task.md @@ -0,0 +1,58 @@ +--- +name: AI Task +about: Create a structured task for AI coding agents +title: '[AI] ' +labels: 'ai-task, ai-ready' +assignees: '' +--- + +## Objective + + + +## Context + + + + +## Requirements + + + +- [ ] +- [ ] +- [ ] + +## Acceptance Criteria + + + +- [ ] All existing tests pass (`Invoke-Pester`) +- [ ] PSScriptAnalyzer reports zero errors +- [ ] New/changed functionality has test coverage +- [ ] + +## Files to Modify + + + + +- +- + +## Out of Scope + + + +- + +## Technical Notes + + + + +## Related Issues + + + +- Related to # diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..a91ab71 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,54 @@ +--- +name: Bug Report +about: Create a report to help us improve +title: '[BUG] ' +labels: 'bug' +assignees: '' +--- + +## Bug Description + + + +## Steps to Reproduce + + + +1. +2. +3. +4. + +## Expected Behavior + + + +## Actual Behavior + + + +## Screenshots + + + +## Environment + + + +- **OS**: [e.g., Windows 11, Windows Server 2022] +- **Module Version**: [e.g., 0.3.5.0] +- **PowerShell Version**: [e.g., 5.1, 7.4.0] +- **ScreenConnect Server Version**: [e.g., 24.1] + +## Additional Context + + + +## Possible Solution + + + +## Checklist + +- [ ] I have searched existing issues to ensure this is not a duplicate +- [ ] I have tested with the latest version diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..1e97046 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: true +contact_links: + - name: Community Support + url: https://join.mspgeek.com/ + about: Ask questions and discuss with the MSPGeek community on Slack + - name: Documentation + url: https://github.com/christaylorcodes/ConnectWiseControlAPI/blob/master/README.md + about: Check out our documentation + - name: Contributing Guide + url: https://github.com/christaylorcodes/ConnectWiseControlAPI/blob/master/.github/CONTRIBUTING.md + about: Learn how to contribute to this project diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..21426fd --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,52 @@ +--- +name: Feature Request +about: Suggest an idea for this project +title: '[FEATURE] ' +labels: 'enhancement' +assignees: '' +--- + +## Feature Description + + + +## Problem Statement + + + + +## Proposed Solution + + + +## Alternative Solutions + + + +## Use Cases + + + +1. +2. +3. + +## Benefits + + + +- +- +- + +## Additional Context + + + +## Would you be willing to contribute this feature? + + + +- [ ] Yes, I'd like to contribute +- [ ] No, but I'm happy to help test +- [ ] No, but I can provide more details diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..82ddb5d --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,50 @@ +# Pull Request + +## Description + + + +## Related Issue + + + +## Type of Change + +- [ ] Bug fix +- [ ] New feature +- [ ] Breaking change +- [ ] Documentation +- [ ] Refactoring / tests + +## Changes Made + + + +- +- + +## Testing + + + +- [ ] `./Tests/test-local.ps1` passes (analyzer, manifest, Pester on PS 7 and 5.1, docs drift) +- [ ] Tested against a live ScreenConnect server (if applicable) + +## Checklist + +- [ ] Code follows project conventions ([AGENTS.md](../AGENTS.md)) +- [ ] Tests cover new/changed behavior +- [ ] PSScriptAnalyzer reports zero errors +- [ ] CHANGELOG.md updated (if applicable) +- [ ] Documentation updated (if applicable) +- [ ] New public function is in `source/Public/` (the build exports it; no manifest edit) and has comment-based help + +## Screenshots + + + +## AI Contribution + + + +- [ ] AI-assisted (tool: ___, issue: #___) diff --git a/.github/PowerShell-StyleGuide.md b/.github/PowerShell-StyleGuide.md new file mode 100644 index 0000000..2873343 --- /dev/null +++ b/.github/PowerShell-StyleGuide.md @@ -0,0 +1,600 @@ +# PowerShell Style Guide + +> **ConnectWiseControlAPI exception:** this module runs from RMM agents, so it targets PowerShell 3.0+ +> and must work on Windows PowerShell 5.1 (no ternary, `??`, `&&`/`||` or other 7-only syntax). Only the +> build and test tooling needs PowerShell 7. This repo uses the Sampler/ModuleBuilder build and `source/` +> layout, but **not** Pester 6, the Sampler test task or PlatyPS 1.x / `docs/help` (it uses Pester 5.7 through +> `Tests/test-local.ps1` and `Build/Update-Help.ps1`), and test runners must not set a global +> `$ErrorActionPreference = 'Stop'` (it breaks the module's error-path tests). Where this guide disagrees, follow +> [AGENTS.md](../AGENTS.md); everything else applies as written. + +This is the authoritative style guide for all PowerShell projects. It applies to both formal modules (built with Sampler/ModuleBuilder, using InvokeBuild as the task runner) and standalone script collections. All projects should reference this file rather than duplicating conventions. + +## Language Targets + +| Context | Version | Rationale | +|---|---|---| +| PowerShell modules | 7.6+ | Current LTS (7.4 LTS and 7.5 reached end of support 2026-11-10) | +| Scripts deployed to managed endpoints | 5.1+ | Windows ships with 5.1; can't guarantee 7.x on all endpoints | +| CI/CD pipelines | 7.6+ | Controlled environment, use latest stable | + +When writing a module, do not add 5.1 compatibility unless the module explicitly targets Windows PowerShell. When writing endpoint scripts, avoid 7.x-only syntax (ternary `?:`, null-coalescing `??`, pipeline chain `&&`/`||`). + +## Formatting Rules + +Formatting is enforced by PSScriptAnalyzer. The settings file (`.PSScriptAnalyzerSettings.psd1`) is the source of truth. Key decisions: + +- **4-space indentation**, spaces only, no tabs +- **120-character max line length** +- **Open braces on same line**: `if ($true) {` +- **Single quotes for constants**, double quotes only when interpolation is needed +- **Align hashtable assignment operators** for readability +- **UTF-8 with BOM** for `.ps1`/`.psm1`/`.psd1` files, CRLF line endings +- **No trailing whitespace** except in Markdown (where trailing spaces create line breaks) + +### Why Single Quotes + +Double-quoted strings invoke the parser's variable expansion. Using them for constants creates a subtle injection surface and makes intent ambiguous: + +```powershell +# Correct +$path = 'C:\Windows\System32' +$message = "Processing $itemCount items" + +# Wrong +$path = "C:\Windows\System32" # No interpolation needed +$message = 'Processing ' + $count # Awkward concatenation when interpolation is cleaner +``` + +## Naming Conventions + +### Functions + +- Use **approved verbs** only (`Get-Verb` for the full list) +- **PascalCase** with `Verb-Noun` format: `Get-BackupStatus`, `New-ClientReport` +- **Singular nouns**: `Get-User` not `Get-Users` (the function can return multiple objects) +- Private helper functions still use `Verb-Noun` but are not exported + +### Parameters + +- **PascalCase**: `$ComputerName`, `$OutputPath` +- **No abbreviations** unless universally understood: `$Id` is fine, `$Comp` is not +- **Use standard parameter names** when applicable: `$ComputerName` not `$Server`, `$Path` not `$FilePath`, `$Credential` not `$Creds` + +### Variables + +- **PascalCase** for all variables: `$ResultList`, `$ErrorCount` +- **Descriptive names**: `$activeClients` not `$ac` +- **Collections should indicate plurality**: `$tickets`, `$computerNames` + +### Files + +- **One function per file** in modules, filename matches function name: `Get-BackupStatus.ps1` +- **Hyphen-separated** for standalone scripts: `Gather-BrightGauge-Data.ps1` +- **Vendor prefixes** for vendor-specific scripts: `CWM-CloseStaleTickets.ps1` + +## Function Structure + +### Module Functions (Public) + +Use `begin`/`process`/`end` blocks when the function accepts pipeline input. Skip them for functions that don't: + +```powershell +# Pipeline-capable function: use begin/process/end +function Get-ServiceStatus { + [CmdletBinding()] + [OutputType([PSCustomObject])] + param( + [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] + [string]$ComputerName + ) + + begin { + Write-Verbose -Message "Starting $($MyInvocation.MyCommand)" + $results = [System.Collections.Generic.List[PSCustomObject]]::new() + } + + process { + # Per-item logic + } + + end { + return $results + } +} +``` + +```powershell +# Non-pipeline function: flat structure is fine +function Connect-MyService { + [CmdletBinding()] + [OutputType([void])] + param( + [Parameter(Mandatory)] + [PSCredential]$Credential + ) + + Write-Verbose -Message "Connecting to service" + # Connection logic +} +``` + +### Standalone Scripts + +Use the region-based structure with declarations, initializations, functions, and execution: + +```powershell +[CmdletBinding()] +param() + +#region [Declarations] +$ErrorActionPreference = 'Stop' +[version]$ScriptVersion = '1.0.0' +#endregion + +#region [Initializations] +[System.Net.ServicePointManager]::SecurityProtocol = 3072 +# Module loading, logging setup +#endregion + +#region [Functions] +# Local function definitions +#endregion + +#region [Execution] +try { + # Main logic +} catch { + # Error handling +} +finally { + # Cleanup +} +#endregion +``` + +## Comment-Based Help + +Required on all exported functions. Place the help block **inside** the function, at the top of the body before `[CmdletBinding()]` (this is what `Templates/Function.ps1` and `Scripts/New-Function.ps1` generate): + +```powershell +function Get-BackupStatus { + <# + .SYNOPSIS + One line. What it does, not how. + + .DESCRIPTION + More detail. When you'd use it, what it connects to, important caveats. + + .PARAMETER ComputerName + What it accepts and any constraints. + + .INPUTS + System.String. The .NET type accepted from the pipeline. + + .OUTPUTS + PSCustomObject. What the function returns. + + .EXAMPLE + Get-BackupStatus -ComputerName 'SERVER01' + + Returns backup status for SERVER01. + + .NOTES + Version: 1.0.0 + Author: Your Name + Creation Date: YYYY-MM-DD + Purpose/Change: Initial development + #> + [CmdletBinding()] + param(...) +} +``` + +For standalone scripts, the help block goes at the top of the file before `[CmdletBinding()]`. + +Private functions: `.SYNOPSIS`, `.PARAMETER`, and one `.EXAMPLE` are sufficient. Skip `.INPUTS`/`.OUTPUTS`/`.LINK`. + +### Documentation Generation (PlatyPS) + +Comment-based help is the **source of truth** for all documentation. `Get-Help` reads it directly from the built module, so no MAML/XML help is generated. For reference docs (GitHub, a docs site), the build generates markdown from it with Microsoft.PowerShell.PlatyPS 1.x: + +```powershell +./build.ps1 -Tasks docs # Build, then regenerate docs/help//*.md from comment-based help +``` + +**Flow:** `.ps1` comment-based help → built module → PlatyPS (`Scripts/Update-MarkdownHelp.ps1`) → `docs/help//`. The folder is regenerated from scratch on every run and each file is validated with `Test-MarkdownCommandHelp`. Do not hand-edit the generated markdown: update the comment-based help and regenerate. The task lists any remaining `{{ ... }}` placeholders, which point at gaps in your comment-based help. + +### Known Parser Pitfall: Dot at Start of Line + +PowerShell's comment-based help parser treats any line beginning with a dot followed by a word (`.SYNOPSIS`, `.PARAMETER`, etc.) as a **help keyword**. This means terms like `.NET`, `.config`, or `.exe` at the start of a line — even a continuation line — will silently break the entire help block. `Get-Help` will return empty descriptions for all parameters with no error or warning. + +```powershell +# BAD — .NET starts a line, parsed as unknown keyword, breaks all help +<# +.DESCRIPTION + The function handles prerequisite checks including + .NET Framework 3.5 validation and MSI integrity. +#> + +# GOOD — .NET appears mid-line +<# +.DESCRIPTION + The function handles prerequisite checks including validation + of .NET Framework 3.5 and MSI integrity. +#> +``` + +This applies to any dot-word combination: `.NET`, `.config`, `.exe`, `.dll`, `.json`, etc. Always ensure these terms appear in the middle of a line, never at the start (after indentation). + +## Error Handling + +### Standard Pattern + +```powershell +$ErrorActionPreference = 'Stop' + +try { + $result = Get-Something -Id $Id +} catch [System.Net.WebException] { + # Typed catch for expected failures: add context, keep the original as InnerException + $errorRecord = [System.Management.Automation.ErrorRecord]::new( + [System.Exception]::new("Network error retrieving ID $Id", $_.Exception), + 'GetSomethingNetworkError', + [System.Management.Automation.ErrorCategory]::ConnectionError, + $Id + ) + $PSCmdlet.ThrowTerminatingError($errorRecord) +} catch { + # General catch for unexpected failures: re-throw attributed to this function + $PSCmdlet.ThrowTerminatingError($_) +} +``` + +### Rules + +- Always set `$ErrorActionPreference = 'Stop'` at the script level, or use `-ErrorAction Stop` on individual cmdlets +- **Catch specific exception types** when you can handle them differently +- **Include context** in error messages: what you were trying to do, which item failed +- **Re-throw** (`throw` with no arguments) unless you genuinely handle the error +- **Never use empty catch blocks** (PSSA enforces this) +- In advanced functions, propagate with `$PSCmdlet.ThrowTerminatingError()` so the error is attributed to the function, not a line inside it +- **Never** write `Write-Error -Message '...' -ErrorRecord $_`: `-Message` and `-ErrorRecord` are in different parameter sets, so the call fails to bind and hides the real error + +### What NOT To Do + +```powershell +# Don't silently swallow errors +catch { } + +# Don't lose the original error record +catch { Write-Error $_.Exception.Message } # Loses stack trace + +# Don't use return codes for error signaling in modules +catch { return -1 } +``` + +## Logging + +### In Modules + +Use `Write-Verbose` and `Write-Debug`. Never use `Write-Host` in module code. The caller controls verbosity via `-Verbose` and `-Debug` switches. + +```powershell +Write-Verbose -Message "Processing item: $ItemName" +Write-Debug -Message "Raw API response: $($response | ConvertTo-Json -Depth 3)" +``` + +### In Standalone Scripts + +**Prefer Windows Event Log** for most scripts. It is built into the OS, requires zero module dependencies, integrates with existing monitoring tools (Event Viewer, SIEM, RMM platforms), and survives script crashes (writes are immediate, no flush needed). + +#### Windows Event Log (Default -- Preferred) + +Use for any script that runs on Windows endpoints, scheduled tasks, or RMM-deployed automation: + +```powershell +#region [Initializations] +$LogSource = 'MyCompany-Automation' +$LogName = 'Application' + +# Register the source if it doesn't exist (requires elevation, run once per machine) +if (-not [System.Diagnostics.EventLog]::SourceExists($LogSource)) { + New-EventLog -LogName $LogName -Source $LogSource +} +#endregion + +# Usage +Write-EventLog -LogName $LogName -Source $LogSource -EntryType Information -EventId 1000 -Message 'Script started' +Write-EventLog -LogName $LogName -Source $LogSource -EntryType Warning -EventId 2000 -Message 'Retry attempt 2 of 3' +Write-EventLog -LogName $LogName -Source $LogSource -EntryType Error -EventId 3000 -Message "Fatal: $($_.Exception.Message)" +``` + +**Event ID conventions:** + +- `1000-1999` -- Informational (script start, milestones, completion) +- `2000-2999` -- Warnings (retries, degraded state, skipped items) +- `3000-3999` -- Errors (failures, exceptions, abort conditions) + +**Benefits over file-based logging:** + +- Zero dependencies (no modules to install or update) +- Survives script crashes (no buffered writes to flush) +- Queryable by monitoring tools, SIEM, and RMM platforms out of the box +- Built-in rotation and retention managed by Windows +- Centralized when forwarded via Windows Event Forwarding or log collectors + +#### PSFramework (When You Need More) + +Use PSFramework when you specifically need structured logging with tags/data objects, CMTrace-formatted files for SCCM-style log viewers, multi-provider output (simultaneous file + console + Teams), or cross-platform support on PS 7+ Linux hosts: + +```powershell +$Modules = @('PSFramework') +# [Module auto-installation] + +$LogPath = "$env:windir\LTSvc\logs" +$ScriptName = [System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name) +$LogFile = Join-Path $LogPath "$ScriptName-%Date%.log" + +Set-PSFLoggingProvider -Name logfile -InstanceName $ScriptName -FilePath $LogFile -Enabled $true -FileType CMTrace +Set-PSFLoggingProvider -Name console -Enabled $true + +# Usage +Write-PSFMessage -Level Host -Message 'Starting processing' +Write-PSFMessage -Level Warning -Message 'Retrying' -Tag 'API', 'Retry' -Data @{ Attempt = 2 } +Write-PSFMessage -Level Error -Message 'Fatal error' -ErrorRecord $_ + +# ALWAYS call before script exit +Wait-PSFMessage +``` + +#### Legacy Patterns + +`Logging` module: maintain in existing scripts, do not introduce into new code. Migrate to Event Log or PSFramework when refactoring. + +## Preferred Modules and Approaches + +| Need | Use | Don't Use | +|---|---|---| +| Logging (scripts) | Windows Event Log (default), `PSFramework` (advanced) | `Logging` module (unmaintained since 2022) | +| Azure AD / Entra | `Microsoft.Graph` | `MSOnline`, `AzureAD` (deprecated) | +| Exchange Online | `ExchangeOnlineManagement` v3+ | Basic auth / remote PSSession | +| Credential storage | Azure Key Vault, `SecretManagement` | Hardcoded strings, plain-text files | +| REST API calls | `Invoke-RestMethod` | `Invoke-WebRequest` (unless you need response headers) | +| JSON handling | `ConvertTo-Json`/`ConvertFrom-Json` | Manual string building | +| Collections (building lists) | `[System.Collections.Generic.List[T]]` | `+=` on arrays (O(n) reallocation) | +| Null checking (PS 7+) | `$x ?? 'default'` | `if ($null -eq $x) { 'default' }` | +| String building | `-f` operator or interpolation | Repeated `+` concatenation | +| File paths | `Join-Path` | String concatenation with `\` | + +## Security Requirements + +- **TLS 1.2 minimum**: `[System.Net.ServicePointManager]::SecurityProtocol = 3072` +- **Never hardcode credentials** or API keys in source files +- **Use `[PSCredential]`** for credential parameters, never separate username/password parameters +- **Validate all external input** (parameters, API responses, file content) +- **Avoid `Invoke-Expression`** (PSSA enforces this) -- if loading remote scripts is unavoidable, pin to a specific commit hash +- **SSL certificate bypass** (`TrustAllCertsPolicy`) is only acceptable for internal tooling against known endpoints, never in production/public code + +## Output Conventions + +- Return **typed objects** (`[PSCustomObject]` with named properties), not formatted strings +- Use `[OutputType()]` attribute on all functions +- Add `PSTypeName` to custom objects for format/type system integration: + ```powershell + [PSCustomObject]@{ + PSTypeName = 'ModuleName.BackupStatus' + Name = $job.Name + Status = $job.LastResult + } + ``` +- For progress on long operations, use `Write-Progress` (scripts) or `Write-Verbose` (modules) +- Functions should output objects to the pipeline, not store them and return at the end, unless ordering/aggregation requires it + +## Testing Standards + +Tests are not optional. They are how code proves it works, how regressions get caught, and how AI agents get the feedback they need to iterate without human intervention. Code that cannot be tested cannot be trusted. + +### Requirements + +- **Every exported function must have a matching test file** +- **Pester 6** with configuration-based invocation +- **PSScriptAnalyzer** runs as part of every test cycle (`-IncludeAnalyzer`), zero errors required +- Test structure per function: `Parameter Validation` > `Functionality` > `Error Handling` > `Edge Cases` + +### Design for Testability + +Write code that is easy to test. If something is hard to test, that is a design problem, not a testing problem. + +**Keep functions small and single-purpose.** A function that connects to an API, transforms data, and writes output is three functions. Split them so each can be tested in isolation: + +```powershell +# Hard to test: does everything, requires live API +function Sync-UserData { + $users = Invoke-RestMethod -Uri $apiUrl # Network call + $mapped = $users | ForEach-Object { ... } # Transformation + $mapped | Export-Csv -Path $outputPath # File I/O +} + +# Easy to test: each piece is independently verifiable +function Get-RemoteUserData { # Mock the API call + [CmdletBinding()] + param([string]$ApiUrl) + return Invoke-RestMethod -Uri $ApiUrl +} + +function ConvertTo-UserRecord { # Pure transformation, no mocking needed + [CmdletBinding()] + param([Parameter(ValueFromPipeline)][object]$InputObject) + process { + [PSCustomObject]@{ + Name = $InputObject.displayName + Email = $InputObject.mail + } + } +} + +function Export-UserReport { # Mock the file system + [CmdletBinding()] + param([object[]]$UserData, [string]$Path) + $UserData | Export-Csv -Path $Path -NoTypeInformation +} +``` + +**Pass dependencies as parameters, not hardcoded values.** This makes mocking straightforward: + +```powershell +# Hard to test: buried dependency +function Get-BackupStatus { + $vault = Connect-AzKeyVault -VaultName 'production-vault' # Can't test without real vault + ... +} + +# Easy to test: inject the dependency +function Get-BackupStatus { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string]$VaultName + ) + $vault = Connect-AzKeyVault -VaultName $VaultName # Mock Connect-AzKeyVault in tests + ... +} +``` + +**Return objects, not formatted strings.** Objects can be asserted against; strings require fragile regex matching: + +```powershell +# Hard to test: "Backup OK - 3 jobs succeeded"... now parse that +function Get-BackupSummary { return "Backup $status - $count jobs $result" } + +# Easy to test: $result.Status | Should -Be 'OK' +function Get-BackupSummary { + [OutputType([PSCustomObject])] + param() + return [PSCustomObject]@{ + Status = $status + JobCount = $count + JobResult = $result + } +} +``` + +**Avoid module-level side effects.** If importing your module triggers API calls, file reads, or connection attempts, tests cannot run in isolation. Defer initialization to explicit function calls. + +### What Good Tests Look Like + +Tests should answer four questions: + +1. **Do the parameters work?** Mandatory parameters reject nulls, validation attributes enforce constraints, pipeline input is accepted where declared. + +2. **Does the happy path produce correct output?** Given known inputs, the output has the right type, the right properties, and the right values. + +3. **Do errors behave correctly?** Invalid inputs throw. API failures propagate with context. The function does not silently return `$null` when it should throw. + +4. **Do edge cases survive?** Empty collections, special characters, very long strings, `$null` in unexpected places. + +```powershell +Describe 'Get-BackupStatus' { + Context 'Parameter Validation' { + It 'Should require ComputerName' { + (Get-Command Get-BackupStatus).Parameters['ComputerName'].Attributes.Mandatory | + Should -Be $true + } + + It 'Should reject empty ComputerName' { + { Get-BackupStatus -ComputerName '' } | Should -Throw + } + } + + Context 'Functionality' { + BeforeAll { + Mock Invoke-RestMethod -ModuleName 'MyModule' -MockWith { + return @{ status = 'Healthy'; lastBackup = '2025-01-15' } + } + } + + It 'Should return a PSCustomObject with expected properties' { + $result = Get-BackupStatus -ComputerName 'SERVER01' + $result | Should -BeOfType [PSCustomObject] + $result.PSObject.Properties.Name | Should -Contain 'Status' + $result.PSObject.Properties.Name | Should -Contain 'LastBackup' + } + + It 'Should call the API exactly once per computer' { + Get-BackupStatus -ComputerName 'SERVER01' + Should -Invoke Invoke-RestMethod -ModuleName 'MyModule' -Times 1 -Exactly + } + } + + Context 'Error Handling' { + BeforeAll { + Mock Invoke-RestMethod -ModuleName 'MyModule' -MockWith { + throw [System.Net.WebException]::new('Connection refused') + } + } + + It 'Should throw when the API is unreachable' { + { Get-BackupStatus -ComputerName 'SERVER01' } | Should -Throw '*Connection refused*' + } + } + + Context 'Edge Cases' { + It 'Should handle multiple computers via pipeline' { + Mock Invoke-RestMethod -ModuleName 'MyModule' -MockWith { + return @{ status = 'Healthy' } + } + $results = @('SRV01', 'SRV02', 'SRV03') | Get-BackupStatus + $results.Count | Should -Be 3 + } + } +} +``` + +### Mock External Dependencies + +Never let tests hit real APIs, databases, or file systems. Mock everything external: + +```powershell +# Mock API calls +Mock Invoke-RestMethod -ModuleName 'MyModule' -MockWith { return @{ data = 'test' } } + +# Mock file system operations +Mock Test-Path -ModuleName 'MyModule' -MockWith { return $true } +Mock Export-Csv -ModuleName 'MyModule' + +# Mock credential retrieval +Mock Get-AzKeyVaultSecret -ModuleName 'MyModule' -MockWith { + return [PSCustomObject]@{ + SecretValue = (ConvertTo-SecureString 'mock' -AsPlainText -Force) + } +} + +# Verify mocks were called with expected arguments +Should -Invoke Invoke-RestMethod -ModuleName 'MyModule' -Times 1 -ParameterFilter { + $Uri -like '*/api/backup*' +} +``` + +Always use `-ModuleName` on every `Mock` and `Should -Invoke` call. Without it, mocks target the test scope instead of the module scope, and the real cmdlet runs inside the function. + +### The AI Agent Feedback Loop + +AI agents depend on test output to know whether their code works. Design tests to give clear, actionable signals: + +- **Structured output**: Use `-OutputFormat Structured` with `Invoke-QuickTest.ps1` so agents can parse JSON results programmatically instead of scraping console text +- **Specific assertions**: `$result.Name | Should -Be 'Expected'` tells the agent exactly what failed. `$result | Should -Not -BeNullOrEmpty` tells it almost nothing +- **Descriptive It blocks**: The test name IS the error message. `'Should return Healthy when all jobs pass'` is actionable. `'Should work'` is not +- **Fast feedback**: Quick-test a single function during development (`Invoke-QuickTest.ps1`), full suite before commit (`test-local.ps1`). Do not make agents wait for the full suite on every iteration +- **No test should depend on another test**: Tests must pass when run individually and in any order. Use `BeforeEach` for per-test setup, `BeforeAll` for shared read-only context + +## Things to Avoid + +- `Write-Host` in module code (breaks automation, untestable) +- Aliases in scripts and modules (`%` -> `ForEach-Object`, `?` -> `Where-Object`, `iex` -> `Invoke-Expression`) +- Positional parameters in calls longer than one argument +- `[void]` casting to suppress output -- use `$null =` or pipe to `Out-Null` for clarity +- `Add-Type` with inline C# unless genuinely necessary (prefer .NET methods directly) +- Global variables (`$global:`) -- use `$script:` scope or pass as parameters +- Magic numbers -- assign to named constants: `$maxRetryCount = 3` not bare `3` +- Backtick line continuation -- use splatting or natural line breaks (after `|`, `,`, `(`, `{`) diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000..cf162a7 --- /dev/null +++ b/.github/SECURITY.md @@ -0,0 +1,101 @@ +# Security Policy + +## Supported Versions + +We actively support the following versions of this project with security updates: + +| Version | Supported | +| ------- | ------------------ | +| Latest | :white_check_mark: | +| < 1.0 | :x: | + +## Reporting a Vulnerability + +We take the security of ConnectWiseControlAPI seriously. If you believe you have found a security vulnerability, please report it to us as described below. + +### Where to Report + +**Please do NOT report security vulnerabilities through public GitHub issues.** + +Instead, please report them via one of the following methods: + +1. **GitHub Security Advisories** (Preferred) + - Navigate to the repository's Security tab + - Click "Report a vulnerability" + - Fill out the security advisory form with details + +2. **Direct Email** + - Send an email to: **security@christaylor.codes** + - Use the subject line: `[SECURITY] ConnectWiseControlAPI - Brief Description` + +3. **Private Message on Slack** + - Contact **@CTaylor** on [MSPGeek Slack](https://join.mspgeek.com/) + - Clearly mark the message as security-related + +### What to Include + +Please include the following information in your report to help us better understand and resolve the issue: + +- **Type of issue** (e.g., credential exposure, injection, privilege escalation) +- **Full paths of source file(s)** related to the manifestation of the issue +- **Location of the affected source code** (tag/branch/commit or direct URL) +- **Step-by-step instructions to reproduce the issue** +- **Proof-of-concept or exploit code** (if possible) +- **Impact of the issue**, including how an attacker might exploit it +- **Your assessment of severity** (Critical, High, Medium, Low) + +### What to Expect + +After you submit a vulnerability report: + +1. **Acknowledgment** - We will acknowledge receipt of your vulnerability report within **48 hours** +2. **Initial Assessment** - We will provide an initial assessment of the vulnerability within **5 business days** +3. **Updates** - We will keep you informed of the progress toward a fix and full announcement +4. **Verification** - We may ask you to verify that our fix resolves the vulnerability +5. **Public Disclosure** - We will coordinate with you on the timing of public disclosure +6. **Credit** - We will credit you in the security advisory (unless you prefer to remain anonymous) + +### Severity Levels + +We use the [CVSS v3.1](https://www.first.org/cvss/calculator/3.1) scoring system to assess vulnerability severity: + +- **Critical (9.0-10.0)** - Fix within 24-48 hours +- **High (7.0-8.9)** - Fix within 1 week +- **Medium (4.0-6.9)** - Fix within 2-4 weeks +- **Low (0.1-3.9)** - Fix in next regular release + +## Security Best Practices for Users + +When using this module, please: + +1. **Secure Your Credentials** + - Never commit API credentials or passwords to source control + - Use PowerShell `[PSCredential]` objects, not plaintext passwords + - Use a complex username and password; accounts that require MFA sign in with `-Mfa`, + `-OneTimeCode` or `-TotpSecret` + - A TOTP secret for unattended logins (`-TotpSecret`) is a second password: keep it in a secret + store, apart from the account password where you can, and replace it if the computer is compromised + +2. **Use HTTPS** + - The module requires your ScreenConnect server to use HTTPS + - TLS 1.2 is enforced by the module + +3. **Keep Updated** + - Regularly update the module from the PowerShell Gallery + - Review the CHANGELOG for security-related fixes + +4. **PowerShell Execution Policy** + - Be cautious when using `-ExecutionPolicy Bypass` + - Prefer signed scripts in production environments + +## Security Hall of Fame + +We appreciate security researchers who responsibly disclose vulnerabilities. Contributors will be listed here (with permission): + +_No vulnerabilities reported yet._ + +## Additional Resources + +- [GitHub Security Best Practices](https://docs.github.com/en/code-security) +- [OWASP Top 10](https://owasp.org/www-project-top-ten/) +- [PowerShell Security Best Practices](https://docs.microsoft.com/en-us/powershell/scripting/security/overview) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..391237f --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,9 @@ +# Copilot Instructions + +This is a PowerShell module that must run on Windows PowerShell 5.1 and PowerShell 7 (no 7-only syntax). For full +conventions, architecture, commands, and contribution workflow, read [AGENTS.md](../AGENTS.md). + +Key file locations: `source/Public/` (exported), `source/Private/` (internal), `source/prefix.ps1` (module-level +code), `Tests/`. `./build.ps1` builds the published module into `output/`. + +Before committing: `./Tests/test-local.ps1` diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..28d7c8f --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,20 @@ +# Keeps the SHA-pinned GitHub Actions in .github/workflows current. +# Dependabot updates both the commit SHA and the trailing "# vX.Y.Z" comment. +# +# PowerShell Gallery modules are NOT covered by Dependabot. The Pester, PSScriptAnalyzer and platyPS +# versions are pinned in the env: block of .github/workflows/ci.yml; bump them there by hand. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + # Let new releases settle for a week before proposing them + cooldown: + default-days: 7 + groups: + github-actions: + patterns: + - '*' + commit-message: + prefix: ci diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a7be283 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,156 @@ +# GitHub Actions CI for ConnectWiseControlAPI (replaces AppVeyor) +# +# Every job calls Tests/test-local.ps1 for one stage, so `./Tests/test-local.ps1` locally runs the same checks. +# The build job (Sampler/ModuleBuilder) produces output///; the Pester jobs test that built +# module under both Windows PowerShell 5.1 and PowerShell 7, because the module must work on both. +# Publishing to the PowerShell Gallery is manual for now (see AGENTS.md). No module name is hard-coded here. +# +# Security note: never interpolate ${{ github.* }} / ${{ matrix.* }} values directly into a +# run: script. Pass them through env: instead. + +name: CI + +# Topic branches are covered by their pull request; listing them under push too would run every job twice. +# Use "Run workflow" (workflow_dispatch) to test a branch that has no PR yet. +on: + push: + branches: + - master + - 'release/**' + pull_request: + branches: + - master + - 'release/**' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + PESTER_VERSION: 5.7.1 + PSSA_VERSION: 1.24.0 + PLATYPS_VERSION: 0.14.2 + +jobs: + build: + name: Build module + runs-on: windows-latest + defaults: + run: + shell: pwsh + + steps: + - name: Checkout Repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Build + run: ./Tests/test-local.ps1 -Stage Build, Manifest + + - name: Upload Build Artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: module-build + path: | + output/ + !output/RequiredModules/ + if-no-files-found: error + retention-days: 7 + + test: + name: Pester (${{ matrix.name }}) + needs: build + runs-on: windows-latest + strategy: + fail-fast: false + matrix: + include: + - shell: pwsh + name: PowerShell 7 + - shell: powershell + name: Windows PowerShell 5.1 + defaults: + run: + shell: ${{ matrix.shell }} + + steps: + - name: Checkout Repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Download Build Artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: module-build + path: output + + - name: Install Pester + run: | + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072 + if (-not (Get-PackageProvider -ListAvailable -Name NuGet -ErrorAction SilentlyContinue)) { + Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Scope CurrentUser -Force | Out-Null + } + Set-PSRepository -Name PSGallery -InstallationPolicy Trusted + Install-Module -Name Pester -RequiredVersion $env:PESTER_VERSION -Scope CurrentUser -Force -SkipPublisherCheck + + - name: Run Pester against the built module + env: + RESULT_NAME: ${{ matrix.shell }} + run: | + ./Tests/test-local.ps1 -Stage Test -SkipWindowsPowerShell -TestResultPath "testResults-$env:RESULT_NAME.xml" + + - name: Upload Test Results + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: test-results-${{ matrix.shell }} + path: testResults-*.xml + retention-days: 30 + + analyze: + name: PSScriptAnalyzer + runs-on: windows-latest + defaults: + run: + shell: pwsh + + steps: + - name: Checkout Repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install PSScriptAnalyzer + run: | + Set-PSRepository -Name PSGallery -InstallationPolicy Trusted + Install-Module -Name PSScriptAnalyzer -RequiredVersion $env:PSSA_VERSION -Scope CurrentUser -Force + + - name: Analyze source + run: ./Tests/test-local.ps1 -Stage Analyze + + docs: + name: Docs drift + runs-on: windows-latest + defaults: + run: + shell: pwsh + + steps: + - name: Checkout Repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install platyPS + run: | + Set-PSRepository -Name PSGallery -InstallationPolicy Trusted + Install-Module -Name platyPS -RequiredVersion $env:PLATYPS_VERSION -Scope CurrentUser -Force + + - name: Regenerate help and check for drift + run: ./Tests/test-local.ps1 -Stage Docs diff --git a/.github/workflows/pr-validation.yml b/.github/workflows/pr-validation.yml new file mode 100644 index 0000000..775183b --- /dev/null +++ b/.github/workflows/pr-validation.yml @@ -0,0 +1,57 @@ +# GitHub Actions PR Validation Workflow +# Checks that CHANGELOG.md was updated and still has an [Unreleased] section. Warnings only. +# +# Security note: never interpolate ${{ github.* }} values directly into a +# run: script. Pass them through env: instead. + +name: PR Validation + +on: + pull_request: + branches: + - master + - 'release/**' + types: [opened, synchronize, reopened] + +permissions: + contents: read + +jobs: + validate: + name: Validate PR + runs-on: ubuntu-latest + + steps: + - name: Checkout Repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Check CHANGELOG Updated + shell: pwsh + env: + BASE_REF: ${{ github.base_ref }} + run: | + $ChangedFiles = git diff --name-only "origin/$env:BASE_REF...HEAD" + + if ($ChangedFiles -notcontains 'CHANGELOG.md') { + Write-Host "::warning::CHANGELOG.md has not been updated in this PR" + Write-Host "Consider adding release notes for your changes" + } else { + Write-Host "CHANGELOG.md has been updated" + } + + - name: Validate CHANGELOG Format + shell: pwsh + run: | + if (Test-Path 'CHANGELOG.md') { + $Changelog = Get-Content -Path 'CHANGELOG.md' -Raw + if ($Changelog -notmatch '\[Unreleased\]') { + Write-Host "::warning::CHANGELOG.md should have an [Unreleased] section for pending changes" + } else { + Write-Host "CHANGELOG.md has an [Unreleased] section" + } + } else { + Write-Host "::warning::No CHANGELOG.md found" + } diff --git a/.gitignore b/.gitignore index f999d21..a9fc20f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,104 @@ -/Scratch.ps1 -.vscode \ No newline at end of file +# ============================================ +# .gitignore - ConnectWiseControlAPI +# ============================================ + +# ---- Project-Specific ---- +Scratch*.ps1 +output/ +coverage.xml +testResults.xml +testResults-*.xml +nul + +# ---- Operating Systems ---- + +# Windows +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +Desktop.ini +$RECYCLE.BIN/ + +# macOS +.DS_Store +.AppleDouble +.LSOverride +._* +.Spotlight-V100 +.Trashes + +# Linux +*~ +.fuse_hidden* +.nfs* + +# ---- IDEs and Editors ---- + +# VS Code +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Visual Studio +.vs/ +*.suo +*.user +*.userosscache +*.sln.docuser + +# JetBrains (Rider, IntelliJ) +.idea/ +*.iml + +# Vim +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +Session.vim +Sessionx.vim +.netrwhist +tags + +# ---- PowerShell ---- +modules/ +*.dll +*.pdb + +# ---- Build Artifacts ---- +bin/ +obj/ +artifacts/ +publish/ +*.nupkg + +# ---- Security & Secrets ---- +.env +.env.* +*.pfx +*.key +*.pem +*.p12 +# Secret *data* files only (Export-Clixml credentials, secret JSON/text). Not name-only patterns like +# *secret*: those matched module source such as Test-CWCApiSecretConnection.ps1. +secrets/ +*.secret +*credential*.xml +*credential*.json +*secret*.xml +*secret*.json +*secret*.txt + +# ---- Claude Code ---- +.claude/settings.local.json +.claude/plan.md + +# ---- Logs & Temp ---- +*.log +logs/ +temp/ +tmp/ +*.tmp +*.bak +*.swp diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..6599efe --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,32 @@ +{ + "recommendations": [ + // PowerShell extension (required) + "ms-vscode.powershell", + + // Pester testing support + "pspester.pester-test", + + // Git integration + "eamodio.gitlens", + + // Markdown support + "yzhang.markdown-all-in-one", + "davidanson.vscode-markdownlint", + + // YAML support (for GitHub Actions) + "redhat.vscode-yaml", + + // EditorConfig support + "editorconfig.editorconfig", + + // Better Comments (color-coded comments) + "aaron-bond.better-comments", + + // Spell checker + "streetsidesoftware.code-spell-checker", + + // Todo Tree (track TODOs in code) + "gruntfuggly.todo-tree" + ], + "unwantedRecommendations": [] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..30e5d26 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,67 @@ +{ + // PowerShell extension settings + "powershell.codeFormatting.preset": "Custom", + "powershell.codeFormatting.openBraceOnSameLine": true, + "powershell.codeFormatting.newLineAfterOpenBrace": true, + // false keeps "} catch {" / "} else {" cuddled, matching PSPlaceCloseBrace in the analyzer settings + "powershell.codeFormatting.newLineAfterCloseBrace": false, + "powershell.codeFormatting.whitespaceBeforeOpenBrace": true, + "powershell.codeFormatting.whitespaceBeforeOpenParen": true, + "powershell.codeFormatting.whitespaceAroundOperator": true, + "powershell.codeFormatting.whitespaceAfterSeparator": true, + "powershell.codeFormatting.ignoreOneLineBlock": true, + "powershell.codeFormatting.alignPropertyValuePairs": true, + "powershell.codeFormatting.pipelineIndentationStyle": "IncreaseIndentationForFirstPipeline", + + // PSScriptAnalyzer integration + "powershell.scriptAnalysis.enable": true, + "powershell.scriptAnalysis.settingsPath": ".PSScriptAnalyzerSettings.psd1", + + // Pester integration + "pester.useLegacyCodeLens": false, + "pester.outputVerbosity": "FromPreference", + + // Editor settings + "editor.formatOnSave": true, + "editor.tabSize": 4, + "editor.insertSpaces": true, + "editor.detectIndentation": false, + "editor.rulers": [120], + "editor.wordWrap": "off", + + // File associations + "files.associations": { + "*.ps1": "powershell", + "*.psm1": "powershell", + "*.psd1": "powershell", + "*.ps1xml": "xml" + }, + + // Files to exclude from explorer + "files.exclude": { + "**/output": true, + "**/.vs": true, + "**/*.coverage.xml": true, + "**/testResults*.xml": true + }, + + // Search exclusions + "search.exclude": { + "**/output": true, + "**/.vs": true + }, + + // Git settings + "git.ignoreLimitWarning": true, + + // Markdown settings for documentation + "markdown.preview.breaks": true, + "[markdown]": { + "editor.wordWrap": "on", + "editor.quickSuggestions": { + "comments": "off", + "strings": "off", + "other": "off" + } + } +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..964bbeb --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,149 @@ +# AGENTS.md + +Single source of truth for AI agents (Claude Code, Copilot, others) working in this repository. Structure follows +the [GitHub-Template](https://github.com/christaylorcodes/GitHub-Template); deliberate differences are listed under +[Template differences](#template-differences). + +## Project Overview + +PowerShell module wrapping the ConnectWise ScreenConnect (formerly ConnectWise Control) web API. The module keeps +the `ConnectWiseControlAPI` name and the `CWC` prefix; prose uses "ScreenConnect". Published to the PowerShell Gallery and +used by MSPs. Source lives in `source/` (Sampler layout); `./build.ps1` builds the publishable module into +`output///`. Version: `ModuleVersion` in `source/ConnectWiseControlAPI.psd1` (history in +`CHANGELOG.md`). +Three auth modes via `Connect-CWC` (stored as `AuthType`): + +- `-Credentials` (`Credentials`): Basic auth, non-MFA account. Reaches the built-in `Services/*.ashx` and extensions. +- `-Credentials` plus `-Mfa`, `-OneTimeCode` or `-TotpSecret` (`Mfa`): `Private/Invoke-CWCMfaLogin.ps1` signs in with + `AuthenticationService.TryLogin` and the connection uses the `.ASPXAUTH` cookie, with no Authorization header and no + stored password. Reaches the same endpoints as `Credentials`. The login expires; a cache hit is re-checked with + `GetEligibleHosts`. +- `-ApiSecret`: RESTful API Manager extension secret. Reaches only that extension's methods: `Public/RestApi/` + functions plus the dual-mode ones (`Get-CWCSessionDetail`, `Update-CWCSessionName`, `Invoke-CWCCommand`), which + branch on `Test-CWCApiSecretConnection`. + +## Quick Start + +```powershell +# Development: import straight from source/ +Import-Module ./source/ConnectWiseControlAPI.psd1 -Force + +# Build the publishable module (first run resolves build dependencies into output/RequiredModules) +./build.ps1 -ResolveDependency -Tasks build + +# Everything CI runs: build, PSScriptAnalyzer, Test-ModuleManifest, Pester against the BUILT module on PS 7 +# *and* Windows PowerShell 5.1, docs drift +./Tests/test-local.ps1 + +# One stage (Test uses the last build; add -TestSource to test source/ instead) +./Tests/test-local.ps1 -Stage Test +./Tests/test-local.ps1 -Stage Analyze, Manifest + +# One test file against source/ (HTTP is mocked). Tests import $env:MODULE_TEST_PATH when set, else source/. +Invoke-Pester -Path ./Tests/ConnectWiseControlAPI.Private.Tests.ps1 + +# Regenerate Docs/, ConnectWiseControlAPI_Functions.md and the MAML help (never edit those by hand) +./Build/Update-Help.ps1 +``` + +Tooling: PowerShell 7 for the build; Pester 5.7.1+, PSScriptAnalyzer, platyPS 0.14.x (`RequiredModules.psd1`). + +`Tests/ConnectWiseControlAPI.Live.Tests.ps1` skips unless `$env:CWC_SERVER`, `CWC_USER` and `CWC_PASSWORD` are set. +`Tests/Live/Invoke-CWCLiveSmokeTest.ps1` checks behaviour against a real server (read-only unless `-AllowWrites`). + +## CI/CD + +`.github/workflows/ci.yml` runs on `windows-latest`. Each job calls one stage of `Tests/test-local.ps1`: + +| Job | What it checks | +| --- | --- | +| Build module | `./build.ps1` (Sampler/ModuleBuilder); `Test-ModuleManifest` on source and built manifests | +| Pester (PowerShell 7) / Pester (Windows PowerShell 5.1) | Full Pester suite against the built module, both editions | +| PSScriptAnalyzer | Zero analyzer errors in `source/` | +| Docs drift | `Build/Update-Help.ps1` leaves no diff | + +`.github/workflows/pr-validation.yml` warns when a PR doesn't update `CHANGELOG.md`. Publishing to the PowerShell +Gallery is manual and needs the owner's explicit go: build, then +`Publish-Module -Path output// -NuGetApiKey ` (publish the built folder, not `source/`). + +## Architecture + +- **Loading**: `build.ps1` (ModuleBuilder) merges `source/prefix.ps1`, `Private/` and `Public/` into one `.psm1` and + 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) 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 + server method's signature. `-Idempotent` turns on retry for HTTP 500 (3 retries, waiting 2/4/8 s; never for + permission errors; otherwise none, so 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`). `-Sensitive` redacts the body from 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. +- **Connection state**: `$script:CWCServerConnection` holds `Server`, `AuthType`, and `Headers`. Credentials mode + adds a `WebSession` (cookies) and an anti-forgery token taken from the front page. ApiSecret mode sends + `CTRLAuthHeader`. Connect-CWC validates the login with a test call and restores the previous connection if that + call fails. + +## Adding New Functions + +1. Add `source/Public//Verb-CWCNoun.ps1` (approved verb, `CWC` prefix). Use `Get-CWCSession.ps1` as the + template. No manifest edit: the build exports every `Public/` file. +2. Call `Invoke-CWCServiceMethod`. Check the method name and argument order against the ScreenConnect server's + `Services/*.ashx` source. Pass `-Idempotent` only for reads and "set to value" updates. +3. Add mocked Pester tests to `Tests/ConnectWiseControlAPI.Public.Tests.ps1`. +4. Run `./Build/Update-Help.ps1` and commit the generated pages. + +## Code Conventions + +Full style guide: [.github/PowerShell-StyleGuide.md](.github/PowerShell-StyleGuide.md) (read its version note +first). It lives under `.github/` rather than the template's `docs/` because Windows treats `docs/` and the +platyPS `Docs/` folder as the same directory, and `Build/Update-Help.ps1` would process it as a command page. +Enforced by `.PSScriptAnalyzerSettings.psd1` and `.editorconfig`: + +- **Code must run on PowerShell 3.0+ / Windows PowerShell 5.1**: no `??`, ternary, `&&`/`||`, or other 7-only syntax. +- 4-space indentation, max 120 characters per line, open brace on the same line, cuddled `} else {` / `} catch {`. +- Single quotes for constants, double quotes only for interpolation. Approved verbs only. +- Public functions need comment-based help (`.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER`, `.EXAMPLE`). Not every + function has it yet; add it to any function you touch. +- Destructive functions use `[CmdletBinding(SupportsShouldProcess)]`. Never pass the request body (it may hold a + password) as the `ShouldProcess` target. +- Report errors with `Write-Error` (non-terminating) and let callers decide. Return objects, not formatted output. +- PowerShell files: UTF-8 with BOM, CRLF line endings. +- `.gitignore` secret patterns are deliberately narrow (`*secret*` once hid `Test-CWCApiSecretConnection.ps1`); + a module test fails if any file under `source/`, `Tests/`, `Docs/`, `Build/`, `.build/` or `Examples/` is + ignored. + +### Git Commit Style + +- Present tense, imperative mood ("Add feature" not "Added feature"), max 72 characters on the first line. +- Reference issues with `#123` after the first line. + +## PR Requirements + +- All CI checks pass (build, Pester on both editions, analyzer, docs drift). +- Tests cover new or changed behaviour; PSScriptAnalyzer reports zero errors. +- `CHANGELOG.md` `[Unreleased]` is updated. + +## What AI Agents Should NOT Do + +- Do not push, merge, publish to the Gallery, or comment on GitHub without the owner's explicit go. +- Do not modify CI workflow files without explicit instruction. +- Do not add new dependencies without discussing in an issue first. +- Do not commit secrets, credentials, or API keys. +- Do not push directly to `master`; always use pull requests. + +## Template Differences + +| Template default | This repo | Why | +| --- | --- | --- | +| PowerShell 7.6, Core only | PowerShell 3.0+, runs on 5.1 and 7 | MSPs run it from RMM agents on Windows PowerShell 5.1 | +| Sampler `test` task, Pester 6 | `Tests/test-local.ps1`, Pester 5.7 | Must run the suite under Windows PowerShell 5.1 | +| `Tests/Unit/{Module,Public,Private}`, one file per function | Four suite files under `Tests/` | Not split yet | +| `docs/` (help, examples, media) | `Docs/` (platyPS), `Examples/`, `Media/` at the root | `docs/` = `Docs/` on Windows | +| Changelog release task | Release notes by hand | The task cannot parse this CHANGELOG's 4-part versions | +| PlatyPS 1.x → `docs/help` | platyPS 0.14 via `Build/Update-Help.ps1` (+ MAML) | `Get-Help` on 5.1 uses the MAML | +| Tag-driven publish workflow | Manual `Publish-Module` | Owner publishes by hand | diff --git a/Build/Update-Help.ps1 b/Build/Update-Help.ps1 new file mode 100644 index 0000000..a0971ea --- /dev/null +++ b/Build/Update-Help.ps1 @@ -0,0 +1,44 @@ +<# +.SYNOPSIS + Regenerates Docs/*.md, the module page and the MAML help from the functions' comment-based help. + +.DESCRIPTION + Run after adding or changing a public function. Requires platyPS (Install-Module platyPS). + Creates pages for new functions, updates existing ones (keeping hand-written text), then fixes what + platyPS gets wrong for this repo: + - PowerShell 7.4+ adds the -ProgressAction common parameter to every page; it is removed. + - The module page lives at the repo root, so its links need the Docs/ prefix. + Finally rebuilds source/en-US/ConnectWiseControlAPI-help.xml. + +.EXAMPLE + ./Build/Update-Help.ps1 +#> +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' +$RepoRoot = Split-Path -Parent $PSScriptRoot +$DocsPath = Join-Path $RepoRoot 'Docs' +$ModulePagePath = Join-Path $RepoRoot 'ConnectWiseControlAPI_Functions.md' + +Import-Module platyPS +$Module = Import-Module (Join-Path $RepoRoot 'source\ConnectWiseControlAPI.psd1') -Force -PassThru + +$Missing = @($Module.ExportedFunctions.Keys | Where-Object { -not (Test-Path (Join-Path $DocsPath "$_.md")) }) +if ($Missing) { $null = New-MarkdownHelp -Command $Missing -OutputFolder $DocsPath } +$null = Update-MarkdownHelpModule -Path $DocsPath -ModulePagePath $ModulePagePath -RefreshModulePage -Force + +foreach ($Page in Get-ChildItem $DocsPath -Filter '*.md') { + $Text = [IO.File]::ReadAllText($Page.FullName) + $Fixed = [regex]::Replace($Text, '(?s)### -ProgressAction\r?\n.*?(?=\r?\n### |\r?\n## )', '') + $Fixed = [regex]::Replace($Fixed, '\s*\[-ProgressAction \]', '') + if ($Fixed -ne $Text) { [IO.File]::WriteAllText($Page.FullName, $Fixed) } +} + +$Text = [IO.File]::ReadAllText($ModulePagePath) +[IO.File]::WriteAllText($ModulePagePath, [regex]::Replace($Text, '\]\((?!Docs/)([A-Za-z-]+\.md)\)', '](Docs/$1)')) + +$null = New-ExternalHelp -Path $DocsPath -OutputPath (Join-Path $RepoRoot 'source\en-US') -Force + +$Placeholders = Select-String -Path (Join-Path $DocsPath '*.md'), $ModulePagePath -Pattern '\{\{' +foreach ($Hit in $Placeholders) { Write-Warning "Placeholder left to fill: $($Hit.Filename):$($Hit.LineNumber)" } diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..208923a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,213 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +Planned as 0.5.0. Versions now have three parts (`0.5.0`); the build needs that. The previous release was 0.4.0.0. + +### Breaking changes + +- `Remove-CWCSession`, `Remove-CWCSessionNote` and `Remove-CWCHostFromSession` ask for confirmation by default. + Unattended scripts must add `-Confirm:$false`; without it they fail and remove nothing +- `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 +- `Get-CWCAuditLog` `-StartDate`/`-EndDate` default to the last 24 hours +- HTTP 500 errors are retried only for calls that are safe to repeat + +Details are in the sections below. + +### Product name + +- ConnectWise renamed Control back to ScreenConnect. Help, messages, examples and the Gallery description now say + ScreenConnect. The module name, the `CWC` command names and the `CWC.*` ErrorIds are unchanged +- `New-CWCMFA -DisplayName` defaults to `ScreenConnect` (was `CW Control`); this is only the label shown in the + authenticator app +- Removed `HelpInfoURI` from the manifest. It pointed at a help file, not an updatable-help location, so + `Update-Help` could not use it. The help ships with the module + +### Added + +- GitHub community files: CONTRIBUTING, CODE_OF_CONDUCT, SECURITY, issue templates, PR template +- `.editorconfig` for consistent editor formatting +- `.gitattributes` for line ending normalization and diff drivers +- `.PSScriptAnalyzerSettings.psd1` with 60+ rules targeting PS 5.1+ compatibility +- `CHANGELOG.md` (this file) +- `Connect-CWC -ApiSecret`: second authentication method using the RESTful API Manager extension's + `RESTfulAuthenticationSecret` (sent as `CTRLAuthHeader`). Works with MFA-enforced servers. + `Get-CWCSessionDetail`, `Update-CWCSessionName`, `New-CWCSession`, `Add-CWCSessionNote`, + `Send-CWCSessionMessage`, `Send-CWCToolboxItem` and `Invoke-CWCCommand` work on both connection types + (`Invoke-CWCCommand` queues only on API-secret connections; output is not retrieved); other functions + return an error naming the required auth method. `-Origin` overrides the Origin header for servers + with `RESTfulAllowedOrigin` set +- MFA login (#12): `Connect-CWC -Credentials` with `-Mfa` (asks for the one-time code; works with + authenticator-app, email and SMS codes), `-OneTimeCode` or `-TotpSecret` (computes the authenticator + code for unattended scripts; the secret is not stored). Signs in through + `AuthenticationService.TryLogin` and uses the login cookie; no Basic auth, and the password is not kept. + A cached MFA login is checked with one call and replaced when it has expired; a replaced MFA login is + logged out. Errors carry ErrorIds `CWC.MfaRequired`, `CWC.MfaCodeRejected`, `CWC.LoginFailed`, + `CWC.LoginThrottled`. Logins are never retried. Requests that fail on an MFA connection with a + permission or anti-forgery error say the login may have expired +- Failed requests no longer keep the login cookie on the request object stored in `$Error` +- `Connect-CWC` reuses a cached connection only for the same server, auth method and identity (user or + secret); anything else reconnects, even without `-Force`. Before, the old connection was silently kept + and later commands went to the previous server or ran as the previous user. If connecting to a + different server, method or identity fails, the module is left disconnected; a failed `-Force` refresh + of the same connection keeps it +- `Find-CWCSession` (`-Filter`/`-Name`/`-GUID`; API secret only), `New-CWCSession`, + `Add-CWCSessionNote`, `Send-CWCSessionMessage`, `Send-CWCToolboxItem`. On credentials connections the + last three queue session events (AddedNote 32, QueuedMessage 45, QueuedTool 47) and take `-Group` +- Live smoke test script `Tests/Live/Invoke-CWCLiveSmokeTest.ps1` (read-only by default; `-AllowWrites` + acts on one chosen test session and cleans up its notes; `-MfaUserName` tests the MFA login; `-TotpTestRole` tests the TOTP login with a temporary user it + creates and deletes; `-MfaNegativeProbes` records the raw failed-login codes) +- `Get-CWCRemoteWorkforceLaunchURL` (by `-GUID`, pipeline, or `-SessionName`), replacing `Get-CWCLauncURL` +- `Get-CWCRemoteWorkforceSession` lists the calling user's assigned machines (`GetRemoteWorkforceSessions`) +- `Initialize-CWCRemoteWorkforceSessionGroup` creates/repairs the extension's session group + (`EnsureCorrectSessionGroupExists`) +- `Remove-CWCSessionNote` removes notes by event ID (`-NoteEventID`) or all notes on a session (`-All`), + skipping notes already deleted; based on the design in #27 by CitybookServicesLTD +- `Remove-CWCHostFromSession` disconnects one connection from a session (QueuedForceDisconnect, event 48); + contributed by turbo-donkey (#28). Takes single `-SessionID`/`-ConnectionID` values and prompts by default +- `Remove-CWCSession -Uninstall` queues `QueuedUninstallAndDelete` (event 100) so the Access client is + uninstalled as well; without it the session record is only deleted (`DeletedSession`, event 21) +- `Enter-CWCSession` opens the Host client joined to a session, like Join in the web UI (#13). It builds + the web client's `sc-://` launch URL from the server's published launch settings and a Host + access token, checks that the client is installed for the current user, and logs the join + (`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 +- Live discovery script `Tests/Live/Invoke-CWCHostLaunchDiscovery.ps1` (read-only; redacts secrets; + `-Launch` opens the client for one test session) + +### Deprecated + +- `Get-CWCLauncURL` now forwards to `Get-CWCRemoteWorkforceLaunchURL` with a warning; removal in v1.0 + +### Changed + +- CI moved from AppVeyor to GitHub Actions (`.github/workflows/ci.yml`): Pester on PowerShell 7 and Windows + PowerShell 5.1, PSScriptAnalyzer, `Test-ModuleManifest` and a docs-drift check. `Tests/test-local.ps1` runs the + same stages locally. `Tests/appveyor.pester.ps1` removed. +- Repository layout follows the GitHub-Template (Sampler): the module source moved from `ConnectWiseControlAPI/` to + `source/` (`Extensions/Remote Workforce` is now `Extensions/RemoteWorkforce`) and `./build.ps1` builds the + published module into `output///`. Module-level setup moved from the `.psm1` to + `source/prefix.ps1`. The published module is unchanged: same 32 functions, PowerShell 3.0+, same help. CI and + `Tests/test-local.ps1` test the built module on PowerShell 7 and Windows PowerShell 5.1. +- Repo files aligned with the GitHub-Template: `AGENTS.md` (agent guide; `CLAUDE.md` now points to it), + `pr-validation.yml`, `dependabot.yml`, `copilot-instructions.md`, `.vscode/` settings, `.github/PowerShell-StyleGuide.md` +- Expanded `.gitignore` to cover OS files, IDEs, build artifacts, and secrets +- Updated `README.md` links to use local community files instead of external GitHub-Template references +- `Connect-CWC` validates credentials with `PageService/GetEligibleHosts` (any permission) instead of + `Get-CWCSessionGroup` (requires ManageSessionGroups), so non-admin accounts can connect +- `Get-CWCAuditLog` `-StartDate`/`-EndDate` default to the last 24 hours; `-IncludeSessionCaptures` is + deprecated (the server no longer accepts it) and now only emits a warning +- All API calls go through one internal helper that builds the endpoint and serializes arguments the same + way everywhere (single items, empty lists and nested event entries) +- HTTP 500 retries are limited to calls that are safe to repeat (reads, "set to value" updates). Before, + a 500 returned after the server had acted could queue a second command, wake, delete or user. Retries + now wait 2, 4 and 8 seconds (3 retries); the old 2-32 ms waits gave a struggling server no time to + recover. A final 500 error now includes the server's error message +- Session event type numbers are kept in one table, verified against a live server's web client +- **Breaking:** `Remove-CWCSession` prompts by default (`ConfirmImpact = 'High'`), confirms each session + separately and rejects an empty GUID. Unattended scripts must add `-Confirm:$false` +- `Connect-CWC` reports a failed login with its likely causes. Wrong credentials are not rejected with a + 401: the request runs as an anonymous user and fails with "Needs permission". A local failure (e.g. a + PowerShell error) is reported as such instead of being blamed on the credentials +- Removed the unloaded `WIP/Invoke-CWCSession.ps1` prototype, superseded by `Enter-CWCSession` +- `Get-CWCLastContact` returns an error when no connection event is found, instead of the current time +- `-Group` accepts the path parts of a nested session group (e.g. `'Clients','Acme'`) on every session + function that takes it; a single group name works as before +- Errors from API calls carry an ErrorId: `CWC.NotConnected`, `CWC.AuthModeMismatch`, `CWC.Http` + (the server answered) or `CWC.NoResponse`, so scripts can branch on `$_.FullyQualifiedErrorId`. The + message now shows the HTTP status and the server's own error text +- `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 +- `Build/Update-Help.ps1` regenerates `Docs/` and the MAML help in one step + +### Fixed + +Endpoint calls audited against the ScreenConnect server's `Services/*.ashx` source: + +- `Invoke-CWCWake` called `PageService.AddEventToSessions`, which no longer exists; it now queues wake + events (type 43) through `AddSessionEvents` +- `Get-CWCAuditLog` sent 6 arguments to `QueryAuditLog`, which takes 5 (the capture flag landed in the + event-type slot); local times were also sent with a `Z` suffix and are now converted to UTC +- `Get-CWCSessionGroup` now calls the documented `GetSessionGroups` (POST) method instead of the + undocumented `session-groups` GET route (both return the same data on ScreenConnect 26.7.6; not a bug fix) +- `Add-CWCRemoteWorkforceRequiredRole` now calls the extension's own + `EnsureRemoteWorkforceSecurityRoleExists` instead of building the role with `CreateRole`: it is + idempotent, honors the extension's `RoleName`/`SessionGroupName` settings, and sets `IsRoleCreated` +- `Update-CWCUser` erased the user's Comment field on every update +- `Invoke-CWCWebRequest -Debug` printed the Basic auth header and anti-forgery token; auth headers are now redacted +- `-Verbose`/`-Debug` output of `New-CWCUser`/`Update-CWCUser` included the password; request bodies holding + secrets are now redacted +- Cookies set by the server were sent back as a `Set-Cookie` request header, so the server never received + them; credentials connections now keep a web session (likely cause of "Invalid anti-forgery token", #22) +- The anti-forgery token regex depended on JSON key order on the server's front page +- Failed requests left auth headers on the request object kept in `$Error` (PS 5.1 and PS 6+); they are now stripped +- `Invoke-CWCCommand` compares event times on the server's clock, so poll latency can no longer make it + skip a fast command's output or return a previous command's output +- On PS 5.1, a non-JSON error body (IIS 401/404 page) threw while building the error and hid the real status +- `Get-CWCLastContact -Quiet -Seconds` was off by the local UTC offset (mixed UTC and local DateTimes) +- `Remove-CWCSession` packed multiple GUIDs into a single event entry; it now sends one entry per session +- `Invoke-CWCCommand` polled the rate-limited `GetSessionDetails` once a second for everything, including + the guest screenshot; it now requests events only (`Get-CWCSessionDetail -Include Events`), and + `Get-CWCLastContact` requests events and connections only +- `Get-CWCSessionDetail -Include` selects which parts of the session details to return (SessionDetailsItems + flags: SessionInfo 1, GuestScreenshotContent 4, Events 8, Connections 16, read from the web client) + +Extension calls audited against the Remote Workforce 1.3.16 `App_Extensions/2c4f522f…/Service.ashx` source: + +- `Get-CWCLauncURL` sent 6 arguments to `GetLaunchUrlForSessionId`, which takes 1 (the session ID), + including a plaintext password the server never used +- The `Launcher` extension folder was the Remote Workforce extension; functions moved under `Remote Workforce/` + +## [0.4.0.0] + +Published to the PowerShell Gallery from commit 889b56b; the repository manifest was not bumped at the time. + +### Fixed + +- `Get-CWCSession` uses the `GetLiveData` endpoint (#23) +- Error handling on PowerShell 7 no longer calls `GetResponseStream` (#15) + +## [0.3.5.0] - 2023-01-24 + +### Fixed + +- Retry logic in `Invoke-CWCWebRequest` moved into catch block (was dead code in try block) +- TLS upgraded from 1.0 to 1.2 in module loader +- Credential leak removed from verbose output in `Connect-CWC` +- Password exposure removed from `-WhatIf` output in `New-CWCUser` and `Update-CWCUser` +- SecureString BSTR memory properly zeroed in `Update-CWCUser` +- Error handling added to `Connect-CWC` initial server request +- Swallowed errors fixed in `Invoke-CWCCommand` and `Get-CWCLastContact` (changed `return $_` to `Write-Error`) +- Script-scope error variable leak fixed in `Invoke-CWCWebRequest` +- Undefined variables fixed in `Get-CWCLauncURL` (added as parameters) +- Manual JSON string replaced with `ConvertTo-Json` in `New-CWCAccessToken` +- `$Group` parameter types standardized to `[string]` across all functions +- `ShouldProcess` added to `Add-CWCRemoteWorkforceRequiredRole` +- UTC/local time mixing fixed in epoch calculations in `Get-CWCLastContact` + +## [0.3.4.0] - 2022-12-20 + +### Added + +- `Get-CWCLiveData` function for real-time session data +- Session event support via `AddSessionEvents` endpoint + +### Changed + +- Build configuration updates + +--- + +[Unreleased]: https://github.com/christaylorcodes/ConnectWiseControlAPI/compare/889b56b...HEAD +[0.4.0.0]: https://github.com/christaylorcodes/ConnectWiseControlAPI/commit/889b56b +[0.3.5.0]: https://www.powershellgallery.com/packages/ConnectWiseControlAPI/0.3.5.0 +[0.3.4.0]: https://www.powershellgallery.com/packages/ConnectWiseControlAPI/0.3.4.0 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..60d1b63 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,18 @@ +# CLAUDE.md + +[AGENTS.md](AGENTS.md) is the single source of truth for all AI agents: project context, architecture, commands, +code conventions and contribution rules. It is imported here so it is always loaded: + +@AGENTS.md + +## Mandatory Validation + +**Before every commit**, run: + +```powershell +./Tests/test-local.ps1 +``` + +It builds the module (`./build.ps1`), then runs PSScriptAnalyzer, `Test-ModuleManifest`, Pester against the built +module under PowerShell 7 **and** Windows PowerShell 5.1, and the docs-drift check, the same stages as CI. Do not commit until all pass. CI is a safety net only; failures should +never first appear there. diff --git a/ConnectWiseControlAPI/ConnectWiseControlAPI.Format.ps1xml b/ConnectWiseControlAPI/ConnectWiseControlAPI.Format.ps1xml deleted file mode 100644 index e69de29..0000000 diff --git a/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 b/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 deleted file mode 100644 index 4afa76d..0000000 --- a/ConnectWiseControlAPI/ConnectWiseControlAPI.psm1 +++ /dev/null @@ -1,22 +0,0 @@ -#Get public and private function definition files. -$Public = @( Get-ChildItem -Path $PSScriptRoot\Public\*.ps1 -ErrorAction SilentlyContinue -Recurse ) -$Private = @( Get-ChildItem -Path $PSScriptRoot\Private\*.ps1 -ErrorAction SilentlyContinue -Recurse ) - -#Dot source the files -Foreach($import in @($Public + $Private)) { - Try { - . $import.fullname - } Catch { - Write-Error -Message "Failed to import function $($import.fullname): $_" - } -} - -# Set Security Protocol -if([Net.SecurityProtocolType]::Tls) { - [Net.ServicePointManager]::SecurityProtocol=[Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls -} - -$script:InternalUserSource = 'InternalMembershipProvider' - -# Export Public functions ($Public.BaseName) for WIP modules -Export-ModuleMember -Function $Public.Basename \ No newline at end of file diff --git a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 b/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 deleted file mode 100644 index 22a2675..0000000 --- a/ConnectWiseControlAPI/Private/Invoke-CWCWebRequest.ps1 +++ /dev/null @@ -1,96 +0,0 @@ -function Invoke-CWCWebRequest { - [CmdletBinding()] - param( - $Arguments, - [int]$MaxRetry = 5 - ) - - # Check that we have cached connection info - if (!$script:CWCServerConnection) { - $ErrorMessage = @() - $ErrorMessage += 'Not connected to a Control server.' - $ErrorMessage += '--> $CWCServerConnection variable not found.' - $ErrorMessage += "----> Run 'Connect-CWC' to initialize the connection before issuing other CWC cmdlets." - return Write-Error ($ErrorMessage | Out-String) - } - - $BaseURI = "https://$($script:CWCServerConnection.Server)" - $Arguments.URI = Join-Url $BaseURI $Arguments.Endpoint - $Arguments.remove('Endpoint') - $Arguments.Headers = $script:CWCServerConnection.Headers - $Arguments.UseBasicParsing = $true - Write-Debug "Arguments: $($Arguments | ConvertTo-Json)" - - # Issue request - try { $Result = Invoke-WebRequest @Arguments } - catch { - # Start error message - $ErrorMessage = @() - - if ($_.Exception.Response -and $PSVersionTable.PSVersion.Major -lt 6) { - # Read exception response - $ErrorStream = $_.Exception.Response.GetResponseStream() - $Reader = New-Object System.IO.StreamReader($ErrorStream) - $script:ErrBody = $Reader.ReadToEnd() | ConvertFrom-Json - - if ($ErrBody.code) { - $ErrorMessage += 'An exception has been thrown.' - $ErrorMessage += "--> $($ErrBody.code)" - if ($ErrBody.code -eq 'Unauthorized') { - $ErrorMessage += "-----> $($ErrBody.message)" - $ErrorMessage += "-----> Use 'Disconnect-CWC' or 'Connect-CWC -Force' to set new authentication." - } - else { - $ErrorMessage += "-----> $($ErrBody.code): $($ErrBody.message)" - $ErrorMessage += '-----> ^ Error has not been documented please report. ^' - } - } - elseif ($_.Exception.message) { - $ErrorMessage += 'An exception has been thrown.' - $ErrorMessage += "--> $($_.Exception.message)" - } - } - - if ($_.ErrorDetails) { - $ErrorMessage += 'An error has been thrown.' - $script:ErrDetails = $_.ErrorDetails - $ErrorMessage += "--> $($ErrDetails.code)" - $ErrorMessage += "--> $($ErrDetails.message)" - if ($ErrDetails.errors.message) { - $ErrorMessage += "-----> $($ErrDetails.errors.message)" - } - } - - if ($ErrorMessage.Length -lt 1) { $ErrorMessage = $_ } - else { $ErrorMessage += $_.ScriptStackTrace } - - return Write-Error ($ErrorMessage | Out-String) - } - - # Not sure this will be hit with current iwr error handling - # May need to move to catch block need to find test - # TODO Find test for retry - # Retry the request - $Retry = 0 - while ($Retry -lt $MaxRetry -and $Result.StatusCode -eq 500) { - $Retry++ - # ConnectWise Manage recommended wait time - $Wait = $([math]::pow( 2, $Retry)) - Write-Warning "Issue with request, status: $($Result.StatusCode) $($Result.StatusDescription)" - Write-Warning "$($Retry)/$($MaxRetry) retries, waiting $($Wait)ms." - Start-Sleep -Milliseconds $Wait - $Result = Invoke-WebRequest @Arguments -UseBasicParsing - } - if ($Retry -ge $MaxRetry) { - return Write-Error "Max retries hit. Status: $($Result.StatusCode) $($Result.StatusDescription)" - } - - if ($script:CWCServerConnection -and $script:CWCServerConnection.Headers) { - $script:CWCServerConnection.Headers.'Set-Cookie' = $Result.Headers['Set-Cookie'] - } - - if ($Arguments.OutFile) { - return $Result - } - return $Result.content | ConvertFrom-Json -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditInfo.ps1 b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditInfo.ps1 deleted file mode 100644 index c1fa36e..0000000 --- a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditInfo.ps1 +++ /dev/null @@ -1,13 +0,0 @@ -function Get-CWCAuditInfo { - [CmdletBinding()] - param () - - $Endpoint = 'Services/AuditService.ashx/GetAuditInfo' - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Method = 'Post' - } - - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} diff --git a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 b/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 deleted file mode 100644 index 26275b2..0000000 --- a/ConnectWiseControlAPI/Public/AuditService/Get-CWCAuditLog.ps1 +++ /dev/null @@ -1,31 +0,0 @@ -function Get-CWCAuditLog { - [CmdletBinding()] - param ( - [datetime]$StartDate, - [datetime]$EndDate, - [string]$SessionName, - [switch]$IncludeSessionCaptures, - [int[]]$EventTypes, - [int[]]$SecurityTypes - ) - - $Endpoint = 'Services/AuditService.ashx/QueryAuditLog' - - $Body = ConvertTo-Json @( - $(Get-Date $StartDate -Format 'yyyy-MM-ddTHH:mm:ss.ffffZ'), - $(Get-Date $EndDate -Format 'yyyy-MM-ddTHH:mm:ss.ffffZ'), - $SessionName, - $IncludeSessionCaptures.IsPresent - $EventTypes, - $SecurityTypes - ) - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} diff --git a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 b/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 deleted file mode 100644 index a26b501..0000000 --- a/ConnectWiseControlAPI/Public/Authentication/Connect-CWC.ps1 +++ /dev/null @@ -1,45 +0,0 @@ -function Connect-CWC { - [CmdletBinding()] - param( - [Parameter(Mandatory=$true)] - [string]$Server, - [Parameter(Mandatory = $True)] - [pscredential]$Credentials, - [switch]$Force - ) - - if ($script:CWCServerConnection -and !$Force) { - Write-Verbose "Using cached Authentication information." - return - } - - $Server = $Server -replace("http.*:\/\/",'') - $EncodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Credentials.UserName):$($Credentials.GetNetworkCredential().Password)")) - $Headers = @{ - 'authorization' = "Basic $EncodedCredentials" - 'content-type' = "application/json; charset=utf-8" - 'origin' = "https://$Server" - } - - $FrontPage = Invoke-WebRequest -Uri $Headers.origin -Headers $Headers -UseBasicParsing - $Regex = [Regex]'(?<=antiForgeryToken":")(.*)(?=","isUserAdministrator)' - $Match = $Regex.Match($FrontPage.content) - if($Match.Success){ $Headers.'x-anti-forgery-token' = $Match.Value.ToString() } - else{ Write-Verbose 'Unable to find anti forgery token. Some commands may not work.' } - - $script:CWCServerConnection = @{ - Server = $Server - Headers = $Headers - } - Write-Verbose ($script:CWCServerConnection | Out-String) - - try{ - $null = Get-CWCSessionGroup -ErrorAction Stop - Write-Verbose '$CWCServerConnection, variable initialized.' - } - catch{ - Remove-Variable CWCServerConnection -Scope script - Write-Verbose 'Authentication failed.' - Write-Error $_ - } -} diff --git a/ConnectWiseControlAPI/Public/Extensions/Launcher/Get-CWCLauncURL.ps1 b/ConnectWiseControlAPI/Public/Extensions/Launcher/Get-CWCLauncURL.ps1 deleted file mode 100644 index c21fc3e..0000000 --- a/ConnectWiseControlAPI/Public/Extensions/Launcher/Get-CWCLauncURL.ps1 +++ /dev/null @@ -1,28 +0,0 @@ -function Get-CWCLauncURL { - [CmdletBinding(SupportsShouldProcess)] - param( - [Parameter(Mandatory = $True)] - [guid[]]$GUID - ) - - $Endpoint = 'App_Extensions/2c4f522f-b39a-413a-8807-dc52a2fce13e/Service.ashx/GetLaunchUrlForSessionId' - - $Body = ConvertTo-Json @( - @($GUID) - $onSuccess - $onFailure - $userContext - $userNameOverride - $passwordOverride - ) - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, 'New-CWCRemoteWorkforceAssignment')) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Add-CWCRemoteWorkforceRequiredRole.ps1 b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Add-CWCRemoteWorkforceRequiredRole.ps1 deleted file mode 100644 index 69f64aa..0000000 --- a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/Add-CWCRemoteWorkforceRequiredRole.ps1 +++ /dev/null @@ -1,46 +0,0 @@ -function Add-CWCRemoteWorkforceRequiredRole { - [CmdletBinding()] - param() - - $Endpoint = 'Services/SecurityService.ashx/SaveRole' - - $SessionGroups = @('My Assigned Machines') - $RoleName = 'Remote Workforce' - - $Body = ConvertTo-Json -Depth 10 @( - "", - $RoleName, - @(), - @( - @{ - "AccessControlType" = 0 - "Name" = "ViewSessionGroup" - "SessionGroupFilter" = 7 - "SessionGroupPath" = $SessionGroups - "OwnershipFilter" = 0 - }, - @{ - "AccessControlType" = 0 - "Name" = "JoinSession" - "SessionGroupFilter" = 7 - "SessionGroupPath" = $SessionGroups - "OwnershipFilter" = 0 - }, - @{ - "AccessControlType" = 0 - "Name" = "HostSessionWithoutConsent" - "SessionGroupFilter" = 7 - "SessionGroupPath" = $SessionGroups - "OwnershipFilter" = 0 - } - ) - ) - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/New-CWCRemoteWorkforceAssignment.ps1 b/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/New-CWCRemoteWorkforceAssignment.ps1 deleted file mode 100644 index 0bba3b9..0000000 --- a/ConnectWiseControlAPI/Public/Extensions/Remote Workforce/New-CWCRemoteWorkforceAssignment.ps1 +++ /dev/null @@ -1,29 +0,0 @@ -function New-CWCRemoteWorkforceAssignment { - [CmdletBinding(SupportsShouldProcess)] - param( - [Parameter(Mandatory = $True)] - [guid[]]$GUID, - [Parameter(Mandatory = $True)] - [string]$Username, - [string]$DisplayName, - [string]$Group = 'All Machines' - ) - - $Endpoint = 'App_Extensions/2c4f522f-b39a-413a-8807-dc52a2fce13e/Service.ashx/AddAssignmentNoteToSession' - - $Body = ConvertTo-Json @( - @($Group), - $GUID, - "UserName:$($Username),UserDisplayName:$($DisplayName)" - ) - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, 'New-CWCRemoteWorkforceAssignment')) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} diff --git a/ConnectWiseControlAPI/Public/Helpers/New-CWCMFA.ps1 b/ConnectWiseControlAPI/Public/Helpers/New-CWCMFA.ps1 deleted file mode 100644 index 39570f0..0000000 --- a/ConnectWiseControlAPI/Public/Helpers/New-CWCMFA.ps1 +++ /dev/null @@ -1,20 +0,0 @@ -function New-CWCMFA { - [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'None')] - param( - $DisplayName = 'CW Control', - $UserAccount - ) - $Possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' - $Key = (1..16 | ForEach-Object { $Possible.ToCharArray() | Get-Random }) -join '' - - $otpauth = "otpauth://totp/$($DisplayName):$($UserAccount)?secret=$($Key)" - Add-Type -AssemblyName System.Web - $otpauthEncoded = [System.Web.HTTPUtility]::UrlEncode($otpauth) - $qrUrl = "https://quickchart.io/chart?cht=qr&chs=400x400&chl=$($otpauthEncoded)&chld=L" - if ($PSCmdlet.ShouldProcess('New-CWCMFA')) { - [pscustomobject]@{ - 'QR' = $qrUrl - 'OTP' = "ms:$Key" - } - } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 deleted file mode 100644 index f3d7845..0000000 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCLastContact.ps1 +++ /dev/null @@ -1,52 +0,0 @@ -function Get-CWCLastContact { - [CmdletBinding()] - [OutputType([boolean], ParameterSetName = ('Quiet'))] - [OutputType([datetime])] - param( - [Parameter(Mandatory = $True)] - [guid]$GUID, - [parameter(ParameterSetName = 'Quiet')] - [switch]$Quiet, - [int]$Seconds, - [string]$Group = 'All Machines' - ) - - # Time conversion - $origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 - $epoch = $((New-TimeSpan -Start $(Get-Date -Date '01/01/1970') -End $(Get-Date)).TotalSeconds) - - try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID } - catch { return $_ } - - if ($SessionDetails -eq 'null' -or !$SessionDetails) { - Write-Warning 'Machine not found.' - return $null - } - - $GuestSessionEvents = $SessionDetails.Events - $GuestSessionConnections = $SessionDetails.Connections | Where-Object { $_.ParticipantName } - - if ($GuestSessionEvents) { - - # Get connection events - $LatestEvent = $GuestSessionEvents | Where-Object { - $_.EventType -in (10, 11) -and - $_.ConnectionID -NotIn $GuestSessionConnections.ConnectionID - } | Sort-Object time | Select-Object -First 1 - if ($LatestEvent.EventType -eq 10) { - # Currently connected - if ($Quiet) { return $True } - else { return Get-Date } - } - else { - # Time conversion hell :( - $TimeDiff = $epoch - ($LatestEvent.Time / 1000) - $OfflineTime = $origin.AddSeconds($TimeDiff) - $Difference = New-TimeSpan -Start $OfflineTime -End $(Get-Date) - if ($Quiet -and $Difference.TotalSeconds -lt $Seconds) { return $True } - elseif ($Quiet) { return $False } - else { return $OfflineTime } - } - } - else { return Write-Error 'Unable to determine last contact.' } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 deleted file mode 100644 index 28271b4..0000000 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCSession.ps1 +++ /dev/null @@ -1,45 +0,0 @@ -function Get-CWCSession { - [CmdletBinding()] - param ( - [Parameter(Mandatory = $True)] - [ValidateSet('Support', 'Access', 'Meeting')] - $Type, - [string]$Group = 'All Machines', - [string]$Search, - [string]$FindSessionID, - [int]$Limit - ) - - $Endpoint = 'Services/PageService.ashx/GetLiveData' - - switch ($Type) { - 'Support' { $Number = 0 } - 'Meeting' { $Number = 1 } - 'Access' { $Number = 2 } - default { return Write-Error "Unknown Type, $Type" } - } - - $Body = ConvertTo-Json @( - @{ - HostSessionInfo = @{ - 'sessionType' = $Number - 'sessionGroupPathParts' = @($Group) - 'filter' = $Search - 'findSessionID' = $FindSessionID - 'sessionLimit' = $Limit - } - ActionCenterInfo = @{} - } - 0 - ) -Depth 5 - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - - $Data = Invoke-CWCWebRequest -Arguments $WebRequestArguments - $Data.ResponseInfoMap.HostSessionInfo.Sessions -} diff --git a/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 b/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 deleted file mode 100644 index c9bdecc..0000000 --- a/ConnectWiseControlAPI/Public/PageService/Get-CWCSessionDetail.ps1 +++ /dev/null @@ -1,21 +0,0 @@ -function Get-CWCSessionDetail { - [CmdletBinding()] - param ( - [string]$Group = 'All Machines', - [Parameter(Mandatory=$True)] - [guid]$GUID - ) - - $Endpoint = 'Services/PageService.ashx/GetSessionDetails' - - $Body = ConvertTo-Json @($Group,$GUID) - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 deleted file mode 100644 index 08f7537..0000000 --- a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCCommand.ps1 +++ /dev/null @@ -1,84 +0,0 @@ -function Invoke-CWCCommand { - [CmdletBinding()] - param ( - [Parameter(Mandatory = $True)] - [guid]$GUID, - [string]$Command, - [int]$TimeOut = 10000, - [int]$MaxLength = 10000, - [switch]$PowerShell, - [string]$Group = 'All Machines', - [switch]$NoWait - ) - - $Endpoint = 'Services/PageService.ashx/AddSessionEvents' - - $origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 - $SessionEventType = 44 - - # Format command - $FormattedCommand = @() - if ($Powershell) { $FormattedCommand += '#!ps' } - $FormattedCommand += "#timeout=$TimeOut" - $FormattedCommand += "#maxlength=$MaxLength" - $FormattedCommand += $Command - $FormattedCommand = $FormattedCommand | Out-String - $CommandObject = @{ - SessionID = $GUID - EventType = $SessionEventType - Data = $FormattedCommand - } - $Body = (ConvertTo-Json @(@($Group), @($CommandObject))).Replace('\r\n', '\n') - Write-Verbose $Body - - # Issue command - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - $null = Invoke-CWCWebRequest -Arguments $WebRequestArguments - if ($NoWait) { return } - - # Get Session - try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID } - catch { return $_ } - - #Get time command was executed - $epoch = $((New-TimeSpan -Start $(Get-Date -Date '01/01/1970') -End $(Get-Date)).TotalSeconds) - $ExecuteTime = $epoch - ((($SessionDetails.events | Where-Object { $_.EventType -eq 44 })[-1]).Time / 1000) - $ExecuteDate = $origin.AddSeconds($ExecuteTime) - - # Look for results of command - $Looking = $True - $TimeOutDateTime = (Get-Date).AddMilliseconds($TimeOut) - $Body = ConvertTo-Json @($Group, $GUID) - while ($Looking) { - try { $SessionDetails = Get-CWCSessionDetail -Group $Group -GUID $GUID } - catch { return $_ } - - $ConnectionsWithData = @() - Foreach ($Connection in $SessionDetails.Events) { - $ConnectionsWithData += $Connection | Where-Object { $_.EventType -eq 70 } - } - - $Events = ($ConnectionsWithData | Where-Object { $_.EventType -eq 70 -and $_.Time }) - foreach ($Event in $Events) { - $epoch = $((New-TimeSpan -Start $(Get-Date -Date '01/01/1970') -End $(Get-Date)).TotalSeconds) - $CheckTime = $epoch - ($Event.Time / 1000) - $CheckDate = $origin.AddSeconds($CheckTime) - if ($CheckDate -gt $ExecuteDate) { - $Looking = $False - $Output = $Event.Data -split '[\r\n]' | Where-Object { $_ -and $_ -ne "C:\WINDOWS\system32>$Command" } - Write-Verbose $Event.Data - return $Output - } - } - - Start-Sleep -Seconds 1 - if ($(Get-Date) -gt $TimeOutDateTime.AddSeconds(1)) { - $Looking = $False - Write-Warning 'Command timed out.' - } - } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 b/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 deleted file mode 100644 index 1023bef..0000000 --- a/ConnectWiseControlAPI/Public/PageService/Invoke-CWCWake.ps1 +++ /dev/null @@ -1,32 +0,0 @@ -function Invoke-CWCWake { - [CmdletBinding()] - param ( - [Parameter(Mandatory=$True)] - [guid[]]$GUID, - [Parameter(Mandatory=$True)] - [ValidateSet('Support','Access')] - [string]$Type - ) - - $Endpoint = 'Services/PageService.ashx/AddEventToSessions' - - $SessionEventType = 43 - - switch($Type){ - 'Support' { $Group = 'All Sessions' } - 'Access' { $Group = 'All Machines' } - default { return Write-Error "Unknown Type, $Type" } - } - - $Body = ConvertTo-Json @($Group,@($GUID),$SessionEventType,'') - Write-Verbose $Body - - # Issue command - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 b/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 deleted file mode 100644 index 9464dbb..0000000 --- a/ConnectWiseControlAPI/Public/PageService/New-CWCAccessToken.ps1 +++ /dev/null @@ -1,22 +0,0 @@ -function New-CWCAccessToken { - [CmdletBinding()] - param ( - [String[]]$Group = 'All Machines', - [Parameter(Mandatory = $True)] - [guid]$GUID - ) - - $Endpoint = 'Services/PageService.ashx/GetAccessToken' - - $Body = @" -[["$($Group -join '","')"],"$GUID"] -"@ - Write-Verbose $Body - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Method = 'Post' - Body = $Body - } - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 deleted file mode 100644 index b4d48d9..0000000 --- a/ConnectWiseControlAPI/Public/PageService/Remove-CWCHostFromSession.ps1 +++ /dev/null @@ -1,38 +0,0 @@ -function Remove-CWCHostFromSession -{ - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $True)] - [guid[]]$SessionID, - [Parameter(Mandatory = $True)] - [guid[]]$ConnectionID, - [Parameter(Mandatory = $True)] - [string]$Group - ) - - $Endpoint = 'Services/PageService.ashx/AddSessionEvents' - - $SessionEventType = 48 - $Body = ConvertTo-Json @( - @( - $Group - ), - @( - @{ - SessionID = $SessionID - EventType = $SessionEventType - ConnectionID = $ConnectionID - } - ) - ) - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, 'Remove-CWCHostFromSession')) - { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 b/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 deleted file mode 100644 index 89ec864..0000000 --- a/ConnectWiseControlAPI/Public/PageService/Remove-CWCSession.ps1 +++ /dev/null @@ -1,40 +0,0 @@ -function Remove-CWCSession -{ - [CmdletBinding(SupportsShouldProcess)] - param ( - [Parameter(Mandatory = $True)] - [guid[]]$GUID, - [Parameter(Mandatory = $True)] - [string]$Group - ) - - $Endpoint = 'Services/PageService.ashx/AddSessionEvents' - - $SessionEventType = 21 - - $GuidList = @() - foreach ($SessionID in $GUID) - { - $GuidList += @{ - SessionID = $SessionID - EventType = $SessionEventType - } - } - - $Body = ConvertTo-Json -Compress -InputObject @( - @( - $Group - ), - $GuidList - ) - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, 'Remove-CWCSession')) - { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 b/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 deleted file mode 100644 index 08447c2..0000000 --- a/ConnectWiseControlAPI/Public/PageService/Update-CWCCustomProperty.ps1 +++ /dev/null @@ -1,24 +0,0 @@ -function Update-CWCCustomProperty { - [CmdletBinding(SupportsShouldProcess)] - param( - [Parameter(Mandatory=$True)] - [guid]$GUID, - [Parameter(Mandatory=$True)] - [int]$Property, - [string]$Value, - [string[]]$Group = 'All Machines' - ) - - $Endpoint = 'Services/PageService.ashx/UpdateSessionCustomPropertyValue' - - $Body = ConvertTo-Json @($Group,$GUID,$Property,$Value) - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, "Update-CWCCustomProperty")) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 b/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 deleted file mode 100644 index 8d71ecb..0000000 --- a/ConnectWiseControlAPI/Public/PageService/Update-CWCSessionName.ps1 +++ /dev/null @@ -1,23 +0,0 @@ -function Update-CWCSessionName { - [CmdletBinding(SupportsShouldProcess)] - param( - [Parameter(Mandatory=$True)] - [guid]$GUID, - [Parameter(Mandatory=$True)] - [string]$NewName, - [string]$Group = 'All Machines' - ) - - $Endpoint = 'Services/PageService.ashx/UpdateSessionName' - - $Body = ConvertTo-Json @($Group,$GUID,$NewName) - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, "Update-CWCSessionName")) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/SecurityService/Get-CWCSecurityConfigurationInfo.ps1 b/ConnectWiseControlAPI/Public/SecurityService/Get-CWCSecurityConfigurationInfo.ps1 deleted file mode 100644 index daeaff0..0000000 --- a/ConnectWiseControlAPI/Public/SecurityService/Get-CWCSecurityConfigurationInfo.ps1 +++ /dev/null @@ -1,12 +0,0 @@ -function Get-CWCSecurityConfigurationInfo { - [CmdletBinding()] - param () - - $Endpoint = 'Services/SecurityService.ashx/GetSecurityConfigurationInfo' - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Method = 'Post' - } - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/SecurityService/New-CWCUser.ps1 b/ConnectWiseControlAPI/Public/SecurityService/New-CWCUser.ps1 deleted file mode 100644 index def3a90..0000000 --- a/ConnectWiseControlAPI/Public/SecurityService/New-CWCUser.ps1 +++ /dev/null @@ -1,38 +0,0 @@ -function New-CWCUser { - [CmdletBinding(SupportsShouldProcess)] - param( - [Parameter(Mandatory=$True)] - [pscredential]$Credentials, - [string]$OTP, - [string]$DisplayName, - [Parameter(Mandatory=$True)] - [string]$Email, - [string[]]$SecurityGroups = @(), - [boolean]$ForcePassChange = $true - ) - - $Endpoint = 'Services/SecurityService.ashx/SaveUser' - - $Body = ConvertTo-Json @( - $script:InternalUserSource, - $null, - $Credentials.UserName, - $Credentials.GetNetworkCredential().Password, - $Credentials.GetNetworkCredential().Password, - $OTP, - $DisplayName, - '', - $Email, - $SecurityGroups, - $ForcePassChange - ) - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, "New-CWCUser")) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/SecurityService/Remove-CWCUser.ps1 b/ConnectWiseControlAPI/Public/SecurityService/Remove-CWCUser.ps1 deleted file mode 100644 index b76bf29..0000000 --- a/ConnectWiseControlAPI/Public/SecurityService/Remove-CWCUser.ps1 +++ /dev/null @@ -1,23 +0,0 @@ -function Remove-CWCUser { - [CmdletBinding(SupportsShouldProcess)] - param( - [Parameter(Mandatory=$True)] - [string]$User - ) - - $Endpoint = 'Services/SecurityService.ashx/DeleteUser' - - $Body = ConvertTo-Json @( - $script:InternalUserSource, - $User - ) - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, "Remove-CWCUser")) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/SecurityService/Update-CWCUser.ps1 b/ConnectWiseControlAPI/Public/SecurityService/Update-CWCUser.ps1 deleted file mode 100644 index 5a37e54..0000000 --- a/ConnectWiseControlAPI/Public/SecurityService/Update-CWCUser.ps1 +++ /dev/null @@ -1,59 +0,0 @@ -function Update-CWCUser { - [CmdletBinding(SupportsShouldProcess)] - param( - [Parameter(Mandatory=$True)] - [string]$UserToUpdate, - [string]$NewUserName, - [secureString]$Password, - [string]$OTP, - [string]$DisplayName, - [string]$Email, - [string[]]$SecurityGroups, - [boolean]$ForcePassChange = $False - ) - - $Endpoint = 'Services/SecurityService.ashx/SaveUser' - - $Security = Get-CWCSecurityConfigurationInfo -ErrorAction Stop - $Internal = $Security.UserSources | Where-Object { $_.ResourceKey -eq $script:InternalUserSource } - $User = $Internal.Users | Where-Object { $_.Name -eq $UserToUpdate } - if(!$User){ return Write-Error "Unable to find user $UserToUpdate" } - - $Update = @( - $script:InternalUserSource, - $UserToUpdate, - $User.Name, - $null, - $null, - $User.PasswordQuestion, - $User.DisplayName, - '', - $User.Email, - $User.RoleNames, - $False - ) - - if($NewUserName){ $Update[2] = $NewUserName } - if($Password){ - $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) - $Update[3] = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr) - $Update[4] = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr) - Remove-Variable bstr - } - if($OTP){ $Update[5] = $OTP } - if($DisplayName){ $Update[6] = $DisplayName } - if($Email){ $Update[8] = $Email } - if($SecurityGroups){ $Update[9] = $SecurityGroups } - if($ForcePassChange){ $Update[10] = $True } - - $Body = ConvertTo-Json $Update - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Body = $Body - Method = 'Post' - } - if ($PSCmdlet.ShouldProcess($WebRequestArguments.Body, "Update-CWCUser")) { - Invoke-CWCWebRequest -Arguments $WebRequestArguments - } -} \ No newline at end of file diff --git a/ConnectWiseControlAPI/Public/SessionGroupService/Get-CWCSessionGroup.ps1 b/ConnectWiseControlAPI/Public/SessionGroupService/Get-CWCSessionGroup.ps1 deleted file mode 100644 index 27de46f..0000000 --- a/ConnectWiseControlAPI/Public/SessionGroupService/Get-CWCSessionGroup.ps1 +++ /dev/null @@ -1,13 +0,0 @@ -function Get-CWCSessionGroup { - [CmdletBinding()] - param () - - $Endpoint = 'Services/SessionGroupService.ashx/session-groups' - - $WebRequestArguments = @{ - Endpoint = $Endpoint - Method = 'Get' - } - - Invoke-CWCWebRequest -Arguments $WebRequestArguments -} diff --git a/ConnectWiseControlAPI_Functions.md b/ConnectWiseControlAPI_Functions.md index 5609a15..deba413 100644 --- a/ConnectWiseControlAPI_Functions.md +++ b/ConnectWiseControlAPI_Functions.md @@ -14,8 +14,17 @@ This module wraps the web API into PowerShell functions. ### [Add-CWCRemoteWorkforceRequiredRole](Docs/Add-CWCRemoteWorkforceRequiredRole.md) Create a new Remote Workforce security role +### [Add-CWCSessionNote](Docs/Add-CWCSessionNote.md) +Adds a note to a session. + ### [Connect-CWC](Docs/Connect-CWC.md) -Initializes the connection parameters for the module. +Connects to a ConnectWise ScreenConnect server. + +### [Enter-CWCSession](Docs/Enter-CWCSession.md) +Opens the ConnectWise ScreenConnect Host client joined to a session, like Join in the web UI. + +### [Find-CWCSession](Docs/Find-CWCSession.md) +Finds sessions by session filter expression, name or ID (API secret connections). ### [Get-CWCAuditInfo](Docs/Get-CWCAuditInfo.md) Shows current audit settings @@ -27,7 +36,14 @@ Pull audit log information Returns the date the machine last connected to the control server. ### [Get-CWCLauncURL](Docs/Get-CWCLauncURL.md) -{{ Fill in the Synopsis }} +DEPRECATED. +Use Get-CWCRemoteWorkforceLaunchURL. + +### [Get-CWCRemoteWorkforceLaunchURL](Docs/Get-CWCRemoteWorkforceLaunchURL.md) +Gets a Remote Workforce host launch URL for an assigned machine. + +### [Get-CWCRemoteWorkforceSession](Docs/Get-CWCRemoteWorkforceSession.md) +Lists the Remote Workforce machines assigned to the calling user. ### [Get-CWCSecurityConfigurationInfo](Docs/Get-CWCSecurityConfigurationInfo.md) Will return security configuration information. @@ -41,6 +57,9 @@ Will return information about a session. ### [Get-CWCSessionGroup](Docs/Get-CWCSessionGroup.md) Returns details of all session groups. +### [Initialize-CWCRemoteWorkforceSessionGroup](Docs/Initialize-CWCRemoteWorkforceSessionGroup.md) +Creates or repairs the session group used by the Remote Workforce extension. + ### [Invoke-CWCCommand](Docs/Invoke-CWCCommand.md) Will issue a command against a given machine and return the results. @@ -48,23 +67,38 @@ Will issue a command against a given machine and return the results. Will issue a wake command to a given session. ### [New-CWCAccessToken](Docs/New-CWCAccessToken.md) -{{ Fill in the Synopsis }} +Gets an access token for joining a session. ### [New-CWCMFA](Docs/New-CWCMFA.md) -Will generate an MFA code to use with user creation. +Creates a new authenticator-app (TOTP) secret for a ScreenConnect user. ### [New-CWCRemoteWorkforceAssignment](Docs/New-CWCRemoteWorkforceAssignment.md) Assign a user to machines. +### [New-CWCSession](Docs/New-CWCSession.md) +Creates a session. + ### [New-CWCUser](Docs/New-CWCUser.md) Creates a user. +### [Remove-CWCHostFromSession](Docs/Remove-CWCHostFromSession.md) +Disconnects one connection (for example a host) from a session. + ### [Remove-CWCSession](Docs/Remove-CWCSession.md) Will end a given session. +### [Remove-CWCSessionNote](Docs/Remove-CWCSessionNote.md) +Removes notes from a session. + ### [Remove-CWCUser](Docs/Remove-CWCUser.md) Removes an internal user. +### [Send-CWCSessionMessage](Docs/Send-CWCSessionMessage.md) +Sends a chat message to a session's guest. + +### [Send-CWCToolboxItem](Docs/Send-CWCToolboxItem.md) +Queues a Toolbox item to run on a session. + ### [Update-CWCCustomProperty](Docs/Update-CWCCustomProperty.md) Will update a custom property for a session. diff --git a/Docs/Add-CWCRemoteWorkforceRequiredRole.md b/Docs/Add-CWCRemoteWorkforceRequiredRole.md index 096bb91..b498cdc 100644 --- a/Docs/Add-CWCRemoteWorkforceRequiredRole.md +++ b/Docs/Add-CWCRemoteWorkforceRequiredRole.md @@ -13,7 +13,8 @@ Create a new Remote Workforce security role ## SYNTAX ``` -Add-CWCRemoteWorkforceRequiredRole [] +Add-CWCRemoteWorkforceRequiredRole [-WhatIf] [-Confirm] + [] ``` ## DESCRIPTION @@ -30,15 +31,44 @@ Adds the Remote Workforce security role ## PARAMETERS +### -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 -### None ## OUTPUTS -### System.Object ## NOTES ## RELATED LINKS diff --git a/Docs/Add-CWCSessionNote.md b/Docs/Add-CWCSessionNote.md new file mode 100644 index 0000000..245767c --- /dev/null +++ b/Docs/Add-CWCSessionNote.md @@ -0,0 +1,131 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Add-CWCSessionNote + +## SYNOPSIS +Adds a note to a session. + +## SYNTAX + +``` +Add-CWCSessionNote [-GUID] [-Note] [[-Group] ] + [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Queues an AddedNote session event. + +Credentials connections: PageService.AddSessionEvents. +The note is attributed to the connected +user and needs the AddNote permission in -Group. + +API secret connections: the RESTful API Manager extension's AddNoteToSession. +The note is +attributed to the extension's RESTfulUserName setting ("RESTful API" by default); -Group is ignored. + +## EXAMPLES + +### EXAMPLE 1 +``` +Add-CWCSessionNote -GUID $SessionID -Note 'Rebooted for patching' +``` + +## PARAMETERS + +### -GUID +Session ID. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: SessionID + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Note +Note text. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Group +Session group containing the session (credentials connections only). +Defaults to 'All Machines'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: All Machines +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 +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Connect-CWC.md b/Docs/Connect-CWC.md index 0a195b5..98b3e5a 100644 --- a/Docs/Connect-CWC.md +++ b/Docs/Connect-CWC.md @@ -8,82 +8,259 @@ schema: 2.0.0 # Connect-CWC ## SYNOPSIS -Initializes the connection parameters for the module. +Connects to a ConnectWise ScreenConnect server. ## SYNTAX +### Credentials (Default) ``` -Connect-CWC [-Server] [-Credentials] [-Force] [] +Connect-CWC -Server -Credentials [-Force] + [] +``` + +### TotpSecret +``` +Connect-CWC -Server -Credentials -TotpSecret [-Force] [] +``` + +### OneTimeCode +``` +Connect-CWC -Server -Credentials -OneTimeCode [-Force] [] +``` + +### Mfa +``` +Connect-CWC -Server -Credentials [-Mfa] [-Force] + [] +``` + +### ApiSecret +``` +Connect-CWC -Server -ApiSecret [-Origin ] [-Force] [] ``` ## DESCRIPTION -Initializes the connection parameters used by other commands in the module. +Three ways to sign in: + +-Credentials alone (default): Basic auth with a ScreenConnect user account that does not use MFA. +Gives access to every function in the module, limited by that user's permissions. Never expires. + +-Credentials with -Mfa, -OneTimeCode or -TotpSecret: signs in the way the web page does, with a one-time +code, for accounts that require MFA. Gives the same access as -Credentials alone. The login is a cookie +that the server expires; when it does, commands fail with a permission error and you run Connect-CWC +again. The password and TOTP secret are not kept after the login. + +-ApiSecret: the authentication secret configured in the RESTful API Manager extension's +RESTfulAuthenticationSecret setting, sent as the CTRLAuthHeader header. Works when every user account +requires MFA. Only functions backed by that extension are available (see NOTES); other functions return +an error telling you to connect with -Credentials. + +The connection is validated before it is cached. An existing connection to the same server with the same +method and identity (user and password, or secret) is reused unless -Force is given; anything else +reconnects. A cached MFA login is checked with one call first and replaced with a new login if it has +expired. ## EXAMPLES ### Example 1 ```powershell -PS C:\> Connect-CWC -Server 'control.christaylor.codes' -Credentials $Credentials -Force +PS C:\> Connect-CWC -Server 'screenconnect.example.com' -Credentials (Get-Credential) +``` + +Connects with an account that does not use MFA. + +### Example 2 +```powershell +PS C:\> Connect-CWC -Server 'screenconnect.example.com' -Credentials (Get-Credential) -Mfa +``` + +Connects with an account that requires MFA and asks for the one-time code. + +### Example 3 +```powershell +PS C:\> Connect-CWC -Server 'screenconnect.example.com' -Credentials $Credential -OneTimeCode (Read-Host 'One-time code') +``` + +Connects with an account that requires MFA, using a code you supply. +Reading it with Read-Host keeps it out of the command history. + +### Example 4 +```powershell +PS C:\> $Credential = Get-Secret -Name 'CWC-Login' +PS C:\> Connect-CWC -Server 'screenconnect.example.com' -Credentials $Credential -TotpSecret (Get-Secret -Name 'CWC-TOTP') ``` -Sets connection information used by the module and overwrites any previously set information. +Unattended login for an account that requires MFA. +Run it again before each batch of work: when the cached login is still valid it costs one call, and when +it has expired it logs in again. + +### Example 5 +```powershell +PS C:\> $Secret = Read-Host -AsSecureString -Prompt 'RESTful API secret' +PS C:\> Connect-CWC -Server 'screenconnect.example.com' -ApiSecret $Secret +``` + +Connects with the RESTful API Manager extension's secret. ## PARAMETERS +### -Server +ScreenConnect server hostname, e.g. screenconnect.example.com. A leading http(s):// is removed. HTTPS is always used. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Credentials -Credentials used to authenticate with the control server. +Username and password of a ScreenConnect user account. ```yaml Type: PSCredential -Parameter Sets: (All) +Parameter Sets: Credentials, TotpSecret, OneTimeCode, Mfa Aliases: Required: True -Position: 1 +Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Force -Used to overwrite any information already loaded in the session. +### -Mfa +Sign in for an account that requires MFA, asking for the one-time code at the console when the server +requests it. Works with authenticator apps and with codes the server sends by email or SMS (they are sent +at this point). For interactive use only. ```yaml Type: SwitchParameter -Parameter Sets: (All) +Parameter Sets: Mfa Aliases: -Required: False +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OneTimeCode +The current one-time code (6 to 8 digits) for an account that requires MFA. +Quote it, so a leading zero is kept. + +```yaml +Type: String +Parameter Sets: OneTimeCode +Aliases: + +Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Server -The URL to your control server. +### -TotpSecret +The account's authenticator-app (TOTP) secret, for unattended scripts. +The current code is computed from it at each login; the secret itself is not stored. +Accepts the value ScreenConnect stores for authenticator apps ("ms:" followed by Base32, as New-CWCMFA creates) +or bare Base32. Not for email or SMS codes. + +Keep it in a secret store, e.g. Microsoft.PowerShell.SecretManagement: -TotpSecret (Get-Secret ...). +A TOTP secret stored next to the password turns MFA into a single factor: keep them in separate vaults +where you can, prefer -ApiSecret when its functions are enough, and replace the secret if the computer is +compromised. + +```yaml +Type: SecureString +Parameter Sets: TotpSecret +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ApiSecret +The RESTful API Manager extension's RESTfulAuthenticationSecret value. + +```yaml +Type: SecureString +Parameter Sets: ApiSecret +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Origin +Origin header sent with -ApiSecret requests. Defaults to https://. Set it to match the +extension's RESTfulAllowedOrigin setting if that setting is configured. ```yaml Type: String +Parameter Sets: ApiSecret +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Force +Reconnect even when the cached connection is for the same server, method and identity. +If that refresh fails, the previous connection is kept. +A failed connection to a different server, method or identity leaves the module disconnected, so later +commands can't reach the old server. + +```yaml +Type: SwitchParameter Parameter Sets: (All) Aliases: -Required: True -Position: 0 +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 -### None ## OUTPUTS -### System.Object ## NOTES +Functions available with -ApiSecret: Get-CWCSessionDetail, Update-CWCSessionName, Invoke-CWCCommand +(queues the command; output is not retrieved), Find-CWCSession, New-CWCSession, Add-CWCSessionNote, +Send-CWCSessionMessage, Send-CWCToolboxItem. +Only calls that are safe to repeat (reads, "set to value" updates) are retried on HTTP 500. + +The API secret is not tied to a ScreenConnect user: the extension does not apply role permissions or session +group scoping, so it can act on every session. Treat it like an administrator password. +Requires the RESTful API Manager extension (2d558935-686a-4bd0-9991-07539f5fe749). + +MFA logins are never retried automatically: each attempt counts toward the server's login limits. +Errors carry an ErrorId: CWC.MfaRequired, CWC.MfaCodeRejected, CWC.LoginFailed, CWC.LoginThrottled or +CWC.NoResponse. The device is never marked as trusted, and the login is never saved to disk. ## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) diff --git a/Docs/Enter-CWCSession.md b/Docs/Enter-CWCSession.md new file mode 100644 index 0000000..b4d8b02 --- /dev/null +++ b/Docs/Enter-CWCSession.md @@ -0,0 +1,159 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Enter-CWCSession + +## SYNOPSIS +Opens the ConnectWise ScreenConnect Host client joined to a session, like Join in the web UI. + +## SYNTAX + +``` +Enter-CWCSession [-GUID] [[-Type] ] [[-Group] ] [[-Name] ] [-UrlOnly] [] +``` + +## DESCRIPTION +Gets a Host access token for the session (PageService.GetAccessToken), builds the client launch +URL the web client uses (sc-\://...) and opens it with the installed ScreenConnect client. +The join is recorded in the session's audit trail (InitiatedJoin), as a web UI join is. + +The client must already be installed for the current Windows user: join any session once from +the web UI. +Launching works on Windows only; on other systems use -UrlOnly and open the URL +yourself. + +Requires Connect-CWC -Credentials and the JoinSession permission in -Group. + +## EXAMPLES + +### EXAMPLE 1 +``` +Enter-CWCSession -GUID 'a1b2c3d4-0000-0000-0000-000000000000' +``` + +### EXAMPLE 2 +``` +Get-CWCSession -Type Access -Search 'DESKTOP-01' -Limit 1 | Enter-CWCSession +``` + +### EXAMPLE 3 +``` +$Url = Enter-CWCSession -GUID $SessionID -UrlOnly +open $Url # macOS +``` + +## PARAMETERS + +### -GUID +Session ID. +Accepts SessionID from the pipeline (e.g. +from Get-CWCSession). + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: SessionID + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Type +Session type. +Defaults to Access. + +```yaml +Type: Object +Parameter Sets: (All) +Aliases: SessionType + +Required: False +Position: 2 +Default value: Access +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Group +Session group containing the session. +Defaults to 'All Machines' for Access, 'All Sessions' for +Support and 'All Meetings' for Meeting. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +Session name shown as the client's title. Taken from the pipeline (e.g. from Get-CWCSession); +when given, the session lookup is skipped. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -UrlOnly +Return the launch URL instead of opening the client. +The URL holds an access token: treat it +like a password. +It uses a delegated token that expires in 5 minutes when your role has the +CreateDelegatedAccessToken permission; otherwise a regular Host token (with a warning), which +is valid for the server's access token lifetime (7 days by default). + +```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 + +### System.String +## NOTES +The access token is not written to verbose, debug, warning or error output. +It does appear in +the launched client's command line (as with a web UI join), and PowerShell module or +script-block logging, when enabled, can record the API response that carries it. +The token is tied to the public IP address this call comes from, so the URL may not work from +another network (a different proxy or VPN exit). + +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Find-CWCSession.md b/Docs/Find-CWCSession.md new file mode 100644 index 0000000..7cc9a77 --- /dev/null +++ b/Docs/Find-CWCSession.md @@ -0,0 +1,115 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Find-CWCSession + +## SYNOPSIS +Finds sessions by session filter expression, name or ID (API secret connections). + +## SYNTAX + +### Filter (Default) +``` +Find-CWCSession -Filter [] +``` + +### Name +``` +Find-CWCSession -Name [] +``` + +### GUID +``` +Find-CWCSession -GUID [] +``` + +## DESCRIPTION +Calls the RESTful API Manager extension. +Searches all sessions of every type; results are not +limited by role permissions or session groups. + +-Filter uses ScreenConnect's session filter syntax, the same syntax as session group filters, +e.g. +"Name LIKE 'DESKTOP-*'" or "CustomProperty1 = 'Acme'". + +## EXAMPLES + +### EXAMPLE 1 +``` +Find-CWCSession -Filter "GuestOperatingSystemName LIKE '*Server*'" +``` + +### EXAMPLE 2 +``` +Find-CWCSession -Name 'DESKTOP-01' +``` + +## PARAMETERS + +### -Filter +A session filter expression (GetSessionsByFilter). + +```yaml +Type: String +Parameter Sets: Filter +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +Exact session name (GetSessionsByName). +Single quotes are not allowed because the extension +inserts the name into a filter expression without escaping. + +```yaml +Type: String +Parameter Sets: Name +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GUID +Session ID (GetSessionBySessionID). + +```yaml +Type: Guid +Parameter Sets: GUID +Aliases: + +Required: True +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 -ApiSecret and the RESTful API Manager extension. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Get-CWCAuditInfo.md b/Docs/Get-CWCAuditInfo.md index 59f7cd5..d7dcbbc 100644 --- a/Docs/Get-CWCAuditInfo.md +++ b/Docs/Get-CWCAuditInfo.md @@ -30,6 +30,7 @@ Displays the current audit settings ## PARAMETERS + ### 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). diff --git a/Docs/Get-CWCAuditLog.md b/Docs/Get-CWCAuditLog.md index 1a02226..399356a 100644 --- a/Docs/Get-CWCAuditLog.md +++ b/Docs/Get-CWCAuditLog.md @@ -31,8 +31,8 @@ Get the audit logs for Computer1 for the last day. ## PARAMETERS -### -EndDate -{{ Fill EndDate Description }} +### -StartDate +Start of the time range. Defaults to 24 hours ago. Local times are converted to UTC. ```yaml Type: DateTime @@ -46,81 +46,82 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -EventTypes -{{ Fill EventTypes Description }} +### -EndDate +End of the time range. Defaults to now. Local times are converted to UTC. ```yaml -Type: Int32[] +Type: DateTime Parameter Sets: (All) Aliases: Required: False -Position: 3 +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -IncludeSessionCaptures -{{ Fill IncludeSessionCaptures Description }} +### -SessionName +Only return entries for sessions with this name. ```yaml -Type: SwitchParameter +Type: String Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -SecurityTypes -{{ Fill SecurityTypes Description }} +### -IncludeSessionCaptures +Deprecated. The server no longer accepts this option; it is ignored with a warning. ```yaml -Type: Int32[] +Type: SwitchParameter Parameter Sets: (All) Aliases: Required: False -Position: 4 +Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -SessionName -{{ Fill SessionName Description }} +### -EventTypes +Session event type numbers to include (for example 44 for QueuedCommand, 70 for RanCommand). ```yaml -Type: String +Type: Int32[] Parameter Sets: (All) Aliases: Required: False -Position: 2 +Position: 4 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -StartDate -{{ Fill StartDate Description }} +### -SecurityTypes +Security event type numbers to include. ```yaml -Type: DateTime +Type: Int32[] Parameter Sets: (All) Aliases: Required: False -Position: 0 +Position: 5 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). diff --git a/Docs/Get-CWCLastContact.md b/Docs/Get-CWCLastContact.md index c4c080e..741c1e3 100644 --- a/Docs/Get-CWCLastContact.md +++ b/Docs/Get-CWCLastContact.md @@ -13,7 +13,7 @@ Returns the date the machine last connected to the control server. ## SYNTAX ``` -Get-CWCLastContact [-GUID] [-Quiet] [[-Seconds] ] [[-Group] ] [] +Get-CWCLastContact -GUID [-Quiet] [-Seconds ] [-Group ] [] ``` ## DESCRIPTION @@ -45,7 +45,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: 3 +Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -76,7 +76,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: 4 +Position: Named Default value: 0 Accept pipeline input: False Accept wildcard characters: False @@ -86,17 +86,18 @@ Accept wildcard characters: False Name of session group to use. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: Required: False -Position: 5 +Position: Named Default value: All Machines 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). diff --git a/Docs/Get-CWCLauncURL.md b/Docs/Get-CWCLauncURL.md index 2a146eb..aedfa1c 100644 --- a/Docs/Get-CWCLauncURL.md +++ b/Docs/Get-CWCLauncURL.md @@ -1,60 +1,131 @@ --- external help file: ConnectWiseControlAPI-help.xml Module Name: ConnectWiseControlAPI -online version: +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI schema: 2.0.0 --- # Get-CWCLauncURL ## SYNOPSIS -{{ Fill in the Synopsis }} +DEPRECATED. +Use Get-CWCRemoteWorkforceLaunchURL. ## SYNTAX ``` -Get-CWCLauncURL [-GUID] [-WhatIf] [-Confirm] [] +Get-CWCLauncURL [-GUID] [[-OnSuccess] ] [[-OnFailure] ] [[-UserContext] ] + [[-UserNameOverride] ] [[-PasswordOverride] ] + [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION -{{ Fill in the Description }} +Retained for backwards compatibility. +Forwards -GUID to Get-CWCRemoteWorkforceLaunchURL. +The Remote Workforce GetLaunchUrlForSessionId endpoint takes only a session ID, so the +OnSuccess, OnFailure, UserContext, UserNameOverride and PasswordOverride parameters are +ignored. +This function will be removed in v1.0. ## EXAMPLES -### Example 1 -```powershell -PS C:\> {{ Add example code here }} +### EXAMPLE 1 +``` +Get-CWCRemoteWorkforceLaunchURL -GUID $SessionID ``` - -{{ Add example description here }} ## PARAMETERS -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -GUID +One or more session IDs. ```yaml -Type: SwitchParameter +Type: Guid[] Parameter Sets: (All) -Aliases: cf +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OnSuccess +Ignored. +Not accepted by the server. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Required: False -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -GUID -{{ Fill GUID Description }} +### -OnFailure +Ignored. +Not accepted by the server. ```yaml -Type: Guid[] +Type: String Parameter Sets: (All) Aliases: -Required: True -Position: 0 +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UserContext +Ignored. +Not accepted by the server. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UserNameOverride +Ignored. +Not accepted by the server. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PasswordOverride +Ignored. +Not accepted by the server. + +```yaml +Type: SecureString +Parameter Sets: (All) +Aliases: + +Required: False +Position: 6 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -76,15 +147,34 @@ 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 -### None ## OUTPUTS -### System.Object ## NOTES +Deprecated in favor of Get-CWCRemoteWorkforceLaunchURL. +Author: Chris Taylor ## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Get-CWCRemoteWorkforceLaunchURL.md b/Docs/Get-CWCRemoteWorkforceLaunchURL.md new file mode 100644 index 0000000..43e750a --- /dev/null +++ b/Docs/Get-CWCRemoteWorkforceLaunchURL.md @@ -0,0 +1,101 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Get-CWCRemoteWorkforceLaunchURL + +## SYNOPSIS +Gets a Remote Workforce host launch URL for an assigned machine. + +## SYNTAX + +### GUID (Default) +``` +Get-CWCRemoteWorkforceLaunchURL -GUID [] +``` + +### SessionName +``` +Get-CWCRemoteWorkforceLaunchURL -SessionName [] +``` + +## DESCRIPTION +Calls the Remote Workforce extension's GetLaunchUrlForSessionId (by session GUID) or +GetLaunchUrl (by session name) endpoint and returns a ClickOnce launch URL. + +The extension only returns a URL when the CALLING user is the user the machine is assigned to +(the session is in their Remote Workforce session group, "My Assigned Machines" by default) +and has View and Join permissions on that group. +Otherwise the server returns null and this +function writes a warning. +An administrator cannot get launch URLs for other users' machines. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-CWCRemoteWorkforceLaunchURL -GUID 'd2b6f0a1-1111-2222-3333-444455556666' +``` + +### EXAMPLE 2 +``` +Get-CWCRemoteWorkforceSession | Get-CWCRemoteWorkforceLaunchURL +``` + +### EXAMPLE 3 +``` +Get-CWCRemoteWorkforceLaunchURL -SessionName 'DESKTOP-01' +``` + +## PARAMETERS + +### -GUID +One or more session IDs. +Each is requested separately. + +```yaml +Type: Guid[] +Parameter Sets: GUID +Aliases: SessionID + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -SessionName +The session name to look up within the caller's Remote Workforce sessions. + +```yaml +Type: String +Parameter Sets: SessionName +Aliases: + +Required: True +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 the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), ScreenConnect 23.6+. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Get-CWCRemoteWorkforceSession.md b/Docs/Get-CWCRemoteWorkforceSession.md new file mode 100644 index 0000000..3174ac0 --- /dev/null +++ b/Docs/Get-CWCRemoteWorkforceSession.md @@ -0,0 +1,53 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Get-CWCRemoteWorkforceSession + +## SYNOPSIS +Lists the Remote Workforce machines assigned to the calling user. + +## SYNTAX + +``` +Get-CWCRemoteWorkforceSession [] +``` + +## DESCRIPTION +Calls the Remote Workforce extension's GetRemoteWorkforceSessions endpoint, which returns the +sessions in the extension's session group for the CALLING user that they can view and join. +The server's name-to-ID map is returned as objects with Name and SessionID properties. + +## EXAMPLES + +### EXAMPLE 1 +``` +Get-CWCRemoteWorkforceSession +``` + +### EXAMPLE 2 +``` +Get-CWCRemoteWorkforceSession | Get-CWCRemoteWorkforceLaunchURL +``` + +## PARAMETERS + + +### 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 the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), ScreenConnect 23.6+. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Get-CWCSecurityConfigurationInfo.md b/Docs/Get-CWCSecurityConfigurationInfo.md index 48967f9..461f553 100644 --- a/Docs/Get-CWCSecurityConfigurationInfo.md +++ b/Docs/Get-CWCSecurityConfigurationInfo.md @@ -30,6 +30,7 @@ Returns security configuration ## PARAMETERS + ### 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). diff --git a/Docs/Get-CWCSession.md b/Docs/Get-CWCSession.md index c614118..921d278 100644 --- a/Docs/Get-CWCSession.md +++ b/Docs/Get-CWCSession.md @@ -13,7 +13,8 @@ Will return a list of sessions. ## SYNTAX ``` -Get-CWCSession -Type [-Group ] [-Search ] [-Limit ] [] +Get-CWCSession [-Type] [[-Group] ] [[-Search] ] [[-FindSessionID] ] + [[-Limit] ] [] ``` ## DESCRIPTION @@ -39,7 +40,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -49,12 +50,12 @@ Accept wildcard characters: False Name of session group to use. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 2 Default value: All Machines Accept pipeline input: False Accept wildcard characters: False @@ -69,7 +70,22 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FindSessionID +Session ID to locate in the results, so the session is included even when -Limit would cut it off. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -84,12 +100,13 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 5 Default value: 0 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). @@ -97,7 +114,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## OUTPUTS -### ConnectWise Control session objects +### ConnectWise ScreenConnect session objects ## NOTES Version: 1.0 Author: Chris Taylor diff --git a/Docs/Get-CWCSessionDetail.md b/Docs/Get-CWCSessionDetail.md index 6dcb0c1..669ac63 100644 --- a/Docs/Get-CWCSessionDetail.md +++ b/Docs/Get-CWCSessionDetail.md @@ -13,7 +13,7 @@ Will return information about a session. ## SYNTAX ``` -Get-CWCSessionDetail [-Group ] -GUID [] +Get-CWCSessionDetail [[-Group] ] [-GUID] [[-Include] ] [] ``` ## DESCRIPTION @@ -34,12 +34,12 @@ Will return details of the requested session. Name of session group to use. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 1 Default value: All Machines Accept pipeline input: False Accept wildcard characters: False @@ -54,12 +54,28 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` +### -Include +Parts of the session details to return: SessionInfo, GuestScreenshotContent, Events, Connections. Omit to return everything, including the guest screenshot. Ignored on -ApiSecret connections. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +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). @@ -67,7 +83,7 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## OUTPUTS -### ConnectWise Control session objects +### ConnectWise ScreenConnect session objects ## NOTES Version: 1.0 Author: Chris Taylor diff --git a/Docs/Get-CWCSessionGroup.md b/Docs/Get-CWCSessionGroup.md index 8d116e1..a33e74f 100644 --- a/Docs/Get-CWCSessionGroup.md +++ b/Docs/Get-CWCSessionGroup.md @@ -30,6 +30,7 @@ Returns details of all session groups. ## PARAMETERS + ### 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). diff --git a/Docs/Initialize-CWCRemoteWorkforceSessionGroup.md b/Docs/Initialize-CWCRemoteWorkforceSessionGroup.md new file mode 100644 index 0000000..b5ce41b --- /dev/null +++ b/Docs/Initialize-CWCRemoteWorkforceSessionGroup.md @@ -0,0 +1,87 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Initialize-CWCRemoteWorkforceSessionGroup + +## SYNOPSIS +Creates or repairs the session group used by the Remote Workforce extension. + +## SYNTAX + +``` +Initialize-CWCRemoteWorkforceSessionGroup [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Calls the Remote Workforce extension's EnsureCorrectSessionGroupExists endpoint. +The extension +creates its Access session group (name from the SessionGroupName setting, "My Assigned Machines" +by default) with the filter Notes LIKE '*|UserName:' + $USERLOGINNAME + ',*', or repairs an +older group whose filter was missing the trailing comma. +Without this group, assignments made +with New-CWCRemoteWorkforceAssignment are not visible to users. + +Idempotent. +Requires the Administer permission. + +## EXAMPLES + +### EXAMPLE 1 +``` +Initialize-CWCRemoteWorkforceSessionGroup +``` + +## PARAMETERS + +### -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 the Remote Workforce extension (2c4f522f-b39a-413a-8807-dc52a2fce13e), ScreenConnect 23.6+. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Invoke-CWCCommand.md b/Docs/Invoke-CWCCommand.md index 3bd1e50..bdce59f 100644 --- a/Docs/Invoke-CWCCommand.md +++ b/Docs/Invoke-CWCCommand.md @@ -13,8 +13,8 @@ Will issue a command against a given machine and return the results. ## SYNTAX ``` -Invoke-CWCCommand [-GUID] [[-Command] ] [[-TimeOut] ] [-MaxLength ] [-PowerShell] - [[-Group] ] [-NoWait] [] +Invoke-CWCCommand [-GUID] [[-Command] ] [[-TimeOut] ] [[-MaxLength] ] + [-PowerShell] [[-Group] ] [-NoWait] [] ``` ## DESCRIPTION @@ -48,7 +48,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: 3 +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -63,7 +63,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: 4 +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -79,12 +79,27 @@ Parameter Sets: (All) Aliases: Required: False -Position: 5 +Position: 3 Default value: 10000 Accept pipeline input: False Accept wildcard characters: False ``` +### -MaxLength +Maximum number of characters of command output to return. Defaults to 10000. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -PowerShell Issues the command in a powershell session. @@ -104,12 +119,12 @@ Accept wildcard characters: False Name of session group to use. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: Required: False -Position: 6 +Position: 5 Default value: All Machines Accept pipeline input: False Accept wildcard characters: False @@ -130,20 +145,6 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -MaxLength -{{ Fill MaxLength Description }} - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -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). diff --git a/Docs/Invoke-CWCWake.md b/Docs/Invoke-CWCWake.md index a6a8b91..0da2e14 100644 --- a/Docs/Invoke-CWCWake.md +++ b/Docs/Invoke-CWCWake.md @@ -13,7 +13,7 @@ Will issue a wake command to a given session. ## SYNTAX ``` -Invoke-CWCWake -GUID -Type [] +Invoke-CWCWake [-GUID] [-Type] [] ``` ## DESCRIPTION @@ -40,7 +40,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -55,12 +55,13 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 2 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). diff --git a/Docs/New-CWCAccessToken.md b/Docs/New-CWCAccessToken.md index d3a7e79..542d860 100644 --- a/Docs/New-CWCAccessToken.md +++ b/Docs/New-CWCAccessToken.md @@ -1,74 +1,82 @@ --- external help file: ConnectWiseControlAPI-help.xml Module Name: ConnectWiseControlAPI -online version: +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI schema: 2.0.0 --- # New-CWCAccessToken ## SYNOPSIS -{{ Fill in the Synopsis }} +Gets an access token for joining a session. ## SYNTAX ``` -New-CWCAccessToken [[-Group] ] [-GUID] [] +New-CWCAccessToken [[-Group] ] [-GUID] + [] ``` ## DESCRIPTION -{{ Fill in the Description }} +Calls PageService.GetAccessToken. +The token lets a Host client join the session with the +connected user's permissions for that session group; the user needs the JoinSession +permission in -Group. +Treat the token as a secret. ## EXAMPLES -### Example 1 -```powershell -PS C:\> {{ Add example code here }} +### EXAMPLE 1 +``` +$Token = New-CWCAccessToken -GUID $SessionID ``` - -{{ Add example description here }} ## PARAMETERS -### -GUID -{{ Fill GUID Description }} +### -Group +Session group containing the session. +Defaults to 'All Machines'. ```yaml -Type: Guid +Type: String[] Parameter Sets: (All) Aliases: -Required: True +Required: False Position: 1 -Default value: None +Default value: All Machines Accept pipeline input: False Accept wildcard characters: False ``` -### -Group -{{ Fill Group Description }} +### -GUID +Session ID. ```yaml -Type: String[] +Type: Guid Parameter Sets: (All) Aliases: -Required: False -Position: 0 +Required: True +Position: 2 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 -### None ## OUTPUTS -### System.Object ## NOTES +Requires Connect-CWC -Credentials. +Author: Chris Taylor ## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/New-CWCMFA.md b/Docs/New-CWCMFA.md index d327518..aab54d4 100644 --- a/Docs/New-CWCMFA.md +++ b/Docs/New-CWCMFA.md @@ -8,22 +8,30 @@ schema: 2.0.0 # New-CWCMFA ## SYNOPSIS -Will generate an MFA code to use with user creation. +Creates a new authenticator-app (TOTP) secret for a ScreenConnect user. ## SYNTAX ``` -New-CWCMFA [-DisplayName ] [-UserAccount ] [-WhatIf] [-Confirm] [] +New-CWCMFA [[-DisplayName] ] [[-UserAccount] ] [-WhatIf] + [-Confirm] [] ``` ## DESCRIPTION -Will generate an MFA code to use with user creation. +Generates a random 16-character Base32 secret. +Returns it in the form ScreenConnect stores ("ms:\") together with a QR code URL to scan with an +authenticator app. +Nothing is sent to the ScreenConnect server: pass the OTP value to New-CWCUser or Update-CWCUser to set it on +an account. + +The QR code URL is on quickchart.io and contains the secret. +Open it only if you accept sending the secret to that service. ## EXAMPLES ### Example 1 ```powershell -PS C:\> New-CWCMFA -DisplayName 'My Control Server' -UserAccount 'CTaylor' +PS C:\> New-CWCMFA -DisplayName 'My ScreenConnect Server' -UserAccount 'CTaylor' ``` Creates an MFA OTP code and QR URL with the provided information. @@ -31,7 +39,7 @@ Creates an MFA OTP code and QR URL with the provided information. ## PARAMETERS ### -DisplayName -Name you want to display in OTP app. +Label the authenticator app shows for the entry. ```yaml Type: Object @@ -39,8 +47,8 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named -Default value: None +Position: 1 +Default value: ScreenConnect Accept pipeline input: False Accept wildcard characters: False ``` @@ -54,19 +62,19 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -WhatIf +Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: SwitchParameter Parameter Sets: (All) -Aliases: cf +Aliases: wi Required: False Position: Named @@ -75,13 +83,13 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -WhatIf -Shows what would happen if the cmdlet runs. The cmdlet is not run. +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml Type: SwitchParameter Parameter Sets: (All) -Aliases: wi +Aliases: cf Required: False Position: Named @@ -90,6 +98,7 @@ 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). diff --git a/Docs/New-CWCRemoteWorkforceAssignment.md b/Docs/New-CWCRemoteWorkforceAssignment.md index af5fdd1..cdb1a36 100644 --- a/Docs/New-CWCRemoteWorkforceAssignment.md +++ b/Docs/New-CWCRemoteWorkforceAssignment.md @@ -13,8 +13,8 @@ Assign a user to machines. ## SYNTAX ``` -New-CWCRemoteWorkforceAssignment -GUID -Username [-DisplayName ] [-WhatIf] [-Confirm] - [] +New-CWCRemoteWorkforceAssignment [-GUID] [-Username] [[-DisplayName] ] + [[-Group] ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -38,7 +38,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -53,7 +53,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -68,22 +68,22 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -Group +Session group containing the session(s). Defaults to 'All Machines' where a default exists. ```yaml -Type: SwitchParameter +Type: String[] Parameter Sets: (All) -Aliases: cf +Aliases: Required: False -Position: Named +Position: 4 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -104,6 +104,22 @@ 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). diff --git a/Docs/New-CWCSession.md b/Docs/New-CWCSession.md new file mode 100644 index 0000000..b220a36 --- /dev/null +++ b/Docs/New-CWCSession.md @@ -0,0 +1,164 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# New-CWCSession + +## SYNOPSIS +Creates a session. + +## SYNTAX + +``` +New-CWCSession [-Type] [-Name] [-IsPublic] [[-Code] ] + [[-CustomPropertyValues] ] [-WhatIf] [-Confirm] + [] +``` + +## DESCRIPTION +Creates a session and returns the new session ID. +Works with both connection types: + +-Credentials: PageService.CreateSession. +Requires the create permission for the session type; +the session host is the connected user. + +-ApiSecret: the RESTful API Manager extension's CreateSession. +The session host is the +extension's RESTfulUserName setting ("RESTful API" by default). + +## EXAMPLES + +### EXAMPLE 1 +``` +New-CWCSession -Type Support -Name 'Ticket 12345' -Code '12345' +``` + +## PARAMETERS + +### -Type +Support, Meeting or Access. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +Session name. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -IsPublic +Make the session publicly listed on the guest page. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Code +Session join code. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CustomPropertyValues +Custom property values in order (CustomProperty1, CustomProperty2, ...). + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: @() +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 + +### System.Guid +## NOTES +Not retried on HTTP 500: a retry after the server created the session would create a second one. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/New-CWCUser.md b/Docs/New-CWCUser.md index 80e1478..998785e 100644 --- a/Docs/New-CWCUser.md +++ b/Docs/New-CWCUser.md @@ -13,8 +13,9 @@ Creates a user. ## SYNTAX ``` -New-CWCUser -Credentials [-OTP ] [-DisplayName ] -Email - [-SecurityGroups ] [-ForcePassChange ] [-WhatIf] [-Confirm] [] +New-CWCUser [-Credentials] [[-OTP] ] [[-DisplayName] ] [-Email] + [[-SecurityGroups] ] [[-ForcePassChange] ] [-WhatIf] + [-Confirm] [] ``` ## DESCRIPTION @@ -37,6 +38,21 @@ New-CWCUser @NewUserParams ## PARAMETERS +### -Credentials +PSCredential object for the new user you want to create. + +```yaml +Type: PSCredential +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -OTP The OTP key used for MFA. Can be generated with `New-CWCMFA` @@ -46,7 +62,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -61,7 +77,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -76,7 +92,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 4 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -91,7 +107,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 5 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -106,27 +122,12 @@ Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 6 Default value: True 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 -``` - ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. @@ -142,21 +143,22 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Credentials -PSCredential object for the new user you want to create. +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml -Type: PSCredential +Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: cf -Required: True +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). diff --git a/Docs/Private/Invoke-CWCWebRequest.md b/Docs/Private/Invoke-CWCWebRequest.md deleted file mode 100644 index ca26865..0000000 --- a/Docs/Private/Invoke-CWCWebRequest.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -external help file: -Module Name: -online version: -schema: 2.0.0 ---- - -# Invoke-CWCWebRequest - -## SYNOPSIS -Used to make the web requests for the module - -## SYNTAX - -``` -Invoke-CWCWebRequest [[-Arguments] ] [[-MaxRetry] ] [] -``` - -## DESCRIPTION -Used by the module to invoke requests and handle errors - -## EXAMPLES - -### Example 1 -```powershell -PS C:\> Invoke-CWCWebRequest -Arguments $Args -``` - -Passes a set of arguments to the web request handler. - -## PARAMETERS - -### -Arguments -An object containing parameters for the web request - -```yaml -Type: Object -Parameter Sets: (All) -Aliases: - -Required: False -Position: 0 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -MaxRetry -amount of times a request will be attempted before failing - -```yaml -Type: Int32 -Parameter Sets: (All) -Aliases: - -Required: False -Position: 1 -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 - -### None - -## OUTPUTS - -### System.Object -## NOTES - -## RELATED LINKS diff --git a/Docs/Private/Join-Url.md b/Docs/Private/Join-Url.md deleted file mode 100644 index 3f30b94..0000000 --- a/Docs/Private/Join-Url.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -external help file: -Module Name: -online version: -schema: 2.0.0 ---- - -# Join-Url - -## SYNOPSIS -{{ Fill in the Synopsis }} - -## SYNTAX - -``` -Join-Url [-Path] [-ChildPath] [] -``` - -## DESCRIPTION -{{ Fill in the Description }} - -## EXAMPLES - -### Example 1 -```powershell -PS C:\> {{ Add example code here }} -``` - -{{ Add example description here }} - -## PARAMETERS - -### -ChildPath -{{ Fill ChildPath Description }} - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -Path -{{ Fill Path Description }} - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: True -Position: 0 -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 - -### None - -## OUTPUTS - -### System.Object -## NOTES - -## RELATED LINKS diff --git a/Docs/Remove-CWCHostFromSession.md b/Docs/Remove-CWCHostFromSession.md new file mode 100644 index 0000000..8819550 --- /dev/null +++ b/Docs/Remove-CWCHostFromSession.md @@ -0,0 +1,129 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Remove-CWCHostFromSession + +## SYNOPSIS +Disconnects one connection (for example a host) from a session. + +## SYNTAX + +``` +Remove-CWCHostFromSession [-SessionID] [-ConnectionID] [-Group] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Queues a QueuedForceDisconnect session event (type 48) for the given connection, the same +action as disconnecting a participant in the ScreenConnect web UI. +Connection IDs are listed in +(Get-CWCSessionDetail -GUID \ -Include Connections).Connections. + +## EXAMPLES + +### EXAMPLE 1 +``` +$Connections = (Get-CWCSessionDetail -GUID $SessionID -Include Connections).Connections +$HostConnection = $Connections | Where-Object { $_.ProcessType -eq 1 } | Select-Object -First 1 +Remove-CWCHostFromSession -SessionID $SessionID -ConnectionID $HostConnection.ConnectionID -Group 'All Machines' +``` + +Disconnects the first host connected to the session (ProcessType 1 = Host). + +## PARAMETERS + +### -SessionID +Session ID. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ConnectionID +ID of the connection to disconnect. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Group +Session group containing the session: a name, or the path parts of a nested group. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: True +Position: 3 +Default value: None +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 +Contributed by turbo-donkey (#28). +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Remove-CWCSession.md b/Docs/Remove-CWCSession.md index c3f7ce8..41a3897 100644 --- a/Docs/Remove-CWCSession.md +++ b/Docs/Remove-CWCSession.md @@ -13,7 +13,8 @@ Will end a given session. ## SYNTAX ``` -Remove-CWCSession -GUID -Group [-WhatIf] [-Confirm] [] +Remove-CWCSession [-GUID] [-Group] [-Uninstall] + [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -40,19 +41,34 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -Group +Session group containing the session(s). Defaults to 'All Machines' where a default exists. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Uninstall +Queue an uninstall of the Access client and delete the session (QueuedUninstallAndDelete) instead of only deleting the session record. ```yaml Type: SwitchParameter Parameter Sets: (All) -Aliases: cf +Aliases: Required: False Position: Named @@ -76,21 +92,22 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Group -{{ Fill Group Description }} +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml -Type: String +Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: cf -Required: True +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). diff --git a/Docs/Remove-CWCSessionNote.md b/Docs/Remove-CWCSessionNote.md new file mode 100644 index 0000000..19f3495 --- /dev/null +++ b/Docs/Remove-CWCSessionNote.md @@ -0,0 +1,162 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Remove-CWCSessionNote + +## SYNOPSIS +Removes notes from a session. + +## SYNTAX + +### ById (Default) +``` +Remove-CWCSessionNote -GUID -NoteEventID [-Group ] [-WhatIf] [-Confirm] [] +``` + +### All +``` +Remove-CWCSessionNote -GUID [-All] [-Group ] [-WhatIf] + [-Confirm] [] +``` + +## DESCRIPTION +Deletes notes (AddedNote events) by adding a DeletedEvent correlated to each note, the same way +the ScreenConnect web UI removes a note. +The user needs the RemoveNote permission in -Group. + +-NoteEventID removes specific notes; -All removes every note still on the session. +Notes that +are already deleted are skipped. + +## EXAMPLES + +### EXAMPLE 1 +``` +Remove-CWCSessionNote -GUID $SessionID -All +``` + +Removes every note on the session, prompting for each one. + +### EXAMPLE 2 +``` +$Notes = (Get-CWCSessionDetail -GUID $SessionID -Include Events).Events | Where-Object EventType -eq 32 +$Notes | Where-Object Data -like 'Rebooted*' | ForEach-Object { + Remove-CWCSessionNote -GUID $SessionID -NoteEventID $_.EventID -Confirm:$false +} +``` + +## PARAMETERS + +### -GUID +Session ID. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: SessionID + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoteEventID +Event ID of each note to remove (the EventID of an AddedNote event in Get-CWCSessionDetail). + +```yaml +Type: Guid[] +Parameter Sets: ById +Aliases: EventID + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -All +Remove every note on the session. + +```yaml +Type: SwitchParameter +Parameter Sets: All +Aliases: + +Required: True +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Group +Session group containing the session: a name, or the path parts of a nested group. +Defaults to 'All Machines'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: All Machines +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 delete notes). +Based on the design in #27 by CitybookServicesLTD. +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Remove-CWCUser.md b/Docs/Remove-CWCUser.md index 90dc062..6f3d778 100644 --- a/Docs/Remove-CWCUser.md +++ b/Docs/Remove-CWCUser.md @@ -26,25 +26,10 @@ Removes the provided internal user. PS C:\> Remove-CWCUser -User 'ctaylor' ``` -Removes the 'ctaylor' user from Control. +Removes the 'ctaylor' user from ScreenConnect. ## PARAMETERS -### -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 -``` - ### -User The user to remove. @@ -54,7 +39,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: 0 +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -76,6 +61,22 @@ 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). diff --git a/Docs/Send-CWCSessionMessage.md b/Docs/Send-CWCSessionMessage.md new file mode 100644 index 0000000..43a4080 --- /dev/null +++ b/Docs/Send-CWCSessionMessage.md @@ -0,0 +1,146 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Send-CWCSessionMessage + +## SYNOPSIS +Sends a chat message to a session's guest. + +## SYNTAX + +``` +Send-CWCSessionMessage [-GUID] [-Message] [[-From] ] [[-Group] ] [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Queues a QueuedMessage session event. + +Credentials connections: PageService.AddSessionEvents. +The guest sees the connected user's +display name as the sender (-From is not supported) and the user needs the matching permission +in -Group. + +API secret connections: the RESTful API Manager extension's SendMessageToSession. +The guest sees +-From as the sender; -Group is ignored. + +## EXAMPLES + +### EXAMPLE 1 +``` +Send-CWCSessionMessage -GUID $SessionID -Message 'Your computer will restart in 5 minutes.' +``` + +## PARAMETERS + +### -GUID +Session ID. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: SessionID + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Message +Message text. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -From +Sender name shown to the guest (API secret connections only). + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: RESTful API +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Group +Session group containing the session (credentials connections only). +Defaults to 'All Machines'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: All Machines +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 +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Send-CWCToolboxItem.md b/Docs/Send-CWCToolboxItem.md new file mode 100644 index 0000000..fe91808 --- /dev/null +++ b/Docs/Send-CWCToolboxItem.md @@ -0,0 +1,128 @@ +--- +external help file: ConnectWiseControlAPI-help.xml +Module Name: ConnectWiseControlAPI +online version: https://github.com/christaylorcodes/ConnectWiseControlAPI +schema: 2.0.0 +--- + +# Send-CWCToolboxItem + +## SYNOPSIS +Queues a Toolbox item to run on a session. + +## SYNTAX + +``` +Send-CWCToolboxItem [-GUID] [-Name] [[-Group] ] + [-WhatIf] [-Confirm] [] +``` + +## DESCRIPTION +Queues a QueuedTool session event naming the Toolbox item. + +Credentials connections: PageService.AddSessionEvents; the user needs the RunSharedTool +permission in -Group. + +API secret connections: the RESTful API Manager extension's SendToolboxItemToSession; -Group is ignored. + +## EXAMPLES + +### EXAMPLE 1 +``` +Send-CWCToolboxItem -GUID $SessionID -Name 'Cleanup.ps1' +``` + +## PARAMETERS + +### -GUID +Session ID. + +```yaml +Type: Guid +Parameter Sets: (All) +Aliases: SessionID + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName) +Accept wildcard characters: False +``` + +### -Name +Toolbox item name as shown in the ScreenConnect Toolbox. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Group +Session group containing the session (credentials connections only). +Defaults to 'All Machines'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: All Machines +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 +Author: Chris Taylor + +## RELATED LINKS + +[https://github.com/christaylorcodes/ConnectWiseControlAPI](https://github.com/christaylorcodes/ConnectWiseControlAPI) + diff --git a/Docs/Update-CWCCustomProperty.md b/Docs/Update-CWCCustomProperty.md index 0f65d2e..2788bb2 100644 --- a/Docs/Update-CWCCustomProperty.md +++ b/Docs/Update-CWCCustomProperty.md @@ -13,8 +13,7 @@ Will update a custom property for a session. ## SYNTAX ``` -Update-CWCCustomProperty -GUID -Property [-Value ] [-Group ] [-WhatIf] - [-Confirm] [] +Update-CWCCustomProperty [-GUID] [-Property] [[-Value] ] [[-Group] ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -46,79 +45,79 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Group -Look for the session in these groups. +### -Property +The property number of the property you want to change. ```yaml -Type: String[] +Type: Int32 Parameter Sets: (All) Aliases: -Required: False -Position: Named -Default value: All Machines +Required: True +Position: 2 +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -Value +The value you want to set the property to. ```yaml -Type: SwitchParameter +Type: String Parameter Sets: (All) -Aliases: cf +Aliases: Required: False -Position: Named +Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -WhatIf -Shows what would happen if the cmdlet runs. The cmdlet is not run. +### -Group +Look for the session in these groups. ```yaml -Type: SwitchParameter +Type: String[] Parameter Sets: (All) -Aliases: wi +Aliases: Required: False -Position: Named -Default value: None +Position: 4 +Default value: All Machines Accept pipeline input: False Accept wildcard characters: False ``` -### -Property -The property number of the property you want to change. +### -WhatIf +Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml -Type: Int32 +Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: wi -Required: True +Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Value -The value you want to set the property to. +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml -Type: String +Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: cf Required: False Position: Named @@ -127,6 +126,7 @@ 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). diff --git a/Docs/Update-CWCSessionName.md b/Docs/Update-CWCSessionName.md index 9b8bcbb..8493453 100644 --- a/Docs/Update-CWCSessionName.md +++ b/Docs/Update-CWCSessionName.md @@ -13,8 +13,7 @@ Updates the name of a session. ## SYNTAX ``` -Update-CWCSessionName -GUID -NewName [-Group ] [-WhatIf] [-Confirm] - [] +Update-CWCSessionName [-GUID] [-NewName] [[-Group] ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -46,7 +45,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -61,7 +60,7 @@ Parameter Sets: (All) Aliases: Required: True -Position: Named +Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -71,24 +70,24 @@ Accept wildcard characters: False Group to look for the session in. ```yaml -Type: String +Type: String[] Parameter Sets: (All) Aliases: Required: False -Position: Named +Position: 3 Default value: All Machines Accept pipeline input: False Accept wildcard characters: False ``` -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -WhatIf +Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: SwitchParameter Parameter Sets: (All) -Aliases: cf +Aliases: wi Required: False Position: Named @@ -97,13 +96,13 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -WhatIf -Shows what would happen if the cmdlet runs. The cmdlet is not run. +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml Type: SwitchParameter Parameter Sets: (All) -Aliases: wi +Aliases: cf Required: False Position: Named @@ -112,6 +111,7 @@ 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). diff --git a/Docs/Update-CWCUser.md b/Docs/Update-CWCUser.md index d7156af..75d4418 100644 --- a/Docs/Update-CWCUser.md +++ b/Docs/Update-CWCUser.md @@ -13,9 +13,9 @@ Update properties of an internal user. ## SYNTAX ``` -Update-CWCUser [-UserToUpdate] [-NewUserName ] [-Password ] [[-OTP] ] - [[-DisplayName] ] [[-Email] ] [[-SecurityGroups] ] [[-ForcePassChange] ] - [-WhatIf] [-Confirm] [] +Update-CWCUser [-UserToUpdate] [[-NewUserName] ] [[-Password] ] + [[-OTP] ] [[-DisplayName] ] [[-Email] ] [[-SecurityGroups] ] + [[-ForcePassChange] ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -32,29 +32,44 @@ Updates the password for 'ctaylor' and forces a password change at next logon. ## PARAMETERS -### -Confirm -Prompts you for confirmation before running the cmdlet. +### -UserToUpdate +The user account you want to update. ```yaml -Type: SwitchParameter +Type: String Parameter Sets: (All) -Aliases: cf +Aliases: -Required: False -Position: Named +Required: True +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -DisplayName -The wanted display name for the user. +### -NewUserName +The new username of the user you are updating. ```yaml Type: String Parameter Sets: (All) Aliases: +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Password +The wanted password of the user. + +```yaml +Type: SecureString +Parameter Sets: (All) +Aliases: + Required: False Position: 3 Default value: None @@ -62,8 +77,8 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Email -The wanted email address for the user. +### -OTP +The wanted MFA option for the user. ```yaml Type: String @@ -77,23 +92,23 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -ForcePassChange -Force the user to change their password at next logon. +### -DisplayName +The wanted display name for the user. ```yaml -Type: Boolean +Type: String Parameter Sets: (All) Aliases: Required: False -Position: 6 +Position: 5 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -OTP -The wanted MFA option for the user. +### -Email +The wanted email address for the user. ```yaml Type: String @@ -101,7 +116,7 @@ Parameter Sets: (All) Aliases: Required: False -Position: 2 +Position: 6 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -116,22 +131,22 @@ Parameter Sets: (All) Aliases: Required: False -Position: 5 +Position: 7 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -UserToUpdate -The user account you want to update. +### -ForcePassChange +Force the user to change their password at next logon. ```yaml -Type: String +Type: Boolean Parameter Sets: (All) Aliases: -Required: True -Position: 0 +Required: False +Position: 8 Default value: None Accept pipeline input: False Accept wildcard characters: False @@ -153,13 +168,13 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -NewUserName -The new username of the user you are updating. +### -Confirm +Prompts you for confirmation before running the cmdlet. ```yaml -Type: String +Type: SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: cf Required: False Position: Named @@ -168,20 +183,6 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Password -The wanted password of the user. - -```yaml -Type: SecureString -Parameter Sets: (All) -Aliases: - -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). diff --git a/Examples/Basic.ps1 b/Examples/Basic.ps1 index a7fd157..8eb57f0 100644 --- a/Examples/Basic.ps1 +++ b/Examples/Basic.ps1 @@ -1,7 +1,7 @@ -# Your Control server URL -$Server = 'control.domain.com' +# Your ScreenConnect server URL +$Server = 'screenconnect.domain.com' -# Get Control credentials +# Get ScreenConnect credentials $Credentials = Get-Credential # Load module @@ -11,7 +11,7 @@ Import-Module 'ConnectWiseControlAPI' # Save connection info Connect-CWC -Server $Server -Credentials $Credentials -# Find this machine in Control +# Find this machine in ScreenConnect $Computer = Get-CWCSession -Type Access -Search $env:COMPUTERNAME -Limit 1 if(!$Computer){ return "Computer not found" } diff --git a/Examples/CreateNewUser.ps1 b/Examples/CreateNewUser.ps1 index a71b9cb..90a9b5a 100644 --- a/Examples/CreateNewUser.ps1 +++ b/Examples/CreateNewUser.ps1 @@ -1,7 +1,7 @@ -# Your Control server URL -$Server = 'control.domain.com' +# Your ScreenConnect server URL +$Server = 'screenconnect.domain.com' -# Get Control credentials +# Get ScreenConnect credentials $Credentials = Get-Credential # Load module diff --git a/Examples/ReinstallAutomate.ps1 b/Examples/ReinstallAutomate.ps1 index 53fa285..753dd19 100644 --- a/Examples/ReinstallAutomate.ps1 +++ b/Examples/ReinstallAutomate.ps1 @@ -1,7 +1,7 @@ -# Your Control server URL -$Server = 'control.domain.com' +# Your ScreenConnect server URL +$Server = 'screenconnect.domain.com' -# Get Control credentials +# Get ScreenConnect credentials $Credentials = Get-Credential # Load module @@ -11,7 +11,7 @@ Import-Module 'ConnectWiseControlAPI' # Save connection info Connect-CWC -Server $Server -Credentials $Credentials -# Find this machine in Control +# Find this machine in ScreenConnect $Computer = Get-CWCSession -Type Access -Search $env:COMPUTERNAME -Limit 1 if(!$Computer) {return "Computer not found"} @@ -24,7 +24,7 @@ $Reinstall = @{ TimeOut = 120000 # The command we want to issue to reinstall Automate Command = 'iwr -UseBasicParsing "https://bit.ly/LTPoSh" | iex;Redo-LTService -InstallerToken "MyToken123" -Backup' - # Tell Control we are pushing a PowerShell command + # Tell ScreenConnect we are pushing a PowerShell command PowerShell = $true } Invoke-CWCCommand @Reinstall diff --git a/Examples/RemoveRedundantSessions.ps1 b/Examples/RemoveRedundantSessions.ps1 index 440ef1d..4bc303a 100644 --- a/Examples/RemoveRedundantSessions.ps1 +++ b/Examples/RemoveRedundantSessions.ps1 @@ -5,10 +5,10 @@ You will need to get session details to further determine uniqueness. #> -# Your Control server URL -$Server = 'control.domain.com' +# Your ScreenConnect server URL +$Server = 'screenconnect.domain.com' -# Get Control credentials +# Get ScreenConnect credentials $Credentials = Get-Credential # Set GroupName to Search in @@ -27,11 +27,14 @@ Import-Module 'ConnectWiseControlAPI' Connect-CWC -Server $Server -Credentials $Credentials # Search for multiple sessions for the same machine, and collect all but the last connected one -$RedundantSessionColl = Get-CWCSession -Type Access -Group $GroupNameAll | +$RedundantSessionColl = Get-CWCSession -Type Access -Group $GroupName | Group-Object -Property Name | Where-Object -Property Count -gt 1 | ForEach-Object { - $_.Group | Sort-Object -Property LastConnectedEventTime | + # LastConnectedEventTime is seconds since the last connection: smallest first, so Skip 1 keeps + # the most recently connected session + # A session that never connected (no time) sorts last, so it is never the one kept + $_.Group | Sort-Object -Property { if ($null -eq $_.LastConnectedEventTime) { [double]::MaxValue } else { [double]$_.LastConnectedEventTime } } | Select-Object -Skip 1 } diff --git a/README.md b/README.md index 2d22e49..f2dcb79 100644 --- a/README.md +++ b/README.md @@ -2,19 +2,19 @@
logo
- ConnectWise Control API + ConnectWiseControlAPI

-This is a PowerShell wrapper for ConnectWise Control +A PowerShell wrapper for the ConnectWise ScreenConnect (formerly ConnectWise Control) web API

-[![Build status](https://ci.appveyor.com/api/projects/status/gkmh0h0234s1x7rt?svg=true)](https://ci.appveyor.com/project/christaylorcodes/ConnectWiseControlAPI) +[![CI](https://github.com/christaylorcodes/ConnectWiseControlAPI/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/christaylorcodes/ConnectWiseControlAPI/actions/workflows/ci.yml) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/8aa3633cda3d41d5baa5e9f595b8124f)](https://www.codacy.com/gh/christaylorcodes/ConnectWiseControlAPI/dashboard?utm_source=github.com&utm_medium=referral&utm_content=christaylorcodes/ConnectWiseControlAPI&utm_campaign=Badge_Grade) [![Gallery](https://img.shields.io/powershellgallery/v/ConnectWiseControlAPI?label=PS%20Gallery&logo=powershell&logoColor=white)](https://www.powershellgallery.com/packages/ConnectWiseControlAPI) [![Donate](https://img.shields.io/badge/$-donate-ff69b4.svg?maxAge=2592000&style=flat)](https://github.com/christaylorcodes/GitHub-Template/blob/main/DONATE.md) @@ -24,14 +24,17 @@ This is a PowerShell wrapper for ConnectWise Control List of Functions • Examples • Install • - Contribute • - Submit a Bug • - Request a Feature + Contribute • + Submit a Bug • + Request a Feature

-This module makes it easy to leverage PowerShell to automate tasks in Control. +This module makes it easy to leverage PowerShell to automate tasks in ScreenConnect. + +ConnectWise renamed Control back to ScreenConnect. The module keeps its name and its `CWC` command names, so +existing scripts keep working. @@ -45,20 +48,74 @@ Install-Module 'ConnectWiseControlAPI' >If you are having issues accessing the PowerShell Gallery check out my [repair script](https://github.com/christaylorcodes/Initialize-PSGallery) +### Upgrading from 0.4 + +0.5.0 changes some behaviour. Check your scripts before you update: + +* `Remove-CWCSession`, `Remove-CWCSessionNote` and `Remove-CWCHostFromSession` ask for confirmation by default. + Unattended scripts must add `-Confirm:$false`; without it they fail and remove nothing. +* `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. +* `Get-CWCAuditLog` covers the last 24 hours unless you pass `-StartDate` and `-EndDate`. +* A request that fails with HTTP 500 is repeated only when repeating is safe (reads and "set to value" updates). + +The full list is in the [changelog](CHANGELOG.md). ## Requirements -* Requires an account without MFA. Use a complex username and password. +* Requires your ScreenConnect server to use https. + +* One of three authentication methods: + + * **Credentials** (`Connect-CWC -Credentials`): an account without MFA. Use a complex username and + password. All functions except `Find-CWCSession` are available, limited by the account's permissions. + + * **Credentials with MFA** (`Connect-CWC -Credentials` plus `-Mfa`, `-OneTimeCode` or `-TotpSecret`): + an account that requires MFA, signed in the way the web page does. Same functions as credentials. + `-Mfa` asks for the code at the console (authenticator app, email or SMS). `-TotpSecret` computes the + authenticator-app code for unattended scripts from the account's TOTP secret (`ms:...` or Base32); + keep that secret in a secret store, and note that storing it next to the password makes MFA a + single factor. The login expires on the server; run `Connect-CWC` again before each batch of work + (a still-valid login is reused with one check call). + + ```powershell + Connect-CWC -Server 'screenconnect.example.com' -Credentials (Get-Credential) -Mfa + + # Unattended, with Microsoft.PowerShell.SecretManagement + Connect-CWC -Server 'screenconnect.example.com' -Credentials (Get-Secret 'CWC-Login') -TotpSecret (Get-Secret 'CWC-TOTP') + ``` + + * **API secret** (`Connect-CWC -ApiSecret`): install the **RESTful API Manager** extension and set its + `RESTfulAuthenticationSecret` setting to a long random value. Works when every account requires MFA. + Available functions: `Find-CWCSession`, `New-CWCSession`, `Get-CWCSessionDetail`, + `Update-CWCSessionName`, `Invoke-CWCCommand` (queues the command but does not return its output), + `Add-CWCSessionNote`, `Send-CWCSessionMessage`, `Send-CWCToolboxItem`. The secret bypasses + ScreenConnect's role permissions and acts on every session, so protect it like an administrator password. + If the extension's `RESTfulAllowedOrigin` setting is set, pass a matching `-Origin`. + + ```powershell + $Secret = Read-Host -AsSecureString -Prompt 'RESTful API secret' + Connect-CWC -Server 'screenconnect.example.com' -ApiSecret $Secret + Find-CWCSession -Filter "Name LIKE 'DESKTOP-*'" + ``` + +## Tutorials & Resources + +In-depth tutorials on [christaylor.codes](https://christaylor.codes): -* Requires your Control server to use https. +- [Introducing ConnectWiseControlAPI](https://christaylor.codes/powershell/msp/connectwisecontrolapi/2023/03/15/introducing-connectwisecontrolapi.html) - Module overview and key features +- [Getting Started with ConnectWiseControlAPI](https://christaylor.codes/powershell/msp/connectwisecontrolapi/2023/03/22/getting-started-connectwisecontrolapi.html) - Authentication, setup, and first commands +- [Cleaning Duplicate Control Sessions](https://christaylor.codes/powershell/msp/connectwisecontrolapi/2023/03/29/cleaning-duplicate-control-sessions.html) - Practical session management automation +- [Building PowerShell API Wrappers](https://christaylor.codes/powershell/development/connectwisecontrolapi/2023/12/05/building-powershell-api-wrappers.html) - Design patterns behind the module -## [Contributing](https://github.com/christaylorcodes/GitHub-Template/blob/main/CONTRIBUTING.md) +## [Contributing](.github/CONTRIBUTING.md) -If you use this project please give it a star and follow so you can get updated when new features are released. This also lets me know what projects are getting used and what ones I should dedicate more time to. If you want to get more involved please see the [contributing page](https://github.com/christaylorcodes/GitHub-Template/blob/main/CONTRIBUTING.md). Projects need all kinds of help even if you don't know how to code. +If you use this project please give it a star and follow so you can get updated when new features are released. This also lets me know what projects are getting used and what ones I should dedicate more time to. If you want to get more involved please see the [contributing page](.github/CONTRIBUTING.md). Projects need all kinds of help even if you don't know how to code. Want to share something you created using the module? Submit it to be featured as a Community Package. -## [Donating](https://github.com/christaylorcodes/GitHub-Template/blob/main/DONATE.md) +## Donating If you cant take time to contribute maybe you would like to help another way. diff --git a/RequiredModules.psd1 b/RequiredModules.psd1 new file mode 100644 index 0000000..2ba1060 --- /dev/null +++ b/RequiredModules.psd1 @@ -0,0 +1,28 @@ +@{ + PSDependOptions = @{ + AddToPath = $true + Target = 'output/RequiredModules' + Parameters = @{ + Repository = 'PSGallery' + } + } + + # Versions use NuGet range syntax (passed to Save-PSResource -Version): + # '[5.7.1,6.0.0)' = 5.7.1 or newer, below 6.0.0 (newest match wins) + # .build/required-modules.ps1 (task Assert_RequiredModule_Versions) fails the build if a resolved + # version falls outside its range. + + # Bounded: breaking changes have landed (or would land) in these + Sampler = '[0.120.1,0.121.0)' # 0.x: minor versions may break tasks + ModuleBuilder = '[3.2.18,4.0.0)' + # Exact: same versions as the env: block in .github/workflows/ci.yml, so a local run matches CI. + # Pester 5 and platyPS 0.14 (not the template's Pester 6 / PlatyPS 1.x): the suite runs on Windows + # PowerShell 5.1 and Build/Update-Help.ps1 produces MAML for Get-Help on 5.1. See AGENTS.md. + Pester = '5.7.1' + PSScriptAnalyzer = '1.24.0' + platyPS = '0.14.2' + + # Floating: low risk (build tooling only) + InvokeBuild = 'latest' + 'powershell-yaml' = 'latest' +} diff --git a/Resolve-Dependency.ps1 b/Resolve-Dependency.ps1 new file mode 100644 index 0000000..7fdf368 --- /dev/null +++ b/Resolve-Dependency.ps1 @@ -0,0 +1,1075 @@ +<# + .DESCRIPTION + Bootstrap script for PSDepend. + + .PARAMETER DependencyFile + Specifies the configuration file for the this script. The default value is + 'RequiredModules.psd1' relative to this script's path. + + .PARAMETER PSDependTarget + Path for PSDepend to be bootstrapped and save other dependencies. + Can also be CurrentUser or AllUsers if you wish to install the modules in + such scope. The default value is 'output/RequiredModules' relative to + this script's path. + + .PARAMETER Proxy + Specifies the URI to use for Proxy when attempting to bootstrap + PackageProvider and PowerShellGet. + + .PARAMETER ProxyCredential + Specifies the credential to contact the Proxy when provided. + + .PARAMETER Scope + Specifies the scope to bootstrap the PackageProvider and PSGet if not available. + THe default value is 'CurrentUser'. + + .PARAMETER Gallery + Specifies the gallery to use when bootstrapping PackageProvider, PSGet and + when calling PSDepend (can be overridden in Dependency files). The default + value is 'PSGallery'. + + .PARAMETER GalleryCredential + Specifies the credentials to use with the Gallery specified above. + + .PARAMETER AllowOldPowerShellGetModule + Allow you to use a locally installed version of PowerShellGet older than + 1.6.0 (not recommended). Default it will install the latest PowerShellGet + if an older version than 2.0 is detected. + + .PARAMETER MinimumPSDependVersion + Allow you to specify a minimum version fo PSDepend, if you're after specific + features. + + .PARAMETER AllowPrerelease + Not yet written. + + .PARAMETER WithYAML + Not yet written. + + .PARAMETER UseModuleFast + Specifies to use ModuleFast instead of PowerShellGet to resolve dependencies + faster. + + .PARAMETER ModuleFastBleedingEdge + Specifies to use ModuleFast code that is in the ModuleFast's main branch + in its GitHub repository. The parameter UseModuleFast must also be set to + true. + + .PARAMETER UsePSResourceGet + Specifies to use the new PSResourceGet module instead of the (now legacy) PowerShellGet module. + + .PARAMETER PSResourceGetVersion + String specifying the module version for PSResourceGet if the `UsePSResourceGet` switch is utilized. + + .NOTES + Load defaults for parameters values from Resolve-Dependency.psd1 if not + provided as parameter. +#> +[CmdletBinding()] +param +( + [Parameter()] + [System.String] + $DependencyFile = 'RequiredModules.psd1', + + [Parameter()] + [System.String] + $PSDependTarget = (Join-Path -Path $PSScriptRoot -ChildPath 'output/RequiredModules'), + + [Parameter()] + [System.Uri] + $Proxy, + + [Parameter()] + [System.Management.Automation.PSCredential] + $ProxyCredential, + + [Parameter()] + [ValidateSet('CurrentUser', 'AllUsers')] + [System.String] + $Scope = 'CurrentUser', + + [Parameter()] + [System.String] + $Gallery = 'PSGallery', + + [Parameter()] + [System.Management.Automation.PSCredential] + $GalleryCredential, + + [Parameter()] + [System.Management.Automation.SwitchParameter] + $AllowOldPowerShellGetModule, + + [Parameter()] + [System.String] + $MinimumPSDependVersion, + + [Parameter()] + [System.Management.Automation.SwitchParameter] + $AllowPrerelease, + + [Parameter()] + [System.Management.Automation.SwitchParameter] + $WithYAML, + + [Parameter()] + [System.Collections.Hashtable] + $RegisterGallery, + + [Parameter()] + [System.Management.Automation.SwitchParameter] + $UseModuleFast, + + [Parameter()] + [System.Management.Automation.SwitchParameter] + $ModuleFastBleedingEdge, + + [Parameter()] + [System.String] + $ModuleFastVersion, + + [Parameter()] + [System.Management.Automation.SwitchParameter] + $UsePSResourceGet, + + [Parameter()] + [System.String] + $PSResourceGetVersion, + + [Parameter()] + [System.Management.Automation.SwitchParameter] + $UsePowerShellGetCompatibilityModule, + + [Parameter()] + [System.String] + $UsePowerShellGetCompatibilityModuleVersion +) + +try +{ + if ($PSVersionTable.PSVersion.Major -le 5) + { + if (-not (Get-Command -Name 'Import-PowerShellDataFile' -ErrorAction 'SilentlyContinue')) + { + Import-Module -Name Microsoft.PowerShell.Utility -RequiredVersion '3.1.0.0' + } + } + + Write-Verbose -Message 'Importing Bootstrap default parameters from ''$PSScriptRoot/Resolve-Dependency.psd1''.' + + $resolveDependencyConfigPath = Join-Path -Path $PSScriptRoot -ChildPath '.\Resolve-Dependency.psd1' -Resolve -ErrorAction 'Stop' + + $resolveDependencyDefaults = Import-PowerShellDataFile -Path $resolveDependencyConfigPath + + $parameterToDefault = $MyInvocation.MyCommand.ParameterSets.Where{ $_.Name -eq $PSCmdlet.ParameterSetName }.Parameters.Keys + + if ($parameterToDefault.Count -eq 0) + { + $parameterToDefault = $MyInvocation.MyCommand.Parameters.Keys + } + + # Set the parameters available in the Parameter Set, or it's not possible to choose yet, so all parameters are an option. + foreach ($parameterName in $parameterToDefault) + { + if (-not $PSBoundParameters.Keys.Contains($parameterName) -and $resolveDependencyDefaults.ContainsKey($parameterName)) + { + Write-Verbose -Message "Setting parameter '$parameterName' to value '$($resolveDependencyDefaults[$parameterName])'." + + try + { + $variableValue = $resolveDependencyDefaults[$parameterName] + + if ($variableValue -is [System.String]) + { + $variableValue = $ExecutionContext.InvokeCommand.ExpandString($variableValue) + } + + $PSBoundParameters.Add($parameterName, $variableValue) + + Set-Variable -Name $parameterName -Value $variableValue -Force -ErrorAction 'SilentlyContinue' + } + catch + { + Write-Verbose -Message "Error adding default for $parameterName : $($_.Exception.Message)." + } + } + } +} +catch +{ + Write-Warning -Message "Error attempting to import Bootstrap's default parameters from '$resolveDependencyConfigPath': $($_.Exception.Message)." +} + +# Handle when both ModuleFast and PSResourceGet is configured or/and passed as parameter. +if ($UseModuleFast -and $UsePSResourceGet) +{ + Write-Information -MessageData 'Both ModuleFast and PSResourceGet is configured or/and passed as parameter.' -InformationAction 'Continue' + + if ($PSVersionTable.PSVersion -ge '7.2') + { + $UsePSResourceGet = $false + + Write-Information -MessageData 'PowerShell 7.2 or higher being used, prefer ModuleFast over PSResourceGet.' -InformationAction 'Continue' + } + else + { + $UseModuleFast = $false + + Write-Information -MessageData 'Windows PowerShell or PowerShell <=7.1 is being used, prefer PSResourceGet since ModuleFast is not supported on this version of PowerShell.' -InformationAction 'Continue' + } +} + +# Only bootstrap ModuleFast if it is not already imported. +if ($UseModuleFast -and -not (Get-Module -Name 'ModuleFast')) +{ + try + { + $moduleFastBootstrapScriptBlockParameters = @{} + + if ($ModuleFastBleedingEdge) + { + Write-Information -MessageData 'ModuleFast is configured to use Bleeding Edge (directly from ModuleFast''s main branch).' -InformationAction 'Continue' + + $moduleFastBootstrapScriptBlockParameters.UseMain = $true + } + elseif ($ModuleFastVersion) + { + if ($ModuleFastVersion -notmatch 'v') + { + $ModuleFastVersion = 'v{0}' -f $ModuleFastVersion + } + + Write-Information -MessageData ('ModuleFast is configured to use version {0}.' -f $ModuleFastVersion) -InformationAction 'Continue' + + $moduleFastBootstrapScriptBlockParameters.Release = $ModuleFastVersion + } + else + { + Write-Information -MessageData 'ModuleFast is configured to use latest released version.' -InformationAction 'Continue' + } + + $moduleFastBootstrapUri = 'bit.ly/modulefast' # cSpell: disable-line + + Write-Debug -Message ('Using bootstrap script at {0}' -f $moduleFastBootstrapUri) + + $invokeWebRequestParameters = @{ + Uri = $moduleFastBootstrapUri + ErrorAction = 'Stop' + } + + $moduleFastBootstrapScript = Invoke-WebRequest @invokeWebRequestParameters + + $moduleFastBootstrapScriptBlock = [ScriptBlock]::Create($moduleFastBootstrapScript) + + & $moduleFastBootstrapScriptBlock @moduleFastBootstrapScriptBlockParameters + } + catch + { + Write-Warning -Message ('ModuleFast could not be bootstrapped. Reverting to PSResourceGet. Error: {0}' -f $_.Exception.Message) + + $UseModuleFast = $false + $UsePSResourceGet = $true + } +} + +if ($UsePSResourceGet) +{ + $psResourceGetModuleName = 'Microsoft.PowerShell.PSResourceGet' + + # If PSResourceGet was used prior it will be locked and we can't replace it. + if ((Test-Path -Path "$PSDependTarget/$psResourceGetModuleName" -PathType 'Container') -and (Get-Module -Name $psResourceGetModuleName)) + { + Write-Information -MessageData ('{0} is already bootstrapped and imported into the session. If there is a need to refresh the module, open a new session and resolve dependencies again.' -f $psResourceGetModuleName) -InformationAction 'Continue' + } + else + { + Write-Debug -Message ('{0} do not exist, saving the module to RequiredModules.' -f $psResourceGetModuleName) + + $psResourceGetDownloaded = $false + + try + { + if (-not $PSResourceGetVersion) + { + # Default to latest version if no version is passed in parameter or specified in configuration. + $psResourceGetUri = "https://www.powershellgallery.com/api/v2/package/$psResourceGetModuleName" + } + else + { + $psResourceGetUri = "https://www.powershellgallery.com/api/v2/package/$psResourceGetModuleName/$PSResourceGetVersion" + } + + $invokeWebRequestParameters = @{ + # TODO: Should support proxy parameters passed to the script. + Uri = $psResourceGetUri + OutFile = "$PSDependTarget/$psResourceGetModuleName.nupkg" # cSpell: ignore nupkg + ErrorAction = 'Stop' + } + + $previousProgressPreference = $ProgressPreference + $ProgressPreference = 'SilentlyContinue' + + # Bootstrapping Microsoft.PowerShell.PSResourceGet. + Invoke-WebRequest @invokeWebRequestParameters + + $ProgressPreference = $previousProgressPreference + + $psResourceGetDownloaded = $true + } + catch + { + Write-Warning -Message ('{0} could not be bootstrapped. Reverting to PowerShellGet. Error: {1}' -f $psResourceGetModuleName, $_.Exception.Message) + } + + $UsePSResourceGet = $false + + if ($psResourceGetDownloaded) + { + # On Windows PowerShell the command Expand-Archive do not like .nupkg as a zip archive extension. + $zipFileName = ((Split-Path -Path $invokeWebRequestParameters.OutFile -Leaf) -replace 'nupkg', 'zip') + + $renameItemParameters = @{ + Path = $invokeWebRequestParameters.OutFile + NewName = $zipFileName + Force = $true + } + + Rename-Item @renameItemParameters + + $psResourceGetZipArchivePath = Join-Path -Path (Split-Path -Path $invokeWebRequestParameters.OutFile -Parent) -ChildPath $zipFileName + + $expandArchiveParameters = @{ + Path = $psResourceGetZipArchivePath + DestinationPath = "$PSDependTarget/$psResourceGetModuleName" + Force = $true + } + + Microsoft.PowerShell.Archive\Expand-Archive @expandArchiveParameters + + Remove-Item -Path $psResourceGetZipArchivePath + + Import-Module -Name $expandArchiveParameters.DestinationPath -Force + + # Successfully bootstrapped PSResourceGet, so let's use it. + $UsePSResourceGet = $true + } + } + + if ($UsePSResourceGet) + { + $psResourceGetModule = Get-Module -Name $psResourceGetModuleName + + $psResourceGetModuleVersion = $psResourceGetModule.Version.ToString() + + if ($psResourceGetModule.PrivateData.PSData.Prerelease) + { + $psResourceGetModuleVersion += '-{0}' -f $psResourceGetModule.PrivateData.PSData.Prerelease + } + + Write-Information -MessageData ('Using {0} v{1}.' -f $psResourceGetModuleName, $psResourceGetModuleVersion) -InformationAction 'Continue' + + if ($UsePowerShellGetCompatibilityModule) + { + $savePowerShellGetParameters = @{ + Name = 'PowerShellGet' + Path = $PSDependTarget + Repository = 'PSGallery' + TrustRepository = $true + } + + if ($UsePowerShellGetCompatibilityModuleVersion) + { + $savePowerShellGetParameters.Version = $UsePowerShellGetCompatibilityModuleVersion + + # Check if the version is a prerelease. + if ($UsePowerShellGetCompatibilityModuleVersion -match '\d+\.\d+\.\d+-.*') + { + $savePowerShellGetParameters.Prerelease = $true + } + } + + Save-PSResource @savePowerShellGetParameters + + Import-Module -Name "$PSDependTarget/PowerShellGet" + } + } +} + +# Check if legacy PowerShellGet and PSDepend must be bootstrapped. +if (-not ($UseModuleFast -or $UsePSResourceGet)) +{ + if ($PSVersionTable.PSVersion.Major -le 5) + { + <# + Making sure the imported PackageManagement module is not from PS7 module + path. The VSCode PS extension is changing the $env:PSModulePath and + prioritize the PS7 path. This is an issue with PowerShellGet because + it loads an old version if available (or fail to load latest). + #> + Get-Module -ListAvailable PackageManagement | + Where-Object -Property 'ModuleBase' -NotMatch 'powershell.7' | + Select-Object -First 1 | + Import-Module -Force + } + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 0 -CurrentOperation 'NuGet Bootstrap' + + $importModuleParameters = @{ + Name = 'PowerShellGet' + MinimumVersion = '2.0' + MaximumVersion = '2.8.999' + ErrorAction = 'SilentlyContinue' + PassThru = $true + } + + if ($AllowOldPowerShellGetModule) + { + $importModuleParameters.Remove('MinimumVersion') + } + + $powerShellGetModule = Import-Module @importModuleParameters + + # Install the package provider if it is not available. + $nuGetProvider = Get-PackageProvider -Name 'NuGet' -ListAvailable -ErrorAction 'SilentlyContinue' | + Select-Object -First 1 + + if (-not $powerShellGetModule -and -not $nuGetProvider) + { + $providerBootstrapParameters = @{ + Name = 'NuGet' + Force = $true + ForceBootstrap = $true + ErrorAction = 'Stop' + Scope = $Scope + } + + switch ($PSBoundParameters.Keys) + { + 'Proxy' + { + $providerBootstrapParameters.Add('Proxy', $Proxy) + } + + 'ProxyCredential' + { + $providerBootstrapParameters.Add('ProxyCredential', $ProxyCredential) + } + + 'AllowPrerelease' + { + $providerBootstrapParameters.Add('AllowPrerelease', $AllowPrerelease) + } + } + + Write-Information -MessageData 'Bootstrap: Installing NuGet Package Provider from the web (Make sure Microsoft addresses/ranges are allowed).' + + $null = Install-PackageProvider @providerBootstrapParameters + + $nuGetProvider = Get-PackageProvider -Name 'NuGet' -ListAvailable | Select-Object -First 1 + + $nuGetProviderVersion = $nuGetProvider.Version.ToString() + + Write-Information -MessageData "Bootstrap: Importing NuGet Package Provider version $nuGetProviderVersion to current session." + + $Null = Import-PackageProvider -Name 'NuGet' -RequiredVersion $nuGetProviderVersion -Force + } + + if ($RegisterGallery) + { + if ($RegisterGallery.ContainsKey('Name') -and -not [System.String]::IsNullOrEmpty($RegisterGallery.Name)) + { + $Gallery = $RegisterGallery.Name + } + else + { + $RegisterGallery.Name = $Gallery + } + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 7 -CurrentOperation "Verifying private package repository '$Gallery'" -Completed + + $previousRegisteredRepository = Get-PSRepository -Name $Gallery -ErrorAction 'SilentlyContinue' + + if ($previousRegisteredRepository.SourceLocation -ne $RegisterGallery.SourceLocation) + { + if ($previousRegisteredRepository) + { + Write-Progress -Activity 'Bootstrap:' -PercentComplete 9 -CurrentOperation "Re-registrering private package repository '$Gallery'" -Completed + + Unregister-PSRepository -Name $Gallery + + $unregisteredPreviousRepository = $true + } + else + { + Write-Progress -Activity 'Bootstrap:' -PercentComplete 9 -CurrentOperation "Registering private package repository '$Gallery'" -Completed + } + + Register-PSRepository @RegisterGallery + } + } + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 10 -CurrentOperation "Ensuring Gallery $Gallery is trusted" + + # Fail if the given PSGallery is not registered. + $previousGalleryInstallationPolicy = (Get-PSRepository -Name $Gallery -ErrorAction 'Stop').Trusted + + $updatedGalleryInstallationPolicy = $false + + if ($previousGalleryInstallationPolicy -ne $true) + { + $updatedGalleryInstallationPolicy = $true + + # Only change policy if the repository is not trusted + Set-PSRepository -Name $Gallery -InstallationPolicy 'Trusted' -ErrorAction 'Ignore' + } +} + +try +{ + # Check if legacy PowerShellGet and PSDepend must be used. + if (-not ($UseModuleFast -or $UsePSResourceGet)) + { + Write-Progress -Activity 'Bootstrap:' -PercentComplete 25 -CurrentOperation 'Checking PowerShellGet' + + # Ensure the module is loaded and retrieve the version you have. + $powerShellGetVersion = (Import-Module -Name 'PowerShellGet' -PassThru -ErrorAction 'SilentlyContinue').Version + + Write-Verbose -Message "Bootstrap: The PowerShellGet version is $powerShellGetVersion" + + # Versions below 2.0 are considered old, unreliable & not recommended + if (-not $powerShellGetVersion -or ($powerShellGetVersion -lt [System.Version] '2.0' -and -not $AllowOldPowerShellGetModule)) + { + Write-Progress -Activity 'Bootstrap:' -PercentComplete 40 -CurrentOperation 'Fetching newer version of PowerShellGet' + + # PowerShellGet module not found, installing or saving it. + if ($PSDependTarget -in 'CurrentUser', 'AllUsers') + { + Write-Debug -Message "PowerShellGet module not found. Attempting to install from Gallery $Gallery." + + Write-Warning -Message "Installing PowerShellGet in $PSDependTarget Scope." + + $installPowerShellGetParameters = @{ + Name = 'PowerShellGet' + Force = $true + SkipPublisherCheck = $true + AllowClobber = $true + Scope = $Scope + Repository = $Gallery + MaximumVersion = '2.8.999' + } + + switch ($PSBoundParameters.Keys) + { + 'Proxy' + { + $installPowerShellGetParameters.Add('Proxy', $Proxy) + } + + 'ProxyCredential' + { + $installPowerShellGetParameters.Add('ProxyCredential', $ProxyCredential) + } + + 'GalleryCredential' + { + $installPowerShellGetParameters.Add('Credential', $GalleryCredential) + } + } + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 60 -CurrentOperation 'Installing newer version of PowerShellGet' + + Install-Module @installPowerShellGetParameters + } + else + { + Write-Debug -Message "PowerShellGet module not found. Attempting to Save from Gallery $Gallery to $PSDependTarget" + + $saveModuleParameters = @{ + Name = 'PowerShellGet' + Repository = $Gallery + Path = $PSDependTarget + Force = $true + MaximumVersion = '2.8.999' + } + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 60 -CurrentOperation "Saving PowerShellGet from $Gallery to $Scope" + + Save-Module @saveModuleParameters + } + + Write-Debug -Message 'Removing previous versions of PowerShellGet and PackageManagement from session' + + Get-Module -Name 'PowerShellGet' -All | Remove-Module -Force -ErrorAction 'SilentlyContinue' + Get-Module -Name 'PackageManagement' -All | Remove-Module -Force + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 65 -CurrentOperation 'Loading latest version of PowerShellGet' + + Write-Debug -Message 'Importing latest PowerShellGet and PackageManagement versions into session' + + if ($AllowOldPowerShellGetModule) + { + $powerShellGetModule = Import-Module -Name 'PowerShellGet' -Force -PassThru + } + else + { + Import-Module -Name 'PackageManagement' -MinimumVersion '1.4.8.1' -Force + + $powerShellGetModule = Import-Module -Name 'PowerShellGet' -MinimumVersion '2.2.5' -Force -PassThru + } + + $powerShellGetVersion = $powerShellGetModule.Version.ToString() + + Write-Information -MessageData "Bootstrap: PowerShellGet version loaded is $powerShellGetVersion" + } + + # Try to import the PSDepend module from the available modules. + $getModuleParameters = @{ + Name = 'PSDepend' + ListAvailable = $true + } + + $psDependModule = Get-Module @getModuleParameters + + if ($PSBoundParameters.ContainsKey('MinimumPSDependVersion')) + { + try + { + $psDependModule = $psDependModule | Where-Object -FilterScript { $_.Version -ge $MinimumPSDependVersion } + } + catch + { + throw ('There was a problem finding the minimum version of PSDepend. Error: {0}' -f $_) + } + } + + if (-not $psDependModule) + { + Write-Debug -Message 'PSDepend module not found.' + + # PSDepend module not found, installing or saving it. + if ($PSDependTarget -in 'CurrentUser', 'AllUsers') + { + Write-Debug -Message "Attempting to install from Gallery '$Gallery'." + + Write-Warning -Message "Installing PSDepend in $PSDependTarget Scope." + + $installPSDependParameters = @{ + Name = 'PSDepend' + Repository = $Gallery + Force = $true + Scope = $PSDependTarget + SkipPublisherCheck = $true + AllowClobber = $true + } + + if ($MinimumPSDependVersion) + { + $installPSDependParameters.Add('MinimumVersion', $MinimumPSDependVersion) + } + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 75 -CurrentOperation "Installing PSDepend from $Gallery" + + Install-Module @installPSDependParameters + } + else + { + Write-Debug -Message "Attempting to Save from Gallery $Gallery to $PSDependTarget" + + $saveModuleParameters = @{ + Name = 'PSDepend' + Repository = $Gallery + Path = $PSDependTarget + Force = $true + } + + if ($MinimumPSDependVersion) + { + $saveModuleParameters.add('MinimumVersion', $MinimumPSDependVersion) + } + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 75 -CurrentOperation "Saving PSDepend from $Gallery to $PSDependTarget" + + Save-Module @saveModuleParameters + } + } + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 80 -CurrentOperation 'Importing PSDepend' + + $importModulePSDependParameters = @{ + Name = 'PSDepend' + ErrorAction = 'Stop' + Force = $true + } + + if ($PSBoundParameters.ContainsKey('MinimumPSDependVersion')) + { + $importModulePSDependParameters.Add('MinimumVersion', $MinimumPSDependVersion) + } + + # We should have successfully bootstrapped PSDepend. Fail if not available. + $null = Import-Module @importModulePSDependParameters + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 81 -CurrentOperation 'Invoke PSDepend' + + if ($WithYAML) + { + Write-Progress -Activity 'Bootstrap:' -PercentComplete 82 -CurrentOperation 'Verifying PowerShell module PowerShell-Yaml' + + if (-not (Get-Module -ListAvailable -Name 'PowerShell-Yaml')) + { + Write-Progress -Activity 'Bootstrap:' -PercentComplete 85 -CurrentOperation 'Installing PowerShell module PowerShell-Yaml' + + Write-Verbose -Message "PowerShell-Yaml module not found. Attempting to Save from Gallery '$Gallery' to '$PSDependTarget'." + + $SaveModuleParam = @{ + Name = 'PowerShell-Yaml' + Repository = $Gallery + Path = $PSDependTarget + Force = $true + } + + Save-Module @SaveModuleParam + } + else + { + Write-Verbose -Message 'PowerShell-Yaml is already available' + } + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 88 -CurrentOperation 'Importing PowerShell module PowerShell-Yaml' + } + } + + if (Test-Path -Path $DependencyFile) + { + if ($UseModuleFast -or $UsePSResourceGet) + { + $requiredModules = Import-PowerShellDataFile -Path $DependencyFile + + $requiredModules = $requiredModules.GetEnumerator() | + Where-Object -FilterScript { $_.Name -ne 'PSDependOptions' } + + if ($UseModuleFast) + { + Write-Progress -Activity 'Bootstrap:' -PercentComplete 90 -CurrentOperation 'Invoking ModuleFast' + + Write-Progress -Activity 'ModuleFast:' -PercentComplete 0 -CurrentOperation 'Restoring Build Dependencies' + + $modulesToSave = @( + 'PSDepend' # Always include PSDepend for backward compatibility. + ) + + if ($WithYAML) + { + $modulesToSave += 'PowerShell-Yaml' + } + + if ($UsePowerShellGetCompatibilityModule) + { + Write-Debug -Message 'PowerShellGet compatibility module is configured to be used.' + + # This is needed to ensure that the PowerShellGet compatibility module works. + $psResourceGetModuleName = 'Microsoft.PowerShell.PSResourceGet' + + if ($PSResourceGetVersion) + { + $modulesToSave += ('{0}:[{1}]' -f $psResourceGetModuleName, $PSResourceGetVersion) + } + else + { + $modulesToSave += $psResourceGetModuleName + } + + $powerShellGetCompatibilityModuleName = 'PowerShellGet' + + if ($UsePowerShellGetCompatibilityModuleVersion) + { + $modulesToSave += ('{0}:[{1}]' -f $powerShellGetCompatibilityModuleName, $UsePowerShellGetCompatibilityModuleVersion) + } + else + { + $modulesToSave += $powerShellGetCompatibilityModuleName + } + } + + foreach ($requiredModule in $requiredModules) + { + # If the RequiredModules.psd1 entry is an Hashtable then special handling is needed. + if ($requiredModule.Value -is [System.Collections.Hashtable]) + { + if (-not $requiredModule.Value.Version) + { + $requiredModuleVersion = 'latest' + } + else + { + $requiredModuleVersion = $requiredModule.Value.Version + } + + if ($requiredModuleVersion -eq 'latest') + { + $moduleNameSuffix = '' + + if ($requiredModule.Value.Parameters.AllowPrerelease -eq $true) + { + <# + Adding '!' to the module name indicate to ModuleFast + that is should also evaluate pre-releases. + #> + $moduleNameSuffix = '!' + } + + $modulesToSave += ('{0}{1}' -f $requiredModule.Name, $moduleNameSuffix) + } + else + { + $modulesToSave += ('{0}:[{1}]' -f $requiredModule.Name, $requiredModuleVersion) + } + } + else + { + if ($requiredModule.Value -eq 'latest') + { + $modulesToSave += $requiredModule.Name + } + else + { + # Handle different nuget version operators already present. + if ($requiredModule.Value -match '[!|:|[|(|,|>|<|=]') + { + $modulesToSave += ('{0}{1}' -f $requiredModule.Name, $requiredModule.Value) + } + else + { + # Assuming the version is a fixed version. + $modulesToSave += ('{0}:[{1}]' -f $requiredModule.Name, $requiredModule.Value) + } + } + } + } + + Write-Debug -Message ("Required modules to retrieve plan for:`n{0}" -f ($modulesToSave | Out-String)) + + $installModuleFastParameters = @{ + Destination = $PSDependTarget + DestinationOnly = $true + NoPSModulePathUpdate = $true + NoProfileUpdate = $true + Update = $true + Confirm = $false + } + + $moduleFastPlan = Install-ModuleFast -Specification $modulesToSave -Plan @installModuleFastParameters + + Write-Debug -Message ("Missing modules that need to be saved:`n{0}" -f ($moduleFastPlan | Out-String)) + + if ($moduleFastPlan) + { + # Clear all modules in plan from the current session so they can be fetched again. + try + { + $moduleFastPlan.Name | Get-Module | Remove-Module -Force + $moduleFastPlan | Install-ModuleFast @installModuleFastParameters + } + catch + { + Write-Warning -Message 'ModuleFast could not save one or more dependencies. Retrying...' + try + { + $moduleFastPlan.Name | Get-Module | Remove-Module -Force + $moduleFastPlan | Install-ModuleFast @installModuleFastParameters + } + catch + { + Write-Error 'ModuleFast could not save one or more dependencies even after a retry.' + } + } + } + else + { + Write-Verbose -Message 'All required modules were already up to date' + } + + Write-Progress -Activity 'ModuleFast:' -PercentComplete 100 -CurrentOperation 'Dependencies restored' -Completed + } + + if ($UsePSResourceGet) + { + Write-Progress -Activity 'Bootstrap:' -PercentComplete 90 -CurrentOperation 'Invoking PSResourceGet' + + $modulesToSave = @( + @{ + Name = 'PSDepend' # Always include PSDepend for backward compatibility. + } + ) + + if ($WithYAML) + { + $modulesToSave += @{ + Name = 'PowerShell-Yaml' + } + } + + # Prepare hashtable that can be concatenated to the Save-PSResource parameters. + foreach ($requiredModule in $requiredModules) + { + # If the RequiredModules.psd1 entry is an Hashtable then special handling is needed. + if ($requiredModule.Value -is [System.Collections.Hashtable]) + { + $saveModuleHashtable = @{ + Name = $requiredModule.Name + } + + if ($requiredModule.Value.Version -and $requiredModule.Value.Version -ne 'latest') + { + $saveModuleHashtable.Version = $requiredModule.Value.Version + } + + if ($requiredModule.Value.Parameters.AllowPrerelease -eq $true) + { + $saveModuleHashtable.Prerelease = $true + } + + $modulesToSave += $saveModuleHashtable + } + else + { + if ($requiredModule.Value -eq 'latest') + { + $modulesToSave += @{ + Name = $requiredModule.Name + } + } + else + { + $modulesToSave += @{ + Name = $requiredModule.Name + Version = $requiredModule.Value + } + } + } + } + + $percentagePerModule = [System.Math]::Floor(100 / $modulesToSave.Length) + + $progressPercentage = 0 + + Write-Progress -Activity 'PSResourceGet:' -PercentComplete $progressPercentage -CurrentOperation 'Restoring Build Dependencies' + + foreach ($currentModule in $modulesToSave) + { + Write-Progress -Activity 'PSResourceGet:' -PercentComplete $progressPercentage -CurrentOperation 'Restoring Build Dependencies' -Status ('Saving module {0}' -f $savePSResourceParameters.Name) + + $savePSResourceParameters = @{ + Path = $PSDependTarget + TrustRepository = $true + Confirm = $false + } + + # Concatenate the module parameters to the Save-PSResource parameters. + $savePSResourceParameters += $currentModule + + # Modules that Sampler depend on that cannot be refreshed without a new session. + $skipModule = @('PowerShell-Yaml') + + if ($savePSResourceParameters.Name -in $skipModule -and (Get-Module -Name $savePSResourceParameters.Name)) + { + Write-Progress -Activity 'PSResourceGet:' -PercentComplete $progressPercentage -CurrentOperation 'Restoring Build Dependencies' -Status ('Skipping module {0}' -f $savePSResourceParameters.Name) + + Write-Information -MessageData ('Skipping the module {0} since it cannot be refresh while loaded into the session. To refresh the module open a new session and resolve dependencies again.' -f $savePSResourceParameters.Name) -InformationAction 'Continue' + } + else + { + # Clear all module from the current session so any new version fetched will be re-imported. + Get-Module -Name $savePSResourceParameters.Name | Remove-Module -Force + + Save-PSResource @savePSResourceParameters -ErrorVariable 'savePSResourceError' + + if ($savePSResourceError) + { + Write-Warning -Message 'Save-PSResource could not save (replace) one or more dependencies. This can be due to the module is loaded into the session (and referencing assemblies). Close the current session and open a new session and try again.' + } + } + + $progressPercentage += $percentagePerModule + } + + Write-Progress -Activity 'PSResourceGet:' -PercentComplete 100 -CurrentOperation 'Dependencies restored' -Completed + } + } + else + { + Write-Progress -Activity 'Bootstrap:' -PercentComplete 90 -CurrentOperation 'Invoking PSDepend' + + Write-Progress -Activity 'PSDepend:' -PercentComplete 0 -CurrentOperation 'Restoring Build Dependencies' + + $psDependParameters = @{ + Force = $true + Path = $DependencyFile + } + + # TODO: Handle when the Dependency file is in YAML, and -WithYAML is specified. + Invoke-PSDepend @psDependParameters + + Write-Progress -Activity 'PSDepend:' -PercentComplete 100 -CurrentOperation 'Dependencies restored' -Completed + } + } + else + { + Write-Warning -Message "The dependency file '$DependencyFile' could not be found." + } + + Write-Progress -Activity 'Bootstrap:' -PercentComplete 100 -CurrentOperation 'Bootstrap complete' -Completed +} +finally +{ + if ($RegisterGallery) + { + Write-Verbose -Message "Removing private package repository '$Gallery'." + Unregister-PSRepository -Name $Gallery + } + + if ($unregisteredPreviousRepository) + { + Write-Verbose -Message "Reverting private package repository '$Gallery' to previous location URI:s." + + $registerPSRepositoryParameters = @{ + Name = $previousRegisteredRepository.Name + InstallationPolicy = $previousRegisteredRepository.InstallationPolicy + } + + if ($previousRegisteredRepository.SourceLocation) + { + $registerPSRepositoryParameters.SourceLocation = $previousRegisteredRepository.SourceLocation + } + + if ($previousRegisteredRepository.PublishLocation) + { + $registerPSRepositoryParameters.PublishLocation = $previousRegisteredRepository.PublishLocation + } + + if ($previousRegisteredRepository.ScriptSourceLocation) + { + $registerPSRepositoryParameters.ScriptSourceLocation = $previousRegisteredRepository.ScriptSourceLocation + } + + if ($previousRegisteredRepository.ScriptPublishLocation) + { + $registerPSRepositoryParameters.ScriptPublishLocation = $previousRegisteredRepository.ScriptPublishLocation + } + + Register-PSRepository @registerPSRepositoryParameters + } + + if ($updatedGalleryInstallationPolicy -eq $true -and $previousGalleryInstallationPolicy -ne $true) + { + # Only try to revert installation policy if the repository exist + if ((Get-PSRepository -Name $Gallery -ErrorAction 'SilentlyContinue')) + { + # Reverting the Installation Policy for the given gallery if it was not already trusted + Set-PSRepository -Name $Gallery -InstallationPolicy 'Untrusted' + } + } + + Write-Verbose -Message 'Project Bootstrapped, returning to Invoke-Build.' +} diff --git a/Resolve-Dependency.psd1 b/Resolve-Dependency.psd1 new file mode 100644 index 0000000..628fa2a --- /dev/null +++ b/Resolve-Dependency.psd1 @@ -0,0 +1,10 @@ +@{ + Gallery = 'PSGallery' + AllowPrerelease = $false + WithYAML = $true + + # Resolve dependencies with PSResourceGet (ships with PowerShell 7.4+) instead of + # the legacy PowerShellGet v2. Version ranges in RequiredModules.psd1 require this. + UsePSResourceGet = $true + PSResourceGetVersion = '1.2.0' +} diff --git a/Tests/ConnectWiseControlAPI.Live.Tests.ps1 b/Tests/ConnectWiseControlAPI.Live.Tests.ps1 new file mode 100644 index 0000000..7b0c44e --- /dev/null +++ b/Tests/ConnectWiseControlAPI.Live.Tests.ps1 @@ -0,0 +1,295 @@ +#Requires -Module Pester + +<# +.SYNOPSIS + Live integration tests against a real ConnectWise ScreenConnect server. + +.DESCRIPTION + Read-only tests that verify actual API connectivity, authentication, + and response parsing against a live CWC instance. No data is modified. + + Requires environment variables: + $env:CWC_SERVER - CWC server hostname (e.g. 'screenconnect.example.com') + $env:CWC_USER - Username for Basic auth + $env:CWC_PASSWORD - Password for Basic auth + + All tests are skipped when environment variables are not set. + + The module connects once in the top-level BeforeAll and shared read-only + data (Access sessions) is fetched once there. Per-endpoint data is fetched + once in each Describe's BeforeAll and the It blocks assert on the cached + results, keeping the number of network calls to a minimum. + +.NOTES + Run with: + Invoke-Pester Tests\ConnectWiseControlAPI.Live.Tests.ps1 -Output Detailed + + Set environment variables first: + $env:CWC_SERVER = 'screenconnect.example.com' + $env:CWC_USER = 'apiuser' + $env:CWC_PASSWORD = 'password' +#> + +BeforeDiscovery { + $script:HasCredentials = [bool]($env:CWC_SERVER -and $env:CWC_USER -and $env:CWC_PASSWORD) +} + +BeforeAll { + $ModuleRoot = Split-Path -Parent $PSScriptRoot + Import-Module (& (Join-Path $PSScriptRoot 'TestHelpers\Resolve-TestModuleManifest.ps1')) -Force + + # Variables set in BeforeDiscovery do not survive into the Run phase (Pester 5), + # so the credential check must be re-evaluated here for the run-time code paths. + $script:HasCredentials = [bool]($env:CWC_SERVER -and $env:CWC_USER -and $env:CWC_PASSWORD) + if ($script:HasCredentials) { + $script:TestServer = $env:CWC_SERVER + $script:TestCredentials = [PSCredential]::new( + $env:CWC_USER, + ($env:CWC_PASSWORD | ConvertTo-SecureString -AsPlainText -Force) + ) + + # Single connection shared by every Describe + Connect-CWC -Server $script:TestServer -Credentials $script:TestCredentials -Force + + # Access sessions are used by the Session, Session Detail and Last Contact tests + $script:AccessSessionsError = $null + try { + $script:AccessSessions = Get-CWCSession -Type 'Access' -Limit 5 + } + catch { + $script:AccessSessionsError = $_ + } + $script:HasSessions = @($script:AccessSessions | Where-Object { $null -ne $_ }).Count -gt 0 + if ($script:HasSessions) { + $script:TestSessionGuid = @($script:AccessSessions)[0].SessionID + } + } +} + +AfterAll { + # Runs once, after every Describe in this file has finished + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = $null + } + Get-Module 'ConnectWiseControlAPI' -ErrorAction SilentlyContinue | Remove-Module -Force +} + +# ============================================================================= +# Authentication +# ============================================================================= +Describe 'Live: Connect-CWC' -Skip:(-not $script:HasCredentials) { + + BeforeAll { + # Connection state established by the top-level BeforeAll - read once + $module = Get-Module 'ConnectWiseControlAPI' + $script:Connection = & $module { $script:CWCServerConnection } + } + + AfterAll { + # 'rejects invalid credentials' clears the connection - restore it for later Describes + Connect-CWC -Server $script:TestServer -Credentials $script:TestCredentials -Force + } + + It 'authenticates successfully' { + { Connect-CWC -Server $script:TestServer -Credentials $script:TestCredentials -Force } | Should -Not -Throw + } + + It 'sets CWCServerConnection after auth' { + $script:Connection | Should -Not -BeNullOrEmpty + $script:Connection.Server | Should -Not -BeNullOrEmpty + $script:Connection.Headers | Should -Not -BeNullOrEmpty + } + + It 'stores the correct server name' { + $cleanServer = $script:TestServer -replace 'http.*://', '' + $script:Connection.Server | Should -Be $cleanServer + } + + It 'extracts an anti-forgery token' { + $script:Connection.Headers.'x-anti-forgery-token' | Should -Not -BeNullOrEmpty + } + + It 'skips reconnect when already connected' { + # Already connected - call should return quickly without error + { Connect-CWC -Server $script:TestServer -Credentials $script:TestCredentials } | Should -Not -Throw + } + + It 'rejects invalid credentials' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = $null + } + $badCred = [PSCredential]::new('baduser', ('badpass' | ConvertTo-SecureString -AsPlainText -Force)) + $result = Connect-CWC -Server $script:TestServer -Credentials $badCred 2>&1 + $hasError = $result | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] } + $hasError | Should -Not -BeNullOrEmpty + } +} + +# ============================================================================= +# Session Groups (simplest read-only call) +# ============================================================================= +Describe 'Live: Get-CWCSessionGroup' -Skip:(-not $script:HasCredentials) { + + BeforeAll { + $script:Groups = Get-CWCSessionGroup + } + + It 'returns session groups' { + $script:Groups | Should -Not -BeNullOrEmpty + } + + It 'returns an array or collection' { + @($script:Groups).Count | Should -BeGreaterThan 0 + } +} + +# ============================================================================= +# Sessions +# ============================================================================= +Describe 'Live: Get-CWCSession' -Skip:(-not $script:HasCredentials) { + + It 'returns Access sessions without error' { + # Fetched once in the top-level BeforeAll + $script:AccessSessionsError | Should -BeNullOrEmpty + } + + It 'returns Support sessions without error' { + { Get-CWCSession -Type 'Support' } | Should -Not -Throw + } + + It 'returns Meeting sessions without error' { + { Get-CWCSession -Type 'Meeting' } | Should -Not -Throw + } + + It 'accepts a Group parameter' { + { Get-CWCSession -Type 'Access' -Group 'All Machines' } | Should -Not -Throw + } + + It 'accepts a Search parameter' { + { Get-CWCSession -Type 'Access' -Search 'nonexistent-machine-xyz' } | Should -Not -Throw + } + + It 'returns session objects with expected properties' { + if (-not $script:HasSessions) { + Set-ItResult -Inconclusive -Because 'No Access sessions found on server' + return + } + $first = @($script:AccessSessions)[0] + # Sessions should have at minimum a SessionID and Name + $first.PSObject.Properties.Name | Should -Contain 'SessionID' + $first.PSObject.Properties.Name | Should -Contain 'Name' + } +} + +# ============================================================================= +# Session Detail +# ============================================================================= +Describe 'Live: Get-CWCSessionDetail' -Skip:(-not $script:HasCredentials) { + + BeforeAll { + if ($script:HasSessions) { + $script:SessionDetail = Get-CWCSessionDetail -GUID $script:TestSessionGuid + } + } + + # HasSessions is only known at run time, so skip inside each It rather than via -Skip + It 'returns detail for a real session' { + if (-not $script:HasSessions) { Set-ItResult -Skipped -Because 'no sessions'; return } + $script:SessionDetail | Should -Not -BeNullOrEmpty + } + + It 'detail contains Events property' { + if (-not $script:HasSessions) { Set-ItResult -Skipped -Because 'no sessions'; return } + $script:SessionDetail.PSObject.Properties.Name | Should -Contain 'Events' + } + + It 'detail contains Connections property' { + if (-not $script:HasSessions) { Set-ItResult -Skipped -Because 'no sessions'; return } + $script:SessionDetail.PSObject.Properties.Name | Should -Contain 'Connections' + } +} + +# ============================================================================= +# Last Contact +# ============================================================================= +Describe 'Live: Get-CWCLastContact' -Skip:(-not $script:HasCredentials) { + + It 'returns a datetime or null for a real session' { + if (-not $script:HasSessions) { Set-ItResult -Skipped -Because 'no sessions'; return } + $result = Get-CWCLastContact -GUID $script:TestSessionGuid -ErrorAction SilentlyContinue + if ($null -ne $result) { + $result | Should -BeOfType [datetime] + } + } + + It 'returns boolean with Quiet switch' { + if (-not $script:HasSessions) { Set-ItResult -Skipped -Because 'no sessions'; return } + $result = Get-CWCLastContact -GUID $script:TestSessionGuid -Quiet -Seconds 86400 -ErrorAction SilentlyContinue + if ($null -ne $result) { + $result | Should -BeOfType [bool] + } + } +} + +# ============================================================================= +# Audit Service +# ============================================================================= +Describe 'Live: Get-CWCAuditInfo' -Skip:(-not $script:HasCredentials) { + + BeforeAll { + $script:AuditInfoError = $null + try { + $script:AuditInfo = Get-CWCAuditInfo + } + catch { + $script:AuditInfoError = $_ + } + } + + It 'returns audit info without error' { + $script:AuditInfoError | Should -BeNullOrEmpty + } + + It 'returns data' { + $script:AuditInfo | Should -Not -BeNullOrEmpty + } +} + +Describe 'Live: Get-CWCAuditLog' -Skip:(-not $script:HasCredentials) { + + It 'returns audit log for date range without error' { + $end = Get-Date + $start = $end.AddDays(-1) + { Get-CWCAuditLog -StartDate $start -EndDate $end } | Should -Not -Throw + } +} + +# ============================================================================= +# Security Service +# ============================================================================= +Describe 'Live: Get-CWCSecurityConfigurationInfo' -Skip:(-not $script:HasCredentials) { + + BeforeAll { + $script:SecurityConfigError = $null + try { + $script:SecurityConfig = Get-CWCSecurityConfigurationInfo + } + catch { + $script:SecurityConfigError = $_ + } + } + + It 'returns security configuration without error' { + $script:SecurityConfigError | Should -BeNullOrEmpty + } + + It 'contains UserSources' { + $script:SecurityConfig | Should -Not -BeNullOrEmpty + $script:SecurityConfig.PSObject.Properties.Name | Should -Contain 'UserSources' + } + + It 'contains InternalMembershipProvider source' { + $internal = $script:SecurityConfig.UserSources | Where-Object { $_.ResourceKey -eq 'InternalMembershipProvider' } + $internal | Should -Not -BeNullOrEmpty + } +} diff --git a/Tests/ConnectWiseControlAPI.Module.Tests.ps1 b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 new file mode 100644 index 0000000..23b80b5 --- /dev/null +++ b/Tests/ConnectWiseControlAPI.Module.Tests.ps1 @@ -0,0 +1,385 @@ +#Requires -Module Pester + +<# +.SYNOPSIS + Module structure, quality, and function validation tests. + +.DESCRIPTION + Tests module manifest, import, exports, function structure, + parameter validation, and ShouldProcess declarations. + +.NOTES + Run with: + Invoke-Pester Tests\ConnectWiseControlAPI.Module.Tests.ps1 -Output Detailed +#> + +BeforeDiscovery { + # One public function per Public/**/*.ps1 file; the tests below check the manifest and the loaded + # module against this list, so a new function needs no test edit. + $ExpectedFunctions = @(Get-ChildItem -Path (Join-Path (Split-Path -Parent $PSScriptRoot) 'source\Public') -Filter '*.ps1' -Recurse | + ForEach-Object BaseName | Sort-Object) +} + +BeforeAll { + $ModuleRoot = Split-Path -Parent $PSScriptRoot + $ManifestPath = & (Join-Path $PSScriptRoot 'TestHelpers\Resolve-TestModuleManifest.ps1') + Import-Module $ManifestPath -Force +} + +AfterAll { + Get-Module 'ConnectWiseControlAPI' -ErrorAction SilentlyContinue | Remove-Module -Force +} + +# ============================================================================= +# Module Quality Tests +# ============================================================================= +Describe 'Module: ConnectWiseControlAPI' { + + Context 'Module Manifest' { + BeforeAll { + $Manifest = Test-ModuleManifest -Path $ManifestPath -ErrorAction Stop + } + + It 'has a valid module manifest' { + $Manifest | Should -Not -BeNullOrEmpty + } + + It 'has a valid root module' { + $Manifest.RootModule | Should -Be 'ConnectWiseControlAPI.psm1' + } + + It 'has a valid GUID' { + $Manifest.GUID.ToString() | Should -Be 'f94fa996-0f01-4c5c-9cd9-3227728ebacb' + } + + It 'requires PowerShell 3.0 or higher' { + $Manifest.PowerShellVersion | Should -Be '3.0' + } + + It 'has a project URI' { + $Manifest.PrivateData.PSData.ProjectUri | Should -Not -BeNullOrEmpty + } + + It 'exports no cmdlets' { + $Manifest.ExportedCmdlets.Keys | Should -HaveCount 0 + } + + It 'lists every public function in FunctionsToExport exactly once' -ForEach @(@{ Expected = $ExpectedFunctions }) { + $Listed = @((Import-PowerShellDataFile -Path $ManifestPath).FunctionsToExport) + if ($Listed.Count -eq 1 -and $Listed[0] -eq '*') { + # source/ manifest: the build writes the explicit list; the .psm1 exports Public/ via Export-ModuleMember + Set-ItResult -Skipped -Because "the source manifest uses '*'; the built manifest is checked instead" + return + } + @($Listed | Group-Object | Where-Object Count -gt 1 | ForEach-Object Name) | Should -BeNullOrEmpty + @($Listed | Sort-Object) | Should -Be $Expected + } + } + + Context 'Module Import' { + It 'is loaded in the session' { + $module = Get-Module 'ConnectWiseControlAPI' + $module | Should -Not -BeNullOrEmpty + $module.Name | Should -Be 'ConnectWiseControlAPI' + } + } + + Context 'Exported Functions' { + BeforeAll { + $ExportedFunctions = (Get-Module 'ConnectWiseControlAPI').ExportedFunctions.Keys + } + + It 'exports the expected number of functions' -ForEach @(@{ Expected = $ExpectedFunctions }) { + $ExportedFunctions | Should -HaveCount $Expected.Count + } + + It 'exports <_>' -ForEach $ExpectedFunctions { + $_ | Should -BeIn $ExportedFunctions + } + } + + Context 'Function-to-File Mapping' { + BeforeAll { + $PublicPath = Join-Path $ModuleRoot 'source\Public' + $PublicFiles = Get-ChildItem -Path $PublicPath -Filter '*.ps1' -Recurse | + Select-Object -ExpandProperty BaseName + $ExportedFunctions = (Get-Module 'ConnectWiseControlAPI').ExportedFunctions.Keys + } + + It 'has a .ps1 file for each exported function' { + foreach ($function in $ExportedFunctions) { + $function | Should -BeIn $PublicFiles -Because "$function should have a matching .ps1 file" + } + } + + It 'every public .ps1 file corresponds to an exported function' { + foreach ($file in $PublicFiles) { + $file | Should -BeIn $ExportedFunctions -Because "$file.ps1 should be exported" + } + } + } + + Context 'Script-Scope Variables' { + It 'has InternalUserSource set to InternalMembershipProvider' { + $module = Get-Module 'ConnectWiseControlAPI' + $value = & $module { $script:InternalUserSource } + $value | Should -Be 'InternalMembershipProvider' + } + } +} + +# ============================================================================= +# Function Structure Tests +# ============================================================================= +Describe 'Function Structure' { + + Context '<_> has proper structure' -ForEach $ExpectedFunctions { + BeforeAll { + $cmd = Get-Command $_ -Module 'ConnectWiseControlAPI' + } + + It 'is a recognized command' { + $cmd | Should -Not -BeNullOrEmpty + } + + It 'has CmdletBinding attribute' { + $cmd.CmdletBinding | Should -BeTrue + } + } + + Context 'ShouldProcess on destructive functions' { + It '<_> supports ShouldProcess' -ForEach @( + 'Remove-CWCSession' + 'Remove-CWCHostFromSession' + 'Remove-CWCSessionNote' + 'Update-CWCCustomProperty' + 'Update-CWCSessionName' + 'New-CWCUser' + 'Remove-CWCUser' + 'Update-CWCUser' + 'Get-CWCLauncURL' + 'Add-CWCRemoteWorkforceRequiredRole' + 'New-CWCRemoteWorkforceAssignment' + 'Initialize-CWCRemoteWorkforceSessionGroup' + 'New-CWCSession' + 'Add-CWCSessionNote' + 'Send-CWCSessionMessage' + 'Send-CWCToolboxItem' + 'New-CWCMFA' + ) { + $cmd = Get-Command $_ -Module 'ConnectWiseControlAPI' + $cmd.Parameters.Keys | Should -Contain 'WhatIf' -Because "$_ should support -WhatIf" + } + } +} + +# ============================================================================= +# Parameter Validation Tests +# ============================================================================= +Describe 'Parameter Validation' { + + Context 'Connect-CWC parameters' { + BeforeAll { + $cmd = Get-Command Connect-CWC -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory Server parameter' { + $cmd.Parameters['Server'].Attributes.Mandatory | Should -Contain $True + } + + It 'has mandatory Credentials parameter' { + $cmd.Parameters['Credentials'].Attributes.Mandatory | Should -Contain $True + } + + It 'Credentials is type PSCredential' { + $cmd.Parameters['Credentials'].ParameterType.Name | Should -Be 'PSCredential' + } + + It 'has optional Force switch' { + $cmd.Parameters.Keys | Should -Contain 'Force' + $cmd.Parameters['Force'].SwitchParameter | Should -BeTrue + } + } + + Context 'Get-CWCSession parameters' { + BeforeAll { + $cmd = Get-Command Get-CWCSession -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory Type parameter' { + $cmd.Parameters['Type'].Attributes.Mandatory | Should -Contain $True + } + + It 'Type validates to Support, Access, Meeting' { + $validateSet = $cmd.Parameters['Type'].Attributes | Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] } + $validateSet.ValidValues | Should -Contain 'Support' + $validateSet.ValidValues | Should -Contain 'Access' + $validateSet.ValidValues | Should -Contain 'Meeting' + $validateSet.ValidValues | Should -HaveCount 3 + } + + It 'has optional Group parameter' { + $cmd.Parameters.Keys | Should -Contain 'Group' + } + } + + Context 'Invoke-CWCCommand parameters' { + BeforeAll { + $cmd = Get-Command Invoke-CWCCommand -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory GUID parameter' { + $cmd.Parameters['GUID'].Attributes.Mandatory | Should -Contain $True + } + + It 'GUID is type guid' { + $cmd.Parameters['GUID'].ParameterType.Name | Should -Be 'Guid' + } + + It 'has optional TimeOut parameter' { + $cmd.Parameters.Keys | Should -Contain 'TimeOut' + $cmd.Parameters['TimeOut'].ParameterType.Name | Should -Be 'Int32' + } + + It 'has optional MaxLength parameter' { + $cmd.Parameters.Keys | Should -Contain 'MaxLength' + $cmd.Parameters['MaxLength'].ParameterType.Name | Should -Be 'Int32' + } + + It 'has PowerShell switch' { + $cmd.Parameters['PowerShell'].SwitchParameter | Should -BeTrue + } + + It 'has NoWait switch' { + $cmd.Parameters['NoWait'].SwitchParameter | Should -BeTrue + } + } + + Context 'Invoke-CWCWake parameters' { + BeforeAll { + $cmd = Get-Command Invoke-CWCWake -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory Type parameter' { + $cmd.Parameters['Type'].Attributes.Mandatory | Should -Contain $True + } + + It 'Type validates to Support, Access only' { + $validateSet = $cmd.Parameters['Type'].Attributes | Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] } + $validateSet.ValidValues | Should -Contain 'Support' + $validateSet.ValidValues | Should -Contain 'Access' + $validateSet.ValidValues | Should -HaveCount 2 + } + + It 'GUID accepts array' { + $cmd.Parameters['GUID'].ParameterType.Name | Should -Be 'Guid[]' + } + } + + Context 'New-CWCUser parameters' { + BeforeAll { + $cmd = Get-Command New-CWCUser -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory Credentials parameter' { + $cmd.Parameters['Credentials'].Attributes.Mandatory | Should -Contain $True + } + + It 'has mandatory Email parameter' { + $cmd.Parameters['Email'].Attributes.Mandatory | Should -Contain $True + } + + It 'has optional ForcePassChange parameter' { + $cmd.Parameters.Keys | Should -Contain 'ForcePassChange' + $cmd.Parameters['ForcePassChange'].ParameterType.Name | Should -Be 'Boolean' + } + } + + Context 'Remove-CWCSession parameters' { + BeforeAll { + $cmd = Get-Command Remove-CWCSession -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory GUID parameter' { + $cmd.Parameters['GUID'].Attributes.Mandatory | Should -Contain $True + } + + It 'GUID accepts array' { + $cmd.Parameters['GUID'].ParameterType.Name | Should -Be 'Guid[]' + } + + It 'has mandatory Group parameter' { + $cmd.Parameters['Group'].Attributes.Mandatory | Should -Contain $True + } + } + + Context 'Get-CWCLastContact parameters' { + BeforeAll { + $cmd = Get-Command Get-CWCLastContact -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory GUID parameter' { + $cmd.Parameters['GUID'].Attributes.Mandatory | Should -Contain $True + } + + It 'has Quiet switch' { + $cmd.Parameters['Quiet'].SwitchParameter | Should -BeTrue + } + + It 'Quiet is in parameter set Quiet' { + $cmd.Parameters['Quiet'].ParameterSets.Keys | Should -Contain 'Quiet' + } + } + + Context 'Update-CWCUser parameters' { + BeforeAll { + $cmd = Get-Command Update-CWCUser -Module 'ConnectWiseControlAPI' + } + + It 'has mandatory UserToUpdate parameter' { + $cmd.Parameters['UserToUpdate'].Attributes.Mandatory | Should -Contain $True + } + + It 'Password is type SecureString' { + $cmd.Parameters['Password'].ParameterType.Name | Should -Be 'SecureString' + } + } +} + +Describe 'Repository' { + # A .gitignore pattern once hid Private/Test-CWCApiSecretConnection.ps1 (matched *secret*), so the + # module only worked on machines that already had the file. + It 'does not git-ignore any source, test, docs, build or example file' { + $RepoRoot = Split-Path $PSScriptRoot -Parent + if (-not (Get-Command git -ErrorAction SilentlyContinue) -or -not (Test-Path (Join-Path $RepoRoot '.git'))) { + Set-ItResult -Skipped -Because 'git or the repository is not available' + return + } + $SourceFolders = 'source', 'Tests', 'Docs', 'Build', '.build', 'Examples' | + ForEach-Object { Join-Path $RepoRoot $_ } | Where-Object { Test-Path $_ } + $SourceFiles = Get-ChildItem $SourceFolders -Recurse -File | + ForEach-Object { $_.FullName.Substring($RepoRoot.Length + 1).Replace('\', '/') } + # Paths as arguments, not --stdin: piped lines carry a trailing CR on Windows, which defeats the patterns + $Ignored = @(git -C $RepoRoot check-ignore --no-index -- $SourceFiles | Where-Object { $_ }) + $Ignored | Should -BeNullOrEmpty + } +} + +Describe 'Generated help' { + BeforeAll { + $RepoRoot = Split-Path $PSScriptRoot -Parent + $DocsPath = Join-Path $RepoRoot 'Docs' + } + + It 'has a Docs page for <_>' -ForEach $ExpectedFunctions { + Join-Path $DocsPath "$_.md" | Should -Exist -Because 'run ./Build/Update-Help.ps1 after adding a function' + } + + # platyPS on PowerShell 7.4+ adds -ProgressAction to every page; Build/Update-Help.ps1 strips it. + It 'does not document the -ProgressAction common parameter' { + $Files = @(Get-ChildItem $DocsPath -Filter '*.md' | ForEach-Object FullName) + + (Join-Path $RepoRoot 'source\en-US\ConnectWiseControlAPI-help.xml') + @(Select-String -Path $Files -Pattern 'ProgressAction' | ForEach-Object { "$($_.Filename):$($_.LineNumber)" }) | + Should -BeNullOrEmpty -Because 'run ./Build/Update-Help.ps1 to regenerate the help' + } +} diff --git a/Tests/ConnectWiseControlAPI.Private.Tests.ps1 b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 new file mode 100644 index 0000000..4e6d290 --- /dev/null +++ b/Tests/ConnectWiseControlAPI.Private.Tests.ps1 @@ -0,0 +1,806 @@ +#Requires -Module Pester + +<# +.SYNOPSIS + Mocked tests for private helper functions. + +.DESCRIPTION + Tests Join-Url and Invoke-CWCWebRequest private functions using + InModuleScope and mocked dependencies. + +.NOTES + Run with: + Invoke-Pester Tests\ConnectWiseControlAPI.Private.Tests.ps1 -Output Detailed +#> + +BeforeAll { + $ModuleRoot = Split-Path -Parent $PSScriptRoot + $ManifestPath = & (Join-Path $PSScriptRoot 'TestHelpers\Resolve-TestModuleManifest.ps1') + Import-Module $ManifestPath -Force +} + +AfterAll { + Get-Module 'ConnectWiseControlAPI' -ErrorAction SilentlyContinue | Remove-Module -Force +} + +# ============================================================================= +# Join-Url +# ============================================================================= +Describe 'Join-Url' { + + It 'joins base and child path' { + InModuleScope 'ConnectWiseControlAPI' { + $result = Join-Url -Path 'https://server.com' -ChildPath 'Services/Test.ashx' + $result | Should -Be 'https://server.com/Services/Test.ashx' + } + } + + It 'trims trailing slash from Path' { + InModuleScope 'ConnectWiseControlAPI' { + $result = Join-Url -Path 'https://server.com/' -ChildPath 'endpoint' + $result | Should -Be 'https://server.com/endpoint' + } + } + + It 'trims leading slash from ChildPath' { + InModuleScope 'ConnectWiseControlAPI' { + $result = Join-Url -Path 'https://server.com' -ChildPath '/endpoint' + $result | Should -Be 'https://server.com/endpoint' + } + } + + It 'handles both trailing and leading slashes' { + InModuleScope 'ConnectWiseControlAPI' { + $result = Join-Url -Path 'https://server.com/' -ChildPath '/endpoint' + $result | Should -Be 'https://server.com/endpoint' + } + } + + It 'handles multi-segment child paths' { + InModuleScope 'ConnectWiseControlAPI' { + $result = Join-Url -Path 'https://server.com' -ChildPath 'Services/PageService.ashx/GetLiveData' + $result | Should -Be 'https://server.com/Services/PageService.ashx/GetLiveData' + } + } +} + +# ============================================================================= +# Invoke-CWCWebRequest +# ============================================================================= +Describe 'Invoke-CWCWebRequest' { + + BeforeEach { + # Default fake connection in module script scope. Tests that need a + # different state (no connection, custom headers) override it inline. + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'test.example.com' + Headers = @{ 'Authorization' = 'Basic dGVzdDp0ZXN0' } + } + } + } + + Context 'Connection Check' { + It 'returns error when not connected' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = $null + $result = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'test' } 2>&1 + $result | Should -Match 'Not connected' + } + } + } + + Context 'URI Construction' { + BeforeEach { + Mock Invoke-WebRequest -ModuleName 'ConnectWiseControlAPI' { + [PSCustomObject]@{ + Content = '{"result":"ok"}' + Headers = @{} + } + } + } + + It 'constructs full URI from server and endpoint' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = 'Services/PageService.ashx/GetLiveData'; Method = 'Post' } + Invoke-CWCWebRequest -Arguments $arguments + Should -Invoke Invoke-WebRequest -Times 1 + $arguments.URI | Should -Be 'https://test.example.com/Services/PageService.ashx/GetLiveData' + } + } + + It 'removes Endpoint key from arguments after constructing URI' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + $arguments.Keys | Should -Not -Contain 'Endpoint' + } + } + + It 'sets UseBasicParsing to true' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + $arguments.UseBasicParsing | Should -BeTrue + } + } + + It 'passes headers from connection state' { + InModuleScope 'ConnectWiseControlAPI' { + $testHeaders = @{ + 'Authorization' = 'Basic dGVzdDp0ZXN0' + 'x-anti-forgery-token' = 'abc123' + } + $script:CWCServerConnection = @{ + Server = 'test.example.com' + Headers = $testHeaders + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + $arguments.Headers.Authorization | Should -Be 'Basic dGVzdDp0ZXN0' + $arguments.Headers.'x-anti-forgery-token' | Should -Be 'abc123' + } + } + + It 'passes a copy of the headers, not the connection state hashtable' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + [object]::ReferenceEquals($arguments.Headers, $script:CWCServerConnection.Headers) | Should -BeFalse + } + } + } + + Context 'Debug output' { + It 'redacts auth headers in debug output' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { [PSCustomObject]@{ Content = '{}'; Headers = @{} } } + $script:CWCServerConnection.Headers.'x-anti-forgery-token' = 'antiforgerysecret' + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $DebugPreference = 'Continue' # not -Debug: PS 5.1 -Debug prompts (Inquire), which fails without a console + $debugOutput = Invoke-CWCWebRequest -Arguments $arguments 5>&1 | Out-String + $debugOutput | Should -Not -Match 'dGVzdDp0ZXN0' + $debugOutput | Should -Not -Match 'antiforgerysecret' + $debugOutput | Should -Match 'redacted' + } + } + } + + Context 'API secret connection' { + BeforeEach { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'test.example.com' + AuthType = 'ApiSecret' + ApiSecret = ('topsecretvalue' | ConvertTo-SecureString -AsPlainText -Force) + Headers = @{ 'origin' = 'https://test.example.com' } + } + Mock Invoke-WebRequest { + [PSCustomObject]@{ Content = '[]'; Headers = @{ 'Set-Cookie' = 'x=1' } } + } + } + } + + It 'sends the secret as CTRLAuthHeader on RESTful API Manager endpoints' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByFilter"; Method = 'Post' } + Invoke-CWCWebRequest -Arguments $arguments + Should -Invoke Invoke-WebRequest -Times 1 + $arguments.Headers.CTRLAuthHeader | Should -Be 'topsecretvalue' + $arguments.Headers.Keys | Should -Not -Contain 'authorization' + } + } + + It 'never sends a WebSession on API-secret connections' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection.WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByFilter"; Method = 'Post' } + Invoke-CWCWebRequest -Arguments $arguments + Should -Invoke Invoke-WebRequest -Times 1 -ParameterFilter { $null -eq $WebSession } + } + } + + It 'does not persist the plaintext secret or cookies in connection state' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByFilter"; Method = 'Post' } + Invoke-CWCWebRequest -Arguments $arguments + $script:CWCServerConnection.Headers.Keys | Should -Not -Contain 'CTRLAuthHeader' + $script:CWCServerConnection.Headers.Keys | Should -Not -Contain 'Set-Cookie' + } + } + + It 'redacts the secret in debug output' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByFilter"; Method = 'Post' } + $DebugPreference = 'Continue' # not -Debug: PS 5.1 -Debug prompts (Inquire), which fails without a console + $debugOutput = Invoke-CWCWebRequest -Arguments $arguments 5>&1 | Out-String + $debugOutput | Should -Not -Match 'topsecretvalue' + } + } + + It 'does not retry extension calls on HTTP 500 (they are not idempotent)' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Start-Sleep {} + Mock Invoke-WebRequest { + $response = [PSCustomObject]@{ StatusCode = 500 } + $exception = [System.Exception]::new('500') + $exception | Add-Member -NotePropertyName Response -NotePropertyValue $response -Force + throw [System.Management.Automation.ErrorRecord]::new($exception, 'x', 'NotSpecified', $null) + } + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/CreateSession"; Method = 'Post' } + $null = Invoke-CWCWebRequest -Arguments $arguments -WarningAction SilentlyContinue 2>&1 + Should -Invoke Invoke-WebRequest -Times 1 -Exactly + } + } + + It 'refuses non-extension endpoints without calling the server' { + InModuleScope 'ConnectWiseControlAPI' { + $arguments = @{ Endpoint = 'Services/PageService.ashx/GetLiveData'; Method = 'Post' } + $result = Invoke-CWCWebRequest -Arguments $arguments 2>&1 + $result.Exception.Message | Should -Match 'Connect-CWC -Credentials' + Should -Invoke Invoke-WebRequest -Times 0 + } + } + + It 'refuses RESTful API Manager endpoints on a credentials connection' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'test.example.com' + Headers = @{ 'Authorization' = 'Basic dGVzdDp0ZXN0' } + } + $arguments = @{ Endpoint = "App_Extensions/$($script:CWCRestApiExtensionID)/Service.ashx/GetSessionsByFilter"; Method = 'Post' } + $result = Invoke-CWCWebRequest -Arguments $arguments 2>&1 + $result.Exception.Message | Should -Match 'Connect-CWC -ApiSecret' + Should -Invoke Invoke-WebRequest -Times 0 + } + } + } + + Context 'Successful Request' { + It 'returns parsed JSON from response content' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { + [PSCustomObject]@{ + Content = '{"name":"TestSession","id":42}' + Headers = @{} + } + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $result = Invoke-CWCWebRequest -Arguments $arguments + $result.name | Should -Be 'TestSession' + $result.id | Should -Be 42 + } + } + + It 'does not store response Set-Cookie as a request header (issue #22)' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { + [PSCustomObject]@{ + Content = '{"ok":true}' + Headers = @{ 'Set-Cookie' = 'session=abc123; Path=/' } + } + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + $script:CWCServerConnection.Headers.Keys | Should -Not -Contain 'Set-Cookie' + } + } + + It 'sends the connection WebSession so server cookies go back to the server (issue #22)' { + InModuleScope 'ConnectWiseControlAPI' { + $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession + $script:CWCServerConnection.WebSession = $session + Mock Invoke-WebRequest { [PSCustomObject]@{ Content = '{}'; Headers = @{} } } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + Invoke-CWCWebRequest -Arguments $arguments + Should -Invoke Invoke-WebRequest -Times 1 -ParameterFilter { [object]::ReferenceEquals($WebSession, $session) } + } + } + + It 'redacts the WebSession in debug output' { + InModuleScope 'ConnectWiseControlAPI' { + $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession + $session.Cookies.Add([System.Net.Cookie]::new('.ASPXAUTH', 'cookiesecretvalue', '/', 'test.example.com')) + $script:CWCServerConnection.WebSession = $session + Mock Invoke-WebRequest { [PSCustomObject]@{ Content = '{}'; Headers = @{} } } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $DebugPreference = 'Continue' + $debugOutput = Invoke-CWCWebRequest -Arguments $arguments 5>&1 | Out-String + $debugOutput | Should -Not -Match 'cookiesecretvalue' + } + } + } + + Context 'Retry on HTTP 500' { + BeforeAll { + # Single factory for the fake HTTP 500 error so both retry tests + # exercise the same catch path: [int]$_.Exception.Response.StatusCode -eq 500. + # Stored in module script scope so mock bodies (which run in module scope) can see it. + InModuleScope 'ConnectWiseControlAPI' { + $script:NewHttp500ErrorRecord = { + $exception = [System.Net.WebException]::new('Server Error') + $exception | Add-Member -NotePropertyName Response -NotePropertyValue ([PSCustomObject]@{ StatusCode = 500 }) -Force + [System.Management.Automation.ErrorRecord]::new( + $exception, 'WebError', 'ConnectionError', $null + ) + } + } + } + + AfterAll { + InModuleScope 'ConnectWiseControlAPI' { + Remove-Variable -Name NewHttp500ErrorRecord -Scope Script -ErrorAction SilentlyContinue + } + } + + BeforeEach { + Mock Start-Sleep -ModuleName 'ConnectWiseControlAPI' {} + } + + It 'does not retry an application exception (errorType body), and keeps the server message' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { + $record = & $script:NewHttp500ErrorRecord + $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new('{"errorType":"SecurityException","message":"Needs permission"}') + throw $record + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $result = Invoke-CWCWebRequest -Arguments $arguments -MaxRetry 3 2>&1 + Should -Invoke Invoke-WebRequest -Times 1 -Exactly + "$result" | Should -Match 'Needs permission' + $result.FullyQualifiedErrorId | Should -BeLike 'CWC.Http500*' + } + } + + It 'retries on HTTP 500 and succeeds' { + InModuleScope 'ConnectWiseControlAPI' { + $script:RetryCallCount = 0 + Mock Invoke-WebRequest { + $script:RetryCallCount++ + if ($script:RetryCallCount -lt 3) { + throw (& $script:NewHttp500ErrorRecord) + } + [PSCustomObject]@{ + Content = '{"ok":true}' + Headers = @{} + } + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $result = Invoke-CWCWebRequest -Arguments $arguments -MaxRetry 5 + $result.ok | Should -BeTrue + Should -Invoke Start-Sleep -Times 2 + } + } + + It 'fails after max retries' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { + throw (& $script:NewHttp500ErrorRecord) + } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Get' } + $result = Invoke-CWCWebRequest -Arguments $arguments -MaxRetry 3 2>&1 + $result | Should -Match 'Max retries hit' + } + } + + It 'does not retry by default (the caller must opt in)' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { throw (& $script:NewHttp500ErrorRecord) } + $arguments = @{ Endpoint = 'Services/Test.ashx'; Method = 'Post' } + $null = Invoke-CWCWebRequest -Arguments $arguments 2>&1 + Should -Invoke Invoke-WebRequest -Times 1 -Exactly + } + } + } + + Context 'MFA connection (#12)' { + BeforeAll { + InModuleScope 'ConnectWiseControlAPI' { + # HTTP 500 with a server error body; the failed request (with a login cookie) as TargetObject + $script:NewServerErrorRecord = { + param([string]$Body, $Request) + $exception = [System.Net.WebException]::new('Server Error') + $exception | Add-Member -NotePropertyName Response -NotePropertyValue ([PSCustomObject]@{ StatusCode = 500 }) -Force + $record = [System.Management.Automation.ErrorRecord]::new($exception, 'WebError', 'InvalidResult', $Request) + $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new($Body) + $record + } + } + } + + BeforeEach { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection = @{ + Server = 'test.example.com' + AuthType = 'Mfa' + Headers = @{ 'origin' = 'https://test.example.com' } + WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession + } + } + } + + It 'sends the WebSession and no Authorization header' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { [PSCustomObject]@{ Content = '{}' } } + $arguments = @{ Endpoint = 'Services/PageService.ashx/GetEligibleHosts'; Method = 'Post' } + $null = Invoke-CWCWebRequest -Arguments $arguments + Should -Invoke Invoke-WebRequest -Times 1 -ParameterFilter { $null -ne $WebSession } + $arguments.Headers.Keys | Should -Not -Contain 'authorization' + } + } + + It 'says the login may have expired on a permission error' { + InModuleScope 'ConnectWiseControlAPI' { + Mock Invoke-WebRequest { throw (& $script:NewServerErrorRecord '{"errorType":"SecurityException","message":"Needs permission"}' $null) } + $result = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/PageService.ashx/GetSessionDetails'; Method = 'Post' } -ErrorAction SilentlyContinue -ErrorVariable err + "$err" | Should -Match 'MFA login has expired' + @($err | Where-Object { $_.FullyQualifiedErrorId -like 'CWC.Http500*' }).Count | Should -BeGreaterThan 0 + } + } + + 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) } + $null = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/PageService.ashx/AddSessionEvents'; Method = 'Post' } -ErrorAction SilentlyContinue -ErrorVariable err + "$err" | Should -Match 'MFA login has expired' + } + } + + It 'does not add the hint on a credentials connection' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection.AuthType = 'Credentials' + Mock Invoke-WebRequest { throw (& $script:NewServerErrorRecord '{"errorType":"SecurityException","message":"Needs permission"}' $null) } + $null = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/PageService.ashx/GetSessionDetails'; Method = 'Post' } -ErrorAction SilentlyContinue -ErrorVariable err + "$err" | Should -Not -Match 'MFA login' + } + } + + It 'does not suggest an expired login while logging in' { + InModuleScope 'ConnectWiseControlAPI' { + $script:CWCServerConnection.LoggingIn = $True + Mock Invoke-WebRequest { throw (& $script:NewServerErrorRecord '{"errorType":"SecurityException","message":"Needs permission"}' $null) } + $null = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/PageService.ashx/GetEligibleHosts'; Method = 'Post' } -ErrorAction SilentlyContinue -ErrorVariable err + "$err" | Should -Not -Match 'MFA login' + } + } + It 'strips the login cookie from the failed request kept on the error record' { + InModuleScope 'ConnectWiseControlAPI' { + $script:FailedRequest = [System.Net.WebRequest]::Create('https://test.example.com/Services/PageService.ashx/GetSessionDetails') + $script:FailedRequest.Headers.Add('Cookie', '.ASPXAUTH=cookiesecretvalue') + $script:FailedRequest.CookieContainer = New-Object System.Net.CookieContainer + Mock Invoke-WebRequest { throw (& $script:NewServerErrorRecord '{"errorType":"SecurityException","message":"Needs permission"}' $script:FailedRequest) } + $null = Invoke-CWCWebRequest -Arguments @{ Endpoint = 'Services/PageService.ashx/GetSessionDetails'; Method = 'Post' } -ErrorAction SilentlyContinue + $script:FailedRequest.Headers['Cookie'] | Should -BeNullOrEmpty + $script:FailedRequest.CookieContainer | Should -BeNullOrEmpty + } + } + } +} + +# ============================================================================= +# MFA helpers (#12) +# ============================================================================= +Describe 'Get-CWCTotpCode' { + + # RFC 6238 appendix B test key "12345678901234567890" in Base32 + It 'matches the RFC 6238 SHA-1 test vector at T=