PowerShell:如何向自定义对象添加条目及修改现有内容
Great job using [pscustomobject] to manage your script's state information — this is a clean, maintainable approach to avoid the chaos of passing dozens of individual variables between functions. Let's break down your questions and validate your implementation:
1. Adding an ActionMenuChoice Type Entry
To append a new entry of type ActionMenuChoice to your $myScriptObject collection, you can create a new custom object and add it to the existing array. For small-scale use cases, the += operator works perfectly:
# Create the new ActionMenuChoice entry $newMenuChoice = [pscustomobject]@{ kind = "ActionMenuChoice" name = "Selected Menu Option:" value = "Export Dataset" } # Append to the existing state object collection $myScriptObject += $newMenuChoice
For bulk additions, you can generate multiple entries at once and merge them in one step:
# Batch create ActionMenuChoice entries $batchMenuEntries = @( ("ActionMenuChoice", "Primary Option", "Import Data"), ("ActionMenuChoice", "Secondary Option", "Generate Report") ) | ForEach-Object { [pscustomobject]@{ kind = $_[0] name = $_[1] value = $_[2] } } # Merge batch entries into the main collection $myScriptObject += $batchMenuEntries
2. Modifying Existing Entry Content
To update an existing entry (like changing the "Current Step" value), use Where-Object to filter the target entry, then directly modify its value property. This is precise and avoids accidentally altering other entries:
# Locate the target entry and update its value $myScriptObject | Where-Object { $_.kind -eq "status" -and $_.name -eq "Current Step:" } | ForEach-Object { $_.value = "Prompting for Login" }
If you're certain there's only one matching entry, you can simplify it to:
$targetStep = $myScriptObject | Where-Object { $_.kind -eq "status" -and $_.name -eq "Current Step:" } $targetStep.value = "Prompting for Login"
Is This Implementation Reasonable?
Absolutely — this is a best practice for managing script state and inter-function variable transfer in PowerShell:
- Clear & Self-Documenting: Each entry has explicit
kind,name, andvalueproperties, making it easy to understand what state information is being tracked, even for someone reading your code later. - Scalable: You can easily add new entry types or extend the object with additional properties (like a
timestampto track when state was updated) without rewriting core logic. - Simplified Function Passing: Instead of defining 10+ parameters for a function, you can pass the entire
$myScriptObjectcollection, and the function can filter out only the state data it needs. - Maintainable: Centralizing state management means you only need to adjust the object structure in one place if requirements change, rather than updating variable names across multiple functions.
Small Optimization Tip
If you expect to add/remove entries frequently, consider using a [System.Collections.Generic.List[pscustomobject]] instead of a regular array. Arrays in PowerShell are immutable, so += creates a new array each time — a List allows in-place additions/removals for better performance:
# Initialize as a List instead of an array $myScriptObject = [System.Collections.Generic.List[pscustomobject]]@( @("status", "Selected Operation(s):", "None"), @("status", "Current Operation:", "None"), @("status", "Current Step:", "Prompting for Script Action"), @("test", "This is just for testing", "1,2,3") ) | ForEach-Object { [pscustomobject]@{kind = $_[0]; name = $_[1]; value = $_[2]} } # Add entries with List's Add() method $myScriptObject.Add([pscustomobject]@{ kind = "ActionMenuChoice" name = "New Option" value = "Archive Data" })
内容的提问来源于stack exchange,提问作者SherpaPsy

