Advertisement
Old-Lost

Dynamic Parameter Example

Jan 13th, 2017
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Restart-RemoteService {
  2.    [CmdletBinding()]
  3.    Param ($ComputerName = $env:COMPUTERNAME)
  4.    DynamicParam {
  5.      
  6.       # Set the dynamic parameters' name
  7.       $ParameterName = 'Service'
  8.      
  9.       # Create the dictionary
  10.       $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
  11.      
  12.       # Create the collection of attributes
  13.       $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
  14.      
  15.       # Create and set the parameters' attributes
  16.       $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
  17.       $ParameterAttribute.Mandatory = $true
  18.       $ParameterAttribute.Position = 1
  19.      
  20.       # Add the attributes to the attributes collection
  21.       $AttributeCollection.Add($ParameterAttribute)
  22.      
  23.       # Generate and set the ValidateSet
  24.       $arrSet = Get-WmiObject Win32_Service -ComputerName $computername | select -ExpandProperty Name
  25.       $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
  26.      
  27.       # Add the ValidateSet to the attributes collection
  28.       $AttributeCollection.Add($ValidateSetAttribute)
  29.      
  30.       # Create and return the dynamic parameter
  31.       $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
  32.       $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
  33.       return $RuntimeParameterDictionary
  34.    }
  35.    
  36.    begin {
  37.       # Bind the parameter to a friendly variable
  38.       $Service = $PsBoundParameters[$ParameterName]
  39.    }
  40.    
  41.    process {
  42.       Write-Debug 'ham'
  43.       ForEach ($machine in $computername) {
  44.          write-host "Stopping service $service on host $machine..." -NoNewline
  45.          Get-WmiObject -ClassName Win32_Service -ComputerName $machine | Where Name -eq $service | % StopService | Out-Null
  46.          write-host "[OK]" -ForegroundColor Cyan
  47.          
  48.          Write-Host "Starting Service $service on host $machine..." -NoNewline
  49.          Get-WmiObject -ClassName Win32_Service -ComputerName $machine | Where Name -eq $service | % StartService | Out-Null
  50.          write-host "[OK]" -ForegroundColor Cyan
  51.       }
  52.    }
  53.    
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement