Saturday, February 13, 2016

Think in PowerShell code

(1) PS has coding construct such as range, dictionary, array, function, module, for, switch,if
(2) Pipeline can do foreach, where, similarly cmdletBinding().
(3) help and get-command are similar but the latter can filter down to specific ones. 
(4) internal variable cannot get from help neither member. so get-variable and get-member would be needed.
$Subnet="192.168.0."
200..210|where{Test-connection "$Subnet$_" -count 1 -quiet}|foreach{"$subnet$_"}  #where taking in True/False by _quiet
100..120|foreach{ Test-Connection "192.168.0.$_" -count 1} help Test-Connection -wh show-command Test-Connection
100..120 | where { test-Connection "192.168.$_" -quiet } #show 100,101, 109 only success ones

Function
{
   [CmdletBinding()]
   Param (
      [parameter(Mandatory=$true, helpmessage='hel']
      $subnet,
      [int]$start
   )
   write-verbose "..." # cmdletbinding allows -Verbose common param and code inside ps1.
}

Function PipeEnabledFun()
{
  begin {}
  process { $ret=$_;}
  end {return $ret}

}

Several function made module as psm1 Import-Module.

help export, select,ExecutionPolicy.

Get-variable, $PSVersion, etc.

help get-command (better than help), get-command *counter*

Reflection:  get-service | get-member
$dict={$v="v1"; $v2="v2"}
$array="s1","s2"
if($v -eq "v") 

switch($v)
{
  41 {"test"; break;}
  default {}
}

foreach($file in get-childItem)
{
  if ($file.Name -like "test")
}

$ScriptBlock ={test-Connection}
&$scriptblock;

No comments:

Post a Comment