functionSafety { # step 1: add -WhatIf and -Confirm, and mark as harmful [CmdletBinding(SupportsShouldProcess,ConfirmImpact="High")] param ( [Parameter(Mandatory)] $Something )
# step 2: abort function when confirmation was rejected if (!$PSCmdlet.ShouldProcess($env:computername, "doing something harmful")) { Write-Warning"Aborted!" return }
# ...and turn it into a hash table $hashtable = $process | ForEach-Object {
$object = $_
# determine the property names in this object and create a # sorted list $columns = $_ | Get-Member-MemberType *Property | Select-Object-ExpandProperty Name | Sort-Object
# create an empty hash table $hashtable = @{}
# take all properties, and add keys to the hash table for each property $columns | ForEach-Object { # exclude empty properties if (![String]::IsNullOrEmpty($object.$_)) { # add a key (property) to the hash table with the # property value $hashtable.$_ = $object.$_ } } $hashtable }
In the previous tip we explained how you can dump all the legal values for a PowerShell attribute. Today we’ll take a look at the [Parameter()] attribute and its value DontShow. Take a look at this function: 在前一个技能中我们介绍了如何导出一个 PowerShell 属性的所有合法值。今天我们将关注 [Parameter()] 属性和它的值 DontShow。我们来看看这个函数:
dynamicparam { # this hash table defines the departments available in each company $data = @{ Microsoft = 'CEO', 'Marketing', 'Delivery' Google = 'Marketing', 'Delivery' Amazon = 'CEO', 'IT', 'Carpool' Facebook = 'CEO', 'Facility', 'Carpool' }
# check to see whether the user already chose a company if ($Company) { # yes, so create a new dynamic parameter $paramDictionary = New-Object-TypeName System.Management.Automation.RuntimeDefinedParameterDictionary $attributeCollection = New-Object-TypeName System.Collections.ObjectModel.Collection[System.Attribute]
# create the appropriate ValidateSet attribute, listing the legal values for # this dynamic parameter $attribute = New-Object System.Management.Automation.ValidateSetAttribute($data.$Company) $attributeCollection.Add($attribute)
process { # if the user entered a string, get the real object if ($PSCmdlet.ParameterSetName -eq'String') { $Service = Get-Service-Name$Name } else { # else, if the user entered (piped) the expected object in the first place, # you are good to go }
# this call tells you which parameter set was invoked $PSCmdlet.ParameterSetName