Chapters/build-a-basic-function-and-module/snippets.ps1

# design input parameters
function Get-MachineInfo {
 Param(
  [string[]]$ComputerName,
  [string]$LogFailuresToPath,
  [string]$Protocol,
  [switch]$ProtocolFallback
 )}


# write the code
function Get-MachineInfo {
 Param(
  [string[]]$ComputerName,
  [string]$LogFailuresToPath,
  [string]$Protocol = "Wsman",
  [switch]$ProtocolFallback
 )
 
 foreach ($computer in $computername) {
 
  # Establish session protocol
  if ($protocol -eq 'Dcom') {
   $option = New-CimSessionOption -Protocol Dcom
  } else {
   $option = New-CimSessionOption -Protocol Wsman
  }
 
  # Connect session
  $session = New-CimSession -ComputerName $computer -SessionOption $option
  
  # Query data
  $os = Get-CimInstance -ClassName Win32_OperatingSystem -CimSession $session
  
  # Close session
  $session | Remove-CimSession
  
  # Output data
  # TODO
 
 } #foreach
 
} #function


# if construct model
If (<expression>) {
    # code
} ElseIf (<expression>) {
    # coded
} ElseIf (<expression>) {
    # code
} Else {
    # code
}



# foreach construct model
ForEach ($item in $collection) {
    # code
}



# variable naming for foreach
$names = Get-Content names.txt
ForEach ($name in $names) {
    # code
}



# naming is for human convenience, shell doesn't care
$names = Get-Content names.txt
ForEach ($purple in $unicorns) {
    # code
}



# design the output
function Get-MachineInfo {
 Param(
  [string[]]$ComputerName,
  [string]$LogFailuresToPath,
  [string]$Protocol = "Wsman",
  [switch]$ProtocolFallback
 )
 
 foreach ($computer in $computername) {
 
  # Establish session protocol
  if ($protocol -eq 'Dcom') {
   $option = New-CimSessionOption -Protocol Dcom
  } else {
   $option = New-CimSessionOption -Protocol Wsman
  }
 
  # Connect session
  $session = New-CimSession -ComputerName $computer -SessionOption $option
  
  # Query data
  $os = Get-CimInstance -ClassName Win32_OperatingSystem -CimSession $session
  
  # Close session
  $session | Remove-CimSession
  
  # Output data
  $os | Select-Object -Prop @{n='ComputerName';e={$computer}},
                            Version,ServicePackMajorVersion
 
 } #foreach
 
} #function



# new module manifest - fix file path as needed
Cd "\Program Files\WindowsPowerShell\Modules\Toolmaking"
New-ModuleManifest -Path .\Toolmaking.psd1
                   -Author "Don Jones & Jeff Hicks"
                   -RootModule .\Toolmaking.psm1
                   -FunctionsToExport @('Get-MachineInfo')
                   -Description "Sample Toolmaking module"
                   -ModuleVersion 1.0.0.0



# test command
Get-MachineInfo -ComputerName localhost



# valid paths for a module
$env:PSModulePath