Z
Z
ZIK13372019-04-07 14:17:12
PowerShell
ZIK1337, 2019-04-07 14:17:12

How to create a cmdlet in PowerShell?

Hello, I have a task:

spoiler
PuXCGnM.jpg

I did like this:
First
9Qq4Lcf.jpg
Second
vG9DxjP.jpg

But it's not a cmdlet, is it? It turns out that I need to create my own, give it a name so that I can call it with a regular command? Then how to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Ratkin, 2019-04-07
@ZIK1337

Alternatively, you can do this.
Create file test.psm1 :

Function Get-NProcesses
{
    param (
        [switch]$Multiple,
        [switch]$LastProcess
    )

    $listProcesses = Get-Process| Select-Object -Unique | Select-Object -Property ProcessName, StartTime  | Where-Object { $_.StartTime -ne $null }

    if($Multiple)
    {
        foreach($process in $listProcesses.ProcessName)
        {
            if((Get-Process $process).Count -gt 1)
            {
                $process
            }
        }
    }

    if($LastProcess)
    {
        $listProcesses | Sort-Object -Property StartTime | Select-Object -Last 1
    }
}

Open PS console:
Import-Module /path/to/test1.psm1
Get-NProcesses -Multiple
Get-NProcesses -LastProcess

S
Sergey, 2019-04-07
@LiS-31

A cmdlet is a PowerShell file with a set of functions. You need to format these pipelines as PS functions and save them to a file with the psm extension, in one of the folders:
C:\Users\%UserName%\Documents\WindowsPowerShell\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\Windows \System32\WindowsPowerShell\v1.0\Modules

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question