PowerShell User Features for Users

Hello! Quite often in your work you have to use independently written functions and drag pieces of code between different scripts. There is already a pretty good article on Habré about Reusing code from Mroff , but there was a need to go a little further, to document and somehow describe your functions. As it turned out, the search provided pretty dry information mainly on the general structure of the function and nothing more. Perseverance was rewarded, and I decided to share the information received. Welcome to Cat, where we will learn how to introduce information for our descendants and colleagues into our functions.

First, let's look at the standard function structure in PowerShell. It looks as follows

Function TestPath ([String]$Path)
        {
                Return(Test-Path $Path)
        }

In general, it’s nothing complicated, as in other languages ​​they gave the name TestPath, in parentheses the variables $ Path were fed, separated by commas, performed the necessary actions in the body of the function and, if necessary, returned a Return () value. But what about when you need to work with several variables? There is always more than one way out - to constantly give mnemonic codes or make a description of a variable, let's look at how this is done:

Function TestPath
        {
                PARAM (
                [PARAMETER(Mandatory=$True,Position=0,HelpMessage = "Путь до проверяемого ресурса",ParameterSetName='Path')]$Path
                )
                Return(Test-Path $Path)
        }

There is no difficulty, but additional parameters have appeared that simplify our lives:

Mandatory - Takes two values ​​True mandatory and False optional;
HelpMessage - Help on the variable;
ParameterSetName - The name of the variable to which these parameters relate;
Position - The position of the variable when calling the function;

Everything seems to be fine. Now we have a variable that has a description, but in order to find out it is necessary to execute the following code:

((Get-Command TestPath).ParameterSets.Parameters | Where-Object Name -eq Path).HelpMessage

PowerShell will answer us with one line in which it will be written: The path to the resource being checked.

It’s convenient to some extent, but if we are used to working with PowerShell, we know the Get-Help command that displays detailed information about the function with examples of its use and variables that need to be passed.

Let's complicate the task a bit and prepare a function of information about which, upon request, Get-Help will be displayed in full:

Function WriteToLog {
    <#
    .SYNOPSIS
        Вывод сообщения в консоль и в файл лога.
    .DESCRIPTION
        Данная функция выводит переданную строку в лог файл и в консоль PowerShell
    .EXAMPLE
        #WriteToLog -Str "Данное сообщение будет выведено в консоль красным цветом и в файл C:\Log\log.txt" -FileName 'C:\Log\log.txt' -Color Red
    .EXAMPLE
        #WriteToLog -Str "Данное сообщение будет выведено в консоль цветом по умолчанию (White) и в файл C:\Log\log.txt" -FileName 'C:\Log\log.txt'
    .PARAMETER Str
        Строка, которую необходимо вывести (обязательный параметр)
    .PARAMETER FileName
        Имя файла лога (обязательный параметр)
    .PARAMETER Color
        Цвет текста сообщения в консоли PowerShell (По умолчанию цвет текста белый (White))
    #>
    param (
        [PARAMETER(Mandatory=$True,Position=0)][String]$Str,
        [PARAMETER(Mandatory=$True,Position=1)][String]$FileName,
        [PARAMETER(Mandatory=$False,Position=2)][String]$Color='White'
        )
        Write-Host $Str -ForegroundColor $Color
        If ((Test-Path $FileName) -eq $True)
            {
                Add-Content -Path $FileName -Value $Str
            }
        Else
            {
                Set-Content -Path $FileName -Value $Str
            }
    }

After executing this code, the Get-Help 'WriteToLog' -ShowWindow command will display the following window.


Let's see what we wrote:

<##> - This block contains parameters for PowerShell help.
.SYNOPSIS - a block for a brief description of the function
.DESCRIPTION - a block for a complete description of the function
.EXAMPLE - a block for an example of the use of the function, there may be several
.PARAMETR Parameter name - a block for describing the variable, each block has its own block.

As you may have noticed, a text comment starts on the next line after the key section name and can be multi-line. The end of the comment is the closing tag #> or the next block.

param () is a block for describing variables in which we indicated their order and the need to pass parameters when calling a function. For the $ Color variable, we set the default value to 'White'.

Now all user-defined functions can be used centrally and you don’t have to remember which parameter is responsible for what, as well as which data type this or that variable uses.

Thank you for reading to the end.

Also popular now: