### POST /New-ExampleInfo Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/help/New-ExampleInfo.md Creates an example information object for a Crescendo command definition. ```APIDOC ## POST /New-ExampleInfo ### Description Creates an object containing example information for a command, which is used when generating help documentation for Crescendo-wrapped native commands. ### Method POST ### Endpoint /New-ExampleInfo ### Parameters #### Request Body - **command** (String) - Required - The name of the command being documented. - **originalCommand** (String) - Required - The original native command name. - **description** (String) - Required - A description of the example usage. ### Request Example { "command": "Get-MyTool", "originalCommand": "mytool --list", "description": "Lists all available items using the native tool." } ### Response #### Success Response (200) - **Object** (System.Object) - Returns a PSCustomObject containing the example configuration. #### Response Example { "command": "Get-MyTool", "originalCommand": "mytool --list", "description": "Lists all available items using the native tool." } ``` -------------------------------- ### Configure Help Documentation and Examples Source: https://context7.com/powershell/crescendo/llms.txt Shows how to define usage synopses and command examples using New-UsageInfo and New-ExampleInfo to improve the generated cmdlet's help documentation. ```powershell # Create basic usage info $usage = New-UsageInfo -usage "Retrieves Docker container information with filtering options" # Apply to a command $cmd = New-CrescendoCommand -Verb "Get" -Noun "DockerContainer" -OriginalName "docker" $cmd.Usage = $usage # Create an example with description $example1 = New-ExampleInfo ` -command "Get-DockerImage -Repository nginx" ` -description "Gets all Docker images with 'nginx' in the repository name" # Create an example showing the native command equivalent $example2 = New-ExampleInfo ` -command "Get-DockerContainer -All -Format json" ` -description "Lists all containers including stopped ones in JSON format" ` -originalCommand "docker ps -a --format json" # Add examples to a command $cmd.Examples.Add($example1) $cmd.Examples.Add($example2) ``` -------------------------------- ### Install PowerShell Crescendo Module Source: https://context7.com/powershell/crescendo/llms.txt Installs the Microsoft.PowerShell.Crescendo module from the PowerShell Gallery using either PowerShellGet or PSResourceGet. ```powershell # Install using PowerShellGet Install-Module -Name Microsoft.PowerShell.Crescendo # Or install using PowerShellGet v3 Install-PSResource -Name Microsoft.PowerShell.Crescendo ``` -------------------------------- ### Programmatically Define Commands with New-CrescendoCommand Source: https://context7.com/powershell/crescendo/llms.txt Creates and configures Command objects dynamically, including parameters, usage information, and examples, before exporting them to JSON. ```powershell # Create a new command definition programmatically $cmd = New-CrescendoCommand -Verb "Get" -Noun "SystemUptime" -OriginalName "uptime" # Add parameters to the command $param = New-ParameterInfo -Name "Short" -OriginalName "-s" $param.ParameterType = "switch" $param.Description = "Display uptime in short format" $cmd.Parameters.Add($param) # Add usage information $cmd.Usage = New-UsageInfo -usage "Displays system uptime information" # Add an example $example = New-ExampleInfo -command "Get-SystemUptime -Short" -description "Gets uptime in compact format" $cmd.Examples.Add($example) # Export the configuration to JSON $cmd.ExportConfigurationFile("./Get-SystemUptime.crescendo.json") ``` -------------------------------- ### Crescendo Command Configuration JSON Structure - YAML Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/help/Import-CommandConfiguration.md Defines the structure of a Crescendo JSON configuration file used with Import-CommandConfiguration. This example shows a basic structure for wrapping the 'ifconfig' command, including parameter definitions and help text. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -------------------------------- ### Initialize Help Parsing Variables Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/src/experimental/HelpParsers/README.md Defines the executable name and the help flag parameter required to initiate the help text retrieval process. ```powershell $exe = "docker" $helpChar = "--help" ``` -------------------------------- ### Extracting Usage from Command Help (PowerShell) Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/src/experimental/HelpParsers/README.md Demonstrates various PowerShell commands used to extract the 'Usage' section from different command-line tools' help output. It highlights the variability in output formats and the use of cmdlets like 'sls', 'select', and piping to 'first'. ```powershell PS> docker --help | sls usage: -NoEmphasis Usage: docker [OPTIONS] COMMAND ``` ```powershell PS> kubectl --help ... Usage: kubectl [flags] [options] ``` ```powershell PS> faas-cli --help|select -first 10 Manage your OpenFaaS functions from the command line Usage: faas-cli [flags] faas-cli [command] ``` ```powershell PS> netsh -? Usage: C:\windows\system32\netsh.exe [-a AliasFile] [-c Context] [-r RemoteMachine] [-u [DomainName\UserNme] [-p Password | *] [Command | -f ScriptFile] ``` -------------------------------- ### Retrieve Command Help Text Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/src/experimental/HelpParsers/README.md Executes the help command for a given executable to retrieve the initial help text for parsing. ```powershell PS> docker run --help|select -first 4 Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...] Run a command in a new container ``` -------------------------------- ### Exporting a Crescendo Module from Configuration Files Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/help/Export-CrescendoModule.md Demonstrates how to generate a PowerShell module using specific configuration files and how to import the resulting module into the current session. ```powershell Export-CrescendoModule -ModuleName netsh -ConfigurationFile netsh*.json Import-Module ./netsh.psm1 ``` -------------------------------- ### Generating Crescendo Configuration Object (PowerShell) Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/src/experimental/HelpParsers/README.md Shows how to construct a PowerShell ordered dictionary that represents the structure of a Crescendo configuration file. This object is then used with the JSON serializer to create the final configuration. ```powershell $h = [ordered]@{ '$schema' = 'https://aka.ms/PowerShell/Crescendo/Schemas/2021-11' 'Commands' = $commands } ``` -------------------------------- ### Inspect Crescendo Command Schema Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/src/experimental/HelpParsers/README.md Demonstrates how to execute a Crescendo parser script without parameters to retrieve and inspect the command schema object. The output provides a structured view of the functions, original command names, and descriptions. ```powershell $result = ./Convert-KubectlHelp.ps1 $result.Commands | Format-Table | Select-Object -First 10 ``` -------------------------------- ### Serializing Crescendo Configuration to JSON (PowerShell) Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/src/experimental/HelpParsers/README.md Illustrates the use of .NET's System.Text.Json.JsonSerializer to convert a PowerShell object (hashtable) into a JSON string, which forms the Crescendo configuration file. ```powershell System.Text.Json.JsonSerializer]::Serialize($h, $sOptions) ``` -------------------------------- ### Define Basic Command Configuration in Crescendo Source: https://context7.com/powershell/crescendo/llms.txt Demonstrates the fundamental structure for wrapping a native command, such as 'ls', into a PowerShell cmdlet. It includes mapping native arguments to PowerShell parameters with specific types and positions. ```json { "$schema": "https://aka.ms/PowerShell/Crescendo/Schemas/2022-06", "Commands": [ { "Verb": "Get", "Noun": "FileList", "OriginalName": "/bin/ls", "Description": "Lists files and directories using the native ls command", "Usage": { "Synopsis": "List directory contents" }, "Parameters": [ { "Name": "Path", "OriginalName": "", "Position": 0, "OriginalPosition": 10, "ParameterType": "string", "DefaultValue": ".", "Description": "The directory path to list" }, { "Name": "Long", "OriginalName": "-l", "ParameterType": "switch", "Description": "Use long listing format" }, { "Name": "All", "OriginalName": "-a", "ParameterType": "switch", "Description": "Include hidden files" } ] } ] } ``` -------------------------------- ### Define Parameters for Crescendo Commands Source: https://context7.com/powershell/crescendo/llms.txt Demonstrates how to create various parameter types including strings, switches, mandatory parameters with validation, and pipeline-enabled inputs using New-ParameterInfo. ```powershell # Create a basic string parameter $pathParam = New-ParameterInfo -Name "Path" -OriginalName "" $pathParam.ParameterType = "string" $pathParam.Position = 0 $pathParam.OriginalPosition = 10 $pathParam.DefaultValue = "." $pathParam.Description = "The path to list" # Create a switch parameter $verboseParam = New-ParameterInfo -Name "Detailed" -OriginalName "-l" $verboseParam.ParameterType = "switch" $verboseParam.Description = "Show detailed listing" # Create a mandatory parameter with validation $formatParam = New-ParameterInfo -Name "Format" -OriginalName "--format" $formatParam.Mandatory = $true $formatParam.ParameterSetName = @("Formatted") $formatParam.AdditionalParameterAttributes = @('[ValidateSet("json","table","csv")]') # Create a pipeline parameter $inputParam = New-ParameterInfo -Name "InputObject" -OriginalName "" $inputParam.ValueFromPipeline = $true $inputParam.ValueFromPipelineByPropertyName = $true ``` -------------------------------- ### Create Proxy Function for Linux apt Command with Output Handling Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/help/en-US/about_Crescendo.md This JSON configuration defines a proxy function for the Linux 'apt' command. It includes an OutputHandler to parse the command's text output and convert it into PSCustomObject, making the data usable with other PowerShell cmdlets. ```json { "$schema": "https://aka.ms/PowerShell/Crescendo/Schemas/2021-11", "Verb": "Get", "Noun":"InstalledPackage", "OriginalName": "apt", "OriginalCommandElements": [ "-q", "list", "--installed" ], "OutputHandlers": [ { "ParameterSetName":"Default", "Handler": "$args[0]|select-object -skip 1|foreach-object{$n,$v,$p,$s = \"$_\" -split ' ';[pscustomobject]@{Name=$n -replace '/now';Version=$v;Architecture=$p;State = $s.Trim('[]') -split ','}}" } ] } ``` -------------------------------- ### Overwriting an Existing Crescendo Module Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/help/Export-CrescendoModule.md Shows how to use the -Force parameter to overwrite an existing module file if it already exists in the destination path. ```powershell Export-CrescendoModule netsh netsh*.json -force ``` -------------------------------- ### Define Parameter Regex Pattern Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/src/experimental/HelpParsers/README.md A regular expression pattern designed to capture parameter names, types, and help descriptions from command-line help output, specifically targeting verbose parameter formats. ```powershell $parmPattern = "--(?[-\w]+)\s(?\w+)\s+(?.*)|--(?[-\w]+)\s+(?.*)" ``` -------------------------------- ### Generate DockerImage Crescendo Command Configuration Source: https://context7.com/powershell/crescendo/llms.txt This PowerShell script demonstrates how to programmatically create a Crescendo command configuration for listing Docker images. It defines the command verb, noun, original command elements, description, supported platforms, and output handlers for parsing JSON output. It also shows how to add a parameter with argument transformation. ```powershell # Step 1: Create command configurations programmatically $getImages = New-CrescendoCommand -Verb "Get" -Noun "DockerImage" -OriginalName "docker" $getImages.OriginalCommandElements = @("image", "ls", "--format", "{{json .}}") $getImages.Description = "Lists Docker images" $getImages.Platform = @("Windows", "Linux", "MacOS") $handler = New-OutputHandler $handler.ParameterSetName = "Default" $handler.Handler = '$input | ConvertFrom-Json' $handler.StreamOutput = $true $getImages.OutputHandlers = @($handler) # Step 2: Add a parameter $repoParam = New-ParameterInfo -Name "Repository" -OriginalName "--filter" $repoParam.ParameterType = "string" $repoParam.Description = "Filter by repository name" $repoParam.ArgumentTransform = '"reference=" + $args[0]' $getImages.Parameters.Add($repoParam) # Step 3: Export configuration to JSON $getImages | Export-CrescendoCommand -fileName "./docker.crescendo.json" -Force # Step 4: Generate the module Export-CrescendoModule -ModuleName "DockerTools" -ConfigurationFile "./docker.crescendo.json" -Force # Step 5: Import and test Import-Module ./DockerTools.psm1 Get-DockerImage | Format-Table Repository, Tag, Size Get-DockerImage -Repository "nginx" | Select-Object ID, Repository # Step 6: Verify Crescendo attribution Test-IsCrescendoCommand Get-DockerImage ``` -------------------------------- ### Implement Crescendo Native Command Wrapper Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/test/assets/ProxyContentTest2.txt This snippet demonstrates the structure of a Crescendo-generated PowerShell function. It includes parameter mapping, argument transformation, and native command execution with output handling. ```PowerShell function Get-Crescendo { [CmdletBinding()] param([Parameter()][object]$pName) BEGIN { $__PARAMETERMAP = @{ pName = @{ OriginalName = '--OriginalName' OriginalPosition = '0' ParameterType = 'object' ArgumentTransform = '$args' ArgumentTransformType = 'inline' } } $__outputHandlers = @{ Default = @{ StreamOutput = $true; Handler = { $input; Pop-CrescendoNativeError -EmitAsError } } } } PROCESS { $__commandArgs = @() # Logic to process parameters and build command arguments # ... (omitted for brevity) if ( $PSCmdlet.ShouldProcess("/bin/ls $__commandArgs")) { & "/bin/ls" $__commandArgs 2>&1| Push-CrescendoNativeError | & $__handler } Pop-CrescendoNativeError -EmitAsError } } ``` -------------------------------- ### Handle NoGap Parameters Source: https://context7.com/powershell/crescendo/llms.txt Configures parameters that require a specific 'key=value' syntax without spaces, common in CLI tools like Docker. The 'NoGap' property ensures the parameter name and value are concatenated correctly. ```json { "$schema": "https://aka.ms/PowerShell/Crescendo/Schemas/2022-06", "Commands": [ { "Verb": "Get", "Noun": "DockerContainerLog", "OriginalName": "docker", "OriginalCommandElements": ["logs"], "Parameters": [ { "Name": "Container", "OriginalName": "", "Position": 0, "ParameterType": "string", "Mandatory": true }, { "Name": "Since", "OriginalName": "--since=", "NoGap": true, "ParameterType": "string", "Description": "Show logs since timestamp (e.g., 2021-01-01T00:00:00)" }, { "Name": "Tail", "OriginalName": "--tail=", "NoGap": true, "ParameterType": "int", "Description": "Number of lines to show from end of logs" } ] } ] } ``` -------------------------------- ### Restrict Commands by Platform Source: https://context7.com/powershell/crescendo/llms.txt Shows how to limit the availability of a command to specific operating systems like Linux or MacOS. It also demonstrates using an inline output handler to process command output via external tools. ```json { "$schema": "https://aka.ms/PowerShell/Crescendo/Schemas/2022-06", "Commands": [ { "Verb": "Get", "Noun": "NetworkInterface", "OriginalName": "ifconfig", "Platform": ["Linux", "MacOS"], "Aliases": ["Get-NetConfig"], "Description": "Displays network interface configuration", "Usage": { "Synopsis": "Run ifconfig to get network configuration" }, "Parameters": [ { "Name": "Interface", "OriginalName": "", "ParameterType": "string", "Position": 0, "Description": "Specific interface name to query" } ], "OutputHandlers": [ { "ParameterSetName": "Default", "HandlerType": "Inline", "StreamOutput": true, "Handler": "$input | jc --ifconfig | ConvertFrom-Json" } ] } ] } ``` -------------------------------- ### Import Crescendo JSON Configuration File - PowerShell Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/help/Import-CommandConfiguration.md Imports a Crescendo JSON file to create a PowerShell object representing a command configuration. This object can then be used to generate a proxy function for a native command. The JSON file specifies details like the command's verb, noun, parameters, and help information. ```powershell Import-CommandConfiguration -File "ifconfig.crescendo.json" ``` -------------------------------- ### Inspect and Manipulate Configurations with Import-CommandConfiguration Source: https://context7.com/powershell/crescendo/llms.txt Imports a JSON configuration file into a Command object for programmatic inspection, modification, or conversion to function code strings. ```powershell # Import a configuration and inspect its structure $config = Import-CommandConfiguration -file "ifconfig.crescendo.json" # View the generated function details $config.Verb # "Invoke" $config.Noun # "ifconfig" $config.OriginalName # "ifconfig" $config.Parameters # Parameter definitions $config.OutputHandlers # Output handler definitions # Convert to function code string $functionCode = $config.ToString() Write-Output $functionCode # Export configuration back to JSON $config.ExportConfigurationFile("./updated-ifconfig.crescendo.json") ``` -------------------------------- ### Implement Output Handlers for Native Commands Source: https://context7.com/powershell/crescendo/llms.txt Shows how to process raw text output from a native command into structured PowerShell objects. Uses an inline script block to convert JSON output from the native tool into a typed PowerShell object. ```json { "$schema": "https://aka.ms/PowerShell/Crescendo/Schemas/2022-06", "Commands": [ { "Verb": "Get", "Noun": "DockerImage", "OriginalName": "docker", "OriginalCommandElements": ["image", "ls", "--format", "{{json .}}"], "OutputHandlers": [ { "ParameterSetName": "Default", "HandlerType": "Inline", "StreamOutput": true, "Handler": "$input | ConvertFrom-Json | Add-Member -TypeName DockerImage -PassThru" } ] } ] } ``` -------------------------------- ### Create Proxy Function for Unix ls Command Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/help/en-US/about_Crescendo.md This JSON configuration defines a proxy function for the Unix '/bin/ls' command. It maps PowerShell parameters 'Path' and 'Detail' to the native command's arguments, enabling pipeline integration and switch parameter functionality. ```json { "$schema": "https://aka.ms/PowerShell/Crescendo/Schemas/2021-11", "Verb": "Get", "Noun":"FileList", "OriginalName": "/bin/ls", "Parameters": [ {"Name": "Path","OriginalName": "", "OriginalPosition": 1, "Position": 0, "DefaultValue": "." }, {"Name": "Detail","OriginalName": "-l","ParameterType": "switch"} ] } ``` -------------------------------- ### Configure Privilege Elevation in Crescendo Source: https://context7.com/powershell/crescendo/llms.txt Demonstrates how to define a command that requires administrative privileges. It uses the 'Elevation' property to specify a native app wrapper and handles output via a CSV conversion. ```json { "$schema": "https://aka.ms/PowerShell/Crescendo/Schemas/2022-06", "Commands": [ { "Verb": "Get", "Noun": "WhoAmI", "OriginalName": "whoami", "Platform": ["Windows"], "OriginalCommandElements": ["/FO", "CSV"], "Elevation": { "Command": "Invoke-WindowsNativeAppWithElevation", "Arguments": [ { "OriginalName": "-Credential", "DefaultValue": "(Get-Credential)" } ] }, "OutputHandlers": [ { "ParameterSetName": "Default", "Handler": "$input | ConvertFrom-CSV", "StreamOutput": true } ], "Parameters": [ { "Name": "Groups", "OriginalName": "/Groups", "ParameterType": "switch", "Description": "Display group membership" } ] } ] } ``` -------------------------------- ### Generate PowerShell Modules with Export-CrescendoModule Source: https://context7.com/powershell/crescendo/llms.txt Creates a deployable PowerShell module from Crescendo JSON configuration files. It supports force overwriting, manifest preservation, and returning generation details. ```powershell # Generate a module from multiple configuration files Export-CrescendoModule -ModuleName "MyDockerModule" -ConfigurationFile "docker*.crescendo.json" -Force # Import and use the generated module Import-Module ./MyDockerModule.psm1 Get-DockerImage | Where-Object { $_.Repository -eq "nginx" } # Generate with manifest preservation (don't overwrite existing psd1) Export-CrescendoModule -ModuleName "NetworkTools" -ConfigurationFile "*.crescendo.json" -NoClobberManifest # Get module generation details with PassThru $result = Export-CrescendoModule -ModuleName "Tools" -ConfigurationFile "tools.json" -PassThru $result.ModulePath # Path to generated .psm1 $result.ManifestArguments # Arguments used for New-ModuleManifest ``` -------------------------------- ### PowerShell Parameter Configuration with Crescendo Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/test/assets/ParameterInfo2.txt Illustrates advanced parameter configuration using the Parameter attribute, specifying properties like Position, ValueFromPipeline, ValueFromPipelineByPropertyName, ValueFromRemainingArguments, Mandatory, and ParameterSetName. Also shows PSDefaultValue for setting default parameter values. ```powershell [Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,ValueFromRemainingArguments=$true,Mandatory=$true,ParameterSetName='psetName')] [PSDefaultValue(Value="defaultValue")] [int]$Param1 = "defaultValue" ``` -------------------------------- ### Transform Command Arguments Source: https://context7.com/powershell/crescendo/llms.txt Illustrates how to modify parameter values before they are passed to the underlying native command. It supports both inline script blocks and external PowerShell functions for transformation. ```json { "$schema": "https://aka.ms/PowerShell/Crescendo/Schemas/2022-06", "Commands": [ { "Verb": "Get", "Noun": "ProcessInfo", "OriginalName": "ps", "Parameters": [ { "Name": "ProcessId", "OriginalName": "-p", "ParameterType": "int[]", "Description": "Process IDs to query", "ArgumentTransform": "$args -join ','", "ArgumentTransformType": "Inline" }, { "Name": "Format", "OriginalName": "-o", "ParameterType": "string[]", "Description": "Output format columns", "ArgumentTransform": "ConvertTo-PsFormatString", "ArgumentTransformType": "Function" } ] } ] } ``` -------------------------------- ### Execute Native Command via Crescendo Wrapper Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/test/assets/ProxyContentTest1.txt A generated PowerShell function that maps parameters to native command arguments, executes the binary, and processes output streams. It includes logic for handling switch parameters, argument transformations, and error reporting via a native error queue. ```powershell function Get-Crescendo { [CmdletBinding()] param( ) BEGIN { $PSNativeCommandUseErrorActionPreference = $false $__CrescendoNativeErrorQueue = [System.Collections.Queue]::new() $__PARAMETERMAP = @{} $__outputHandlers = @{ Default = @{ StreamOutput = $true; Handler = { $input; Pop-CrescendoNativeError -EmitAsError } } } } PROCESS { $__boundParameters = $PSBoundParameters $__defaultValueParameters = $PSCmdlet.MyInvocation.MyCommand.Parameters.Values.Where({$_.Attributes.Where({$_.TypeId.Name -eq "PSDefaultValueAttribute"})}).Name $__defaultValueParameters.Where({ !$__boundParameters["$_"] }).ForEach({$__boundParameters["$_"] = get-variable -value $_}) $__commandArgs = @() $MyInvocation.MyCommand.Parameters.Values.Where({$_.SwitchParameter -and $_.Name -notmatch "Debug|Whatif|Confirm|Verbose" -and ! $__boundParameters[$_.Name]}).ForEach({$__boundParameters[$_.Name] = [switch]::new($false)}) if ($__boundParameters["Debug"]){wait-debugger} foreach ($paramName in $__boundParameters.Keys| Where-Object {!$__PARAMETERMAP[$_].ApplyToExecutable}| Where-Object {!$__PARAMETERMAP[$_].ExcludeAsArgument}| Sort-Object {$__PARAMETERMAP[$_].OriginalPosition}) { $value = $__boundParameters[$paramName] $param = $__PARAMETERMAP[$paramName] if ($param) { if ($value -is [switch]) { if ($value.IsPresent) { if ($param.OriginalName) { $__commandArgs += $param.OriginalName } } elseif ($param.DefaultMissingValue) { $__commandArgs += $param.DefaultMissingValue } } elseif ( $param.NoGap ) { if($param.ArgumentTransform -ne '$args') { $transform = $param.ArgumentTransform if($param.ArgumentTransformType -eq 'inline') { $transform = [scriptblock]::Create($param.ArgumentTransform) } $__commandArgs += & $transform $value } else { $pFmt = "{0}{1}" if($value -match "\s") { $pFmt = "{0}\"{1}\"" } $__commandArgs += $pFmt -f $param.OriginalName, $value } } else { if($param.OriginalName) { $__commandArgs += $param.OriginalName } if($param.ArgumentTransformType -eq 'inline') { $transform = [scriptblock]::Create($param.ArgumentTransform) } else { $transform = $param.ArgumentTransform } $__commandArgs += & $transform $value } } } $__commandArgs = $__commandArgs | Where-Object {$_ -ne $null} if ($__boundParameters["Debug"]){wait-debugger} if ( $__boundParameters["Verbose"]) { Write-Verbose -Verbose -Message "/bin/ls" $__commandArgs | Write-Verbose -Verbose } $__handlerInfo = $__outputHandlers[$PSCmdlet.ParameterSetName] if (! $__handlerInfo ) { $__handlerInfo = $__outputHandlers["Default"] } $__handler = $__handlerInfo.Handler if ( $PSCmdlet.ShouldProcess("/bin/ls $__commandArgs")) { if ( -not (Get-Command -ErrorAction Ignore "/bin/ls")) { throw "Cannot find executable '/bin/ls'" } if ( $__handlerInfo.StreamOutput ) { if ( $null -eq $__handler ) { & "/bin/ls" $__commandArgs } else { & "/bin/ls" $__commandArgs 2>&1| Push-CrescendoNativeError | & $__handler } } else { $result = & "/bin/ls" $__commandArgs 2>&1| Push-CrescendoNativeError & $__handler $result } } Pop-CrescendoNativeError -EmitAsError } } ``` -------------------------------- ### Configure Mutually Exclusive Parameter Sets Source: https://context7.com/powershell/crescendo/llms.txt Configures a command with multiple parameter sets to handle different operational modes, such as listing, extracting, or creating archives. This ensures that only valid combinations of parameters are accepted by the resulting cmdlet. ```json { "$schema": "https://aka.ms/PowerShell/Crescendo/Schemas/2022-06", "Commands": [ { "Verb": "Invoke", "Noun": "Tar", "OriginalName": "/usr/bin/tar", "SupportsShouldProcess": true, "DefaultParameterSetName": "list", "Description": "Manipulates tar archives", "Parameters": [ { "Name": "Archive", "OriginalName": "-f", "Position": 0, "ParameterType": "string", "Mandatory": true, "ValueFromPipeline": true }, { "Name": "List", "OriginalName": "-t", "ParameterType": "switch", "ParameterSetName": ["list"], "Description": "List archive contents" }, { "Name": "Extract", "OriginalName": "-x", "ParameterType": "switch", "ParameterSetName": ["extract"], "Description": "Extract archive contents" }, { "Name": "Create", "OriginalName": "-c", "ParameterType": "switch", "ParameterSetName": ["create"], "Description": "Create a new archive" }, { "Name": "Files", "OriginalName": "", "OriginalPosition": 1, "ParameterType": "string[]", "ParameterSetName": ["create"], "Description": "Files to add to the archive" }, { "Name": "Verbose", "OriginalName": "-v", "ParameterType": "switch", "Description": "Verbose output" } ] } ] } ``` -------------------------------- ### Define Output Handlers for Native Commands Source: https://context7.com/powershell/crescendo/llms.txt Configures how native command output is processed into PowerShell objects using New-OutputHandler, supporting inline scripts, custom functions, or bypass modes. ```powershell # Create an inline output handler for JSON conversion $handler = New-OutputHandler $handler.ParameterSetName = "Default" $handler.Handler = '$input | ConvertFrom-Json' $handler.HandlerType = "Inline" $handler.StreamOutput = $true # Create a function-based handler $funcHandler = New-OutputHandler $funcHandler.ParameterSetName = "Detailed" $funcHandler.Handler = "ConvertTo-DockerObject" $funcHandler.HandlerType = "Function" $funcHandler.StreamOutput = $true # Create a bypass handler $bypassHandler = New-OutputHandler $bypassHandler.ParameterSetName = "Raw" $bypassHandler.HandlerType = "ByPass" ``` -------------------------------- ### PowerShell Parameter Validation and Aliasing Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/test/assets/ParameterInfo2.txt Demonstrates the use of ValidateRange and ValidateNotNullOrEmpty attributes for input validation, and the Alias attribute for providing alternative parameter names. These are essential for robust command-line interface design. ```powershell [ValidateRange(1,10)] [ValidateNotNullOrEmpty()] [Alias('alias1','alias2')] [int]$Param1 ``` -------------------------------- ### Define Parameter Mapping in PowerShell Crescendo Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/test/assets/ParameterMap1.txt This snippet demonstrates the configuration of a parameter mapping object for Crescendo. It defines how a specific parameter is handled, including its position, type, and transformation logic for the target executable. ```powershell $__PARAMETERMAP = @{ P1 = @{ OriginalName = '-p1' OriginalPosition = '0' Position = '2147483647' ParameterType = 'object' ApplyToExecutable = $False NoGap = $False DefaultMissingValue = 'Default missing value' ArgumentTransform = '$args' ArgumentTransformType = 'inline' } } ``` -------------------------------- ### Export Command Objects with Export-CrescendoCommand Source: https://context7.com/powershell/crescendo/llms.txt Exports existing Command objects into Crescendo JSON configuration files, supporting both individual file generation and combined file output. ```powershell # Create multiple commands and export to separate files $dockerPs = New-CrescendoCommand -Verb "Get" -Noun "DockerContainer" -OriginalName "docker" $dockerImages = New-CrescendoCommand -Verb "Get" -Noun "DockerImage" -OriginalName "docker" # Export each command to its own file (Verb-Noun.crescendo.json) $dockerPs, $dockerImages | Export-CrescendoCommand -targetDirectory "./configs" # Export all commands to a single combined file $dockerPs, $dockerImages | Export-CrescendoCommand -fileName "docker-commands.crescendo.json" -Force ``` -------------------------------- ### Define Output Handler for JSON Conversion Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/help/en-US/about_Crescendo.md This snippet demonstrates how to define an OutputHandler in a Crescendo JSON configuration to convert JSON output from a native command into PowerShell objects. It specifies the parameter set and the script block to perform the conversion. ```json { "OutputHandler": [ "ParameterSetName": "Default" "Handler": "$args[0] | ConvertFrom-Json" ] } ``` -------------------------------- ### Verify Crescendo Command Metadata Source: https://context7.com/powershell/crescendo/llms.txt Uses Test-IsCrescendoCommand to validate if a command was generated by the Crescendo module and inspect its elevation requirements. ```powershell # Test a single command $result = Test-IsCrescendoCommand -Command "Get-DockerImage" $result.IsCrescendoCommand $result.RequiresElevation # Test multiple commands via pipeline Get-Command -Module MyDockerModule | Test-IsCrescendoCommand # Test by function info object $funcInfo = Get-Command Get-DockerContainer Test-IsCrescendoCommand -Command $funcInfo ``` -------------------------------- ### Define Advanced PowerShell Parameter Attributes Source: https://github.com/powershell/crescendo/blob/master/Microsoft.PowerShell.Crescendo/test/assets/ParameterInfo3.txt This snippet illustrates how to apply validation, aliasing, and pipeline binding attributes to a PowerShell parameter. It ensures input integrity using ValidateRange and ValidateNotNullOrEmpty, while configuring pipeline behavior and default values. ```powershell [ValidateRange(1,10)] [ValidateNotNullOrEmpty()] [Alias('alias1','alias2')] [Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true,ValueFromRemainingArguments=$true)] [PSDefaultValue(Value="defaultValue")] [int]$Param1 = "defaultValue" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.