UNCLASSIFIED

Skip to content
Snippets Groups Projects
Commit df5ef368 authored by brandon scurry's avatar brandon scurry
Browse files

Upload New File

parent 03ca13eb
1 merge request!47Upload New File
= Day 4 PowerShell Student Guide
:toc: auto
== Functions
Just like other scripting languages, Windows PowerShell has the ability to create functions. Functions are new commands made up of PowerShell building blocks. The syntax of a function looks as follows:
.Function syntax
----
function <name> {
code to execute
}
----
=== Function demo
.Example 1 test-it
[source,powershell]
----
function test-it {
'Hello World!'
}
test-it
----
.Example 2 test-me
[source,powershell]
----
function test-me($value) {
if($value) {
Write-Host -ForegroundColor Green "True"
}
else {
Write-host -ForegroundColor Red "False"
}
}
test-me
test-me 1
----
[IMPORTANT]
Show examples of functions with the use of the ```return``` statement
== Parameter Sets, Parameters, Switches
=== Function Parameters
Earlier we learned that cmdlets have parameters and just like cmdlets, functions can have parameters. This is useful if you are expecting a specific argument type. To add parameters to a function, you have to use the *_param()_* argument.
=== Functions with parameters demo
.Example 1 function with parameters
[source,powershell]
----
function test-func {
param(
$param1='Default Value 1', $param2='Default Value 2'
)
"you entered $param1 and $param2"
}
test-func
test-func Hello World
----
.Example 2 function with switch parameter
[source,powershell]
----
function Do-Switch {
param(
[Switch]
$DoSwitch
)
if ($DoSwitch) {
'Switch is done'
}
else {
'Switch off'
}
}
Do-Switch
Do-Switch -DoSwitch
----
== Mandatory Parameters
By default the use of parameters are optional but PowerShell gives you the ability to make function parameters mandatory.
* Mandatory parameters prefix parameter variables with
** [Parameter(Mandatory=$true)]$FirstName
* By default, without this prefix the parameter is optional
* Adding Mandatory parameter to a script will prompt the user if not provided
=== Functions with mandatory parameters demo
.Example 1 function with mandatory parameters
[source,powershell]
----
function test-me {
param (
[Parameter(Mandatory=$true)]
$var
)
"Your name is $var"
}
test-me
test-me Greg
----
.Example 2 function with help message
[source,powershell]
----
function test-message {
param (
[Parameter(Mandatory=$true, HelpMessage='Enter a name please')]
$var
)
"Your name is $var"
}
test-message
!? # Get Help Message
Bob
----
.Example 3 strongly typed mandatory parameters
[source,powershell]
----
function Convert-ToDollars {
param(
[Parameter(Mandatory, HelpMessage='Enter number of Euros.')]
[Double]
$Euro
)
$Dollar = $Euro * 1.4
$Dollar
}
----
== Parameter Binding
Windows PowerShell uses *_ParamterSets_* to define groups of parameters. You can choose between which parameter groups to use but you cannot mix the parameters that are in different groups.
=== Functions with parameter sets demo
.Example 1 parameter sets
[source,powershell]
----
function check-user {
[CmdletBinding(DefaultParameterSetName='A')]
param (
[Parameter(ParameterSetName='A',Mandatory=$true)]
$name,
[Parameter(ParameterSetName='B',Mandatory=$true)]
$id,
[Parameter(ParameterSetName='C',Mandatory=$true)]
$username
)
$var = $PSCmdlet.ParameterSetName
"The $var parameter set was chosen"
}
check-user
check-user -name Bob
check-user -id 1001
check-user -username b1001
----
The function *_check-user_* exither accepts a name, id, or username but not a combination of them. The automatic variable *_$PSCmdlet_* indicates which parameter set was chosen.
Parameter sets can be used to bind input data automatically to the right parameter set.
.Add Soldier PSCustomObject with mandatory Parameters
[source,powershell]
----
Function Add-Soldier {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)][string]$FirstName,
[Parameter(Mandatory=$true)][string]$LastName,
[Parameter(Mandatory=$true)][string]$Rank,
[Parameter(Mandatory=$true)][string]$MOS,
[Parameter(Mandatory=$true)][string]$Position
)
$Soldier = [PSCustomObject]@{
"FirstName" = $FirstName
"LastName" = $LastName
"Rank" = $Rank
"MOS" = $MOS
"Position" = $Position
}
Return $Soldier
}
Add-Soldier
----
=== Functions with binding parameters demo
.Example 1 parameter binding
[source,powershell]
----
function test-user {
[CmdletBinding(DefaultParameterSetName='Name')]
param(
[Parameter(ParameterSetName='Name', Position=0, Mandatory=$true)]
[String]
$name,
[Parameter(ParameterSetNAme='ID', Position=0, Mandatory=$true)]
[Int]
$id
)
$set = $PSCmdlet.ParameterSetName
"The $set parameter set was selected"
if($set -eq 'ID') {
"Their ID is $id"
}
else {
"Their name is $name"
}
}
test-user bob
test-user 1001
----
== Advanced Functions
=== Begin-Process-End
These are designed to work like cmdlets. They consist of a $_PROCESS_* block with optional *_BEGIN_* and/or *_END_* blocks.
.Function Blocks
PROCESS::
Called once for each object in the pipeline.
BEGIN::
Called prior to processing anything in the pipeline.
END::
Called after all the objects in the pipeline have been processed
.Syntax
----
function bare-bones {
[CmdletBinding()]
Param(
<Define Parameters>
)
Begin {
<code>
}
Process {
<code>
}
End {
<code>
}
}
----
=== Advanced Functions demo
.example 1 barebones
[source,powershell]
----
function add-nums {
param(
[Parameter(Mandatory=$true)]
$var1,
[Parameter(Mandatory=$true)]
$var2
)
Begin {
$sum = 0
}
Process {
$sum = $var1 + $var2
}
End {
$sum
}
}
[WARNING]
If you run this function without supplying any numbers, the function will treat the requested nums as strings and concatenate them. This can be bypassed by casting the $vars as ints.
----
.Example 2 advanced use
[source,powershell]
----
function Get-IPConfig {
param(
[Switch]$IP,
[Switch]$Mac,
[Switch]$All
)
Begin {
Clear-Host
}
Process {
if ($Mac) {
ipconfig -all | Select-String "Physical"
}
elseif ($IP) {
ipconfig -all | Select-String "IPv"
}
elseif ($all) {
ipconfig -all
}
else {
ipconfig
}
}
End {
"`n " + (Get-Date).DateTime
}
}
----
== Comments Based Help
* Powershell allows you to create comment-based help for functions and scripts.
* This allows you to build help files that can be accessed with the Get-Help command.
.Single Line Comment
[source,powershell]
----
# Some Code
Get-Process # This is another comment
# Some more code
----
.Multi-Line Comment
[source,powershell]
----
<#
Some Code
#>
----
.Comment Based Help
[source,powershell]
----
<#
.SYNOPSIS
>PARAMETER Something
...etc
#>
----
* Use special help comment keywords to provide help topics for functions and scripts
* The Get-Help cmdlet displays comment-based help in the same format in which it displays the cmdlet help topics
* Even supports Get-Help -parameters such as:
** -Detailed, -Full, -Example, -Online
* Comment-based help primarily appears at the beginning of the code
** This method is typically only be preceded by comments and blank lines
* Functions can also use this comment based help
.Keywords can appear in any order and are not case-sensitive
|===
|.SYNOPSIS | A brief description of the function or script
|.DESCRIPTION | A detailed description of the function or script
|.PARAMETER <Name> | The description of a parameter Add a .PARAMETER keyword for each parameter in the function or script syntax
|.EXAMPLE | A sample command, optionally followed by sample output and a description
Repeat this keyword for each example
|.INPUTS | The .NET Framework object types that can be piped in
|.OUTPUTS | The .NET Framework object type that the cmdlet returns
|.NOTES | Additional information about the function or script
|.LINK | Can also include a Uniform Resource Identifier (URI) to an online link
- The link opens when you use the -Online parameter of Get-Help
Also for a related topic; the value appears must be comment out
|.COMPONENT | The technology or feature that the function or script uses, or to which it is related
|.ROLE | The user role for the help topic
|.FUNCTIONALITY | The intended use of the function
|===
.The following are automatically generated by the Get-Help cmdlet
|===
|Name:|By default, is taken from the script or function name
|Syntax:|Is generated from the function or script syntax
|Parameter List:|Is generated from parameter keywords
|Common Parameters:|Are added to the syntax and parameter list of the help topic, even if they have no effect
Get-Help about_CommonParameters.
|Parameter Attribute Table:|Get-Help generates the parameter attributes table when you use the Full or Parameter parameter
The value of the Required, Position, and Default value attributes is from the function or script syntax
Note:
Default values do not appear in the parameter attribute table, even when they are defined in the function or script
To help users, list the default value in the parameter description.
|Remarks:|Is automatically generated from the function or script name
You cannot change or affect its content
|===
.Get-TopMemoryProcesses.ps1
[source,powershell]
----
<#
.SYNOPSIS
Example of Comment Based Help
.DeScRiPtIoN
Note that this is case-insensitive
.Example
./Get-TopMemoryProcess -Top 5
.Example
./Get-TopMemoryProcess -ComputerName Server1 -Top 20
.Parameter Computer
Specific target computer
Defaults to localhost
.Parameter Top
Specify desired number of top processes
.Notes
Checkout my GitHub Page!
.link
https://github.com/high101bro/PoSh-ACME
#>
param (
$ComputerName = 'localhost',
$Top = 10
)
Get-WMIObject -Class Win32_Process -ComputerName $ComputerName `
| Sort-Object -Property WorkingSetSize -Descending `
| Select-Object -Property Name, @{Name='Memory';Expression={"$($_.WorkingSetSize / 1MB) MB"}}, `
ProcessId, ParentProcessId -First $Top `
| Format-Table -AutoSize
----
* Save the following Script off as `Get-TopMemoryProcesses.ps1`
* Then run it by `./Get-TopMemoryProcess.ps1`
* Next, run it with a parameter `./Get-TopMemoryProcess.ps1 -Top 5`
* Finally, run `Get-Help Get-TopMemoryProcess.ps1` and view the help file
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment