PSFramework

repository·development·Indexed 19 days ago

https://github.com/powershellframeworkcollective/psframework

A specialized framework providing infrastructure for PowerShell scripting, including tools for configuration management, logging, user experience optimization, and general manageability. It features advanced logging via Write-PSFMessage, high-performance object modification with [PSFramework.Object.ObjectHost]::AddNoteProperty(), and utilities for generating Format and Type Extension XML files. The framework also provides a decoupled extension pattern using Invoke-PSFCallback and streamlined error handling through Invoke-PSFProtectedCommand.

Tokens
30.2K
Snippets
92
Records
128
Agent score
54%

What's inside psframework

  1. Overview of PSFramework components

    development

    PSFramework is a toolkit designed to speed up PowerShell development and improve code manageability by providing solutions for generic scripting challenges. Its core components include:

    • Configuration: Self-documenting settings with input validation and change events.
    • Flow Control: Managed exception handling and termination for modules.
    • License: Centralized registration of product licenses.
    • Message: A powerful, asynchronous logging system.
    • Result Cache: Caching function outputs to allow retrieval even if not stored in a variable.
    • Runspace: A system for managing named runspaces that prevents multiple parallel executions of the same task.
  2. Manage the PSFramework Result Cache

    development

    The PSFramework Result Cache component allows you to store and retrieve the results of expensive operations (such as API calls or complex computations) to improve performance. You can manage the cache using the following core commands:

    • Set-PSFResultCache: Stores a value or object in the cache.
    • Get-PSFResultCache: Retrieves a previously stored value from the cache.
    • Clear-PSFResultCache: Removes items from the cache.
  3. Manage background tasks with Runspace

    development
    The Runspace component manages named runspaces for background tasks. It provides a mechanism to run a script in parallel to the main execution while guaranteeing that only a single instance of a specific named runspace is running at any time. This prevents conflicts (e.g., when accessing the same file) and avoids doubling the number of runspaces during parallel operations.
  4. How the PSFramework Process of Change works

    development

    When a breaking change is necessary (e.g., to improve performance or reduce environmental impact), PSFramework follows a transparent, multi-stage process:

    1. RFC (Request for Comments): An issue is posted describing the change and its benefits. It remains open for discussion for three months.
    2. Pending Change: If no convincing arguments against the change are raised during the RFC period, the change is marked as 'Pending'.
    3. Deprecation: The old way of operating is declared deprecated. Affected features will trigger warnings when the deprecated method is used.
    4. Warning Mechanism: On Windows systems, using deprecated functionality generates a PowerShell Eventlog warning (ID: 666; Category: 1; EntryType: Warning; Source: PowerShell).
    5. Implementation: The breaking change is implemented nine months after the RFC is approved.
  5. Perform a LEFT JOIN with Select-PSFObject

    development

    You can perform a simple property-matching join between your current pipeline objects and another variable. This allows you to pull data from a secondary list based on a matching property value.

    Syntax: "<PropertyFromOtherObject> from <VariableName> WHERE <OtherObjectProperty> = <CurrentObjectProperty>"

    Note: Currently only supports simple property-matching.

    $list = @()
    $list += [PSCustomObject]@{ Type = "Foo"; ID = 1 }
    $list += [PSCustomObject]@{ Type = "Bar"; ID = 2 }
    
    # Selects Name from $obj, and for each, finds the ID from $list where Type matches Name
    $obj | Select-PSFObject Name, "ID from list WHERE Type = Name"
  6. Inherit values from caller scope with -Inherit

    development

    The -Inherit switch allows the cmdlet to substitute missing keys (specified in -Include) with values from variables in the caller's scope that share the same name. This is specifically designed to allow inheriting default parameter values when cloning $PSBoundParameters.

    $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include ComputerName, Credential, Target -Inherit
  7. Use Invoke-PSFProtectedCommand to simplify error handling and logging

    development

    The Invoke-PSFProtectedCommand cmdlet reduces boilerplate code by combining ShouldProcess (for -WhatIf and -Confirm support), try/catch error handling, and logging into a single call. It is designed to make code more readable and less error-prone.

    Key Capabilities:

    • Automatic Logging: Logs the execution and potential failures of the provided -ScriptBlock.
    • ShouldProcess Support: Automatically honors -WhatIf and -Confirm parameters.
    • Error Handling Modes:
      • By default, failures result in a warning and the command terminates silently (unless -EnableException is used).
      • With -EnableException $true, failures throw terminating exceptions, allowing calling scripts to catch them.
    • Retry Logic: Provides built-in mechanisms to retry failed actions at static or escalating intervals.

    Note: This command must be used within an advanced function unless you explicitly provide the -PSCmdlet parameter.

    Invoke-PSFProtectedCommand -Action "Doing Something" -Target $computer -ScriptBlock {
        Get-Something -ComputerName $computer -ErrorAction Stop
    } -EnableException $true
  8. How the PSFramework message architecture works

    development

    PSFramework uses a numeric level system to control verbosity across different PowerShell streams. The -Level parameter determines which stream the message is sent to, which is controlled by the configuration system.

    Message Levels and Streams

    StreamLevel Range / Examples
    InformationCritical (1), Important/Output/Host (2), Significant (3)
    VerboseVeryVerbose (4), Verbose (5), SomewhatVerbose (6)
    DebugCritical (1) through Significant (3), VeryVerbose (4), Verbose (5), SomewhatVerbose (6), System (7), Debug (8), InternalComment (9), Warning (666)
    WarningWarning (666)
    ErrorErrors are handled via the -ErrorRecord parameter on Write-PSFMessage rather than a numeric level.

    Concept: Scaling Verbosity

    By using a range of levels, users can control the granularity of information they see. For example, a function might log major steps at level 4 and sub-steps at level 6. A user can increase the psframework.message.info.maximum configuration value to see more detail without changing the code.

  9. Understand the PSFramework Reliability Promise

    development

    PSFramework is designed as a stable platform for building other code. The project follows a 'No Breaking Changes' policy for all features that have reached the deployment stage. This ensures that updating the module version will not break your existing automation or scripts.

    What is guaranteed (No Breaking Changes):

    • Function and Cmdlet Signatures: Current parameterization will remain valid and produce the same results.
    • Logging Providers: Configuration and default behaviors are stable.
    • Parameter Classes: Will continue to understand current input (even if they add support for new input).
    • Validation Attributes: Will continue to accept current definitions.
    • Advertised Features: Any feature documented on the official documentation site is covered.

    What is NOT guaranteed:

    • Preview Features: New commands are considered 'Preview' for the first month of release to allow for feedback. After this month, they are subject to the stability promise.
    • Internal Library Mechanics: Some internal mechanics are public for script access but are not officially supported for public consumption.
    • UI User Interaction: Display formats for human-readable messages may change, provided the previous state can be re-enabled via configuration.
    • Experimental Features: Features explicitly marked as experimental are exempt from the stability policy.
    • System Mandated Changes: Changes required to maintain compatibility across all supported platforms (e.g., resolving conflicts with PowerShell Core).
  10. Use the Flow Control component to manage function interruptions

    development

    The PSFramework Flow Control component provides mechanisms to signal and test for interruptions within functions. This allows you to implement graceful exits or pause processing when a stop signal is received.

    Key commands:

    • Stop-PSFFunction: Signals that the current function should stop execution.
    • Test-PSFFunctionInterrupt: Checks if a stop signal has been issued for the current function context.