PowerShell Beginner’s Guide – Creating Functions

In this post we will be going through creating a functions in PowerShell.

PowerShell functions are reusable code created to perform specific tasks. Functions can accept inputs (parameters), process data, and produce outputs (return data).

PowerShell functions make code readability and efficiency better and allows easier automate of tasks.

Functions can be either saved in script file (.ps1), then called as part of the script or saved as modules (.psm1) and these can then be imported using the import-module command or added to a PowerShell profile so they load each time PowerShell is launched.

First we will go through creating a basic function, this can be made up of existing PowerShell commands, standard command line or we can add .Net Name spaces and classes.

Functions

To create a new function we type function and set a name. Then a script block to contain the code that will be run. When naming a functions it can be called anything but it is a good idea to keep the same Verb-Noun that is used by other PowerShell commands.

The below example will create a new command called Check-Logfiles and when its run it will use get-childitem to look in the specific logs folder

function Check-Logfiles {

Get-ChildItem C:\temp\Logs

}
Function

This can be useful if you have a repeatable tasks as you can create a new command and instead of having to add all the parameter each time to an existing command, you can just set in the function and run each time to check logs, services or any other specific checks.

Parameters

Most PowerShell commands, such as cmdlets, functions and scripts, rely on parameters to allow users to select options or provide inputs.

Parameters can be set to either required or not required by adding mandatory.

When setting parameters we need to use a type, the most common type I use is string but there are many additional like Boolean or date.

String: This can either be hardcoded text or a variable. This can then be passed to the command in the function.

Bool: Set the script to use $True, $False, 1 or 0.

Parameters can be set to either be required or not required by adding mandatory.

The below is the update Check-Logfiles function above and replaces the path with a $path variable and a confirm parameter to run the script.

 function Check-Logfiles {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)] 
        [string]$path,
        [bool]$Confrim
    )

    Get-ChildItem $path
    }
Function with parameters

Next we an add in the Boolean to put in true or false requirement to run the script.

function Check-Logfiles {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)] 
        [string]$path,

        [bool]$Confrim
    )

    if($Confrim -eq "True"){
    Get-ChildItem $path
    }

    else {
        Write-Warning "Confirm not set to true"
    }
    
    }
Function with Boolean

Parameter Validation

We an add validation to parameters to set what values will be accept by the parameter. To use validation we will add ValidateSet to the parameter.

For the below example we will only be accepting two paths in the Check-Logfiles function. If a users set a path outside other than the set paths the function will fail immediately and output the reason to the PowerShell console.

function Check-Logfiles {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)] 
        [ValidateSet('C:\temp\Logs','C:\temp\Logs2')]
        [string]$path
    )

    Get-ChildItem $path
    
    }

The above are just a few examples of the different ways to use a function. Functions are great way to create reusable code / commands and give structure to your scripts. Functions should be kept a small as possible and set to do only a single task this will allow easier troubleshooting.

Multiple functions can be combined in a single script to complete more complex tasks.

PowerShell Beginner’s Guide – PowerShell Remoting

In this we will be going through PowerShell remoting (PSRemoting).

PowerShell remoting is a feature that enables administrators to manage multiple computers remotely using PowerShell commands. It allows us to execute commands, run scripts, and manage configurations on one or more remote computers from a single console.

With PSremoting, we can run administrative tasks, automate processes, and manage Windows and Linux without needing to access each machine through RDP or direct console.

PowerShell Remoting User Rights

The two local groups allows users can connect to a machines remotely using PSRemoting by default:

  • Administrators
  • Remote Management Users

If users don’t require admin rights on the machine and but they will need to remote on, they should just be added to remote management users. It always best to setup least privileges for security.

Enabling PowerShell Remoting

First we need to enable PSRemoting, if it is not enabled or the WinRM ports are blocked between the two machines. We will receive and error like the below.

PS Remoting Error

To enable PSRemoting we need to run

Enable-PSRemoting
Enable PowerShell Remoting

Once enabled we can now connect using

Enter-PSSession ComputerName
PowerShell Remote Connection

Now that we are connect we can run commands as if we had the PowerShell console open directly on the remote computer.

Running Remote Command

To exit and return back to local PowerShell console, we just need to run

Exit-PSSession
Exiting PowerShell Session

Invoke-Command

Using Enter-PSSession is good for running commands against one machine but if we want to run against multiple machines we can use Invoke-command.

When running we specify the command that will be run in the sriptblock inbetween the two curly brackets {}.

Invoke-Command -ComputerName computer1,computer2 -ScriptBlock { Command}

In the below example I am running against three machines and getting the computersystem WIM class.

PowerShell Remoting Multiple Machines

PowerShell Sessions

Another method to run multiple commands against machines is to create a PowerShell session and then re-using this initial connection.

In the below example I am connect to the three machines, checking the printer spooler service and stopping the service in the third command.

PowerShell Sessions

This has been a quick few examples of setting up and using PSRemoting. Using PSRemoting makes administration a lot easier on remote machines. .

Some security teams don’t want remoting enabled (it is enabled by default on Windows Servers OS since 2012) as they see its as a security risk, while there are risks the benefits out way the risks and there are many ways to harden and reduce security risks associated with PowerShell rather than disabling PSRemoting.