Powershell e sebetsang ka litlelase ha se oxymoron, kea e tiisa

Hey Habr! Ke fana ka tlhokomelo ea hau phetolelo ea sehlooho "PowerShell e sebetsang e nang le Lihlopha.
Kea ts'episa hore ha se oxymoron"
ka Christopher Kuech.

Li-paradigms tse shebaneng le morero le tse sebetsang li ka 'na tsa bonahala li sa lumellane, empa ka bobeli li tšehetsoa ka ho lekana ho Powershell. Hoo e ka bang lipuo tsohle tsa lenaneo, tse sebetsang kapa che, li na le lisebelisoa tsa tlamahano ea boleng bo atolositsoeng; Litlelase, joalo ka sebopeho le lirekoto, ke mokhoa o le mong feela. Haeba re fokotsa tšebeliso ea rona ea Lihlopha ho tlama mabitso le litekanyetso, 'me re qoba likhopolo tse boima tsa mananeo a kang lefa, polymorphism, kapa phetoho, re ka sebelisa melemo ea bona ntle le ho thatafatsa khoutu ea rona. Ho feta moo, ka ho kenyelletsa mekhoa e sa fetoheng ea phetoho, re ka ntlafatsa khoutu ea rona ea ts'ebetso ka Lihlopha.

Boselamose ba li-castes

Castes ke e 'ngoe ea likarolo tse matla ka ho fetisisa ho Powershell. Ha o fana ka boleng, o itšetlehile ka bokhoni bo hlakileng ba ho qala le ho netefatsa tikoloho e eketsang kopo ea hau. Mohlala, ho kenya khoele feela ho [xml] ho tla e tsamaisa ka har'a khoutu ea sekhetho ebe ho hlahisa sefate se felletseng sa xml. Re ka sebelisa Lihlopha khoutu ea rona ka sepheo se tšoanang.

Etsa li-hashtable

Haeba ha u na sehahi, u ka tsoela pele ntle le sehahi ka ho akhela hashtable ho mofuta oa sehlopha sa hau. Se ke oa lebala ho sebelisa litšoaneleho tsa netefatso ho sebelisa monyetla ona ka botlalo. Ka nako e ts'oanang, re ka sebelisa thepa e thaepileng ea sehlopha ho sebelisa mokhoa o tebileng oa ho qala le ho netefatsa.

class Cluster {
    [ValidatePattern("^[A-z]+$")]
    [string] $Service
    [ValidateSet("TEST", "STAGE", "CANARY", "PROD")]
    [string] $FlightingRing
    [ValidateSet("EastUS", "WestUS", "NorthEurope")]
    [string] $Region
    [ValidateRange(0, 255)]
    [int] $Index
}

[Cluster]@{
    Service       = "MyService"
    FlightingRing = "PROD"
    Region        = "EastUS"
    Index         = 2
}

Ho feta moo, ho lahla ho thusa ho fumana tlhahiso e hloekileng. Bapisa tlhahiso ea Cluster hashtable array e fetiselitsoeng ho Format-Table le seo u se fumanang haeba u qala ho kenya li-hashtable tsena sehlopheng. Thepa ea sehlopha e lula e thathamisitsoe ka tatellano eo e hlalosoang ka eona moo. Se ke oa lebala ho eketsa senotlolo se patiloeng pele ho thepa eo u sa batleng ho bonahala liphethong.

Powershell e sebetsang ka litlelase ha se oxymoron, kea e tiisa

Ho lahla meelelo

Haeba u na le sehahi se nang le khang e le 'ngoe, ho fana ka boleng ho mofuta oa sehlopha sa hau ho tla fetisetsa boleng ho moetsi oa hau, moo o ka qalang mohlala oa sehlopha sa hau.

class Cluster {
    [ValidatePattern("^[A-z]+$")]
    [string] $Service
    [ValidateSet("TEST", "STAGE", "CANARY", "PROD")]
    [string] $FlightingRing
    [ValidateSet("EastUS", "WestUS", "NorthEurope")]
    [string] $Region
    [ValidateRange(0, 255)]
    [int] $Index

    Cluster([string] $id) {
        $this.Service, $this.FlightingRing, $this.Region, $this.Index = $id -split "-"
    }
}

[Cluster]"MyService-PROD-EastUS-2"

Lahlela moleng

U ka boela ua fetisa mokhoa oa sehlopha sa [string] ToString() ho hlalosa mohopolo o ka morao oa kemiso ea khoele ea ntho, joalo ka ho sebelisa tlhale ea likhoele.

class Cluster {
    [ValidatePattern("^[A-z]+$")]
    [string] $Service
    [ValidateSet("TEST", "STAGE", "CANARY", "PROD")]
    [string] $FlightingRing
    [ValidateSet("EastUS", "WestUS", "NorthEurope")]
    [string] $Region
    [ValidateRange(0, 255)]
    [int] $Index

    [string] ToString() {
        return $this.Service, $this.FlightingRing, $this.Region, $this.Index -join "-"
    }
}

$cluster = [Cluster]@{
    Service       = "MyService"
    FlightingRing = "PROD"
    Region        = "EastUS"
    Index         = 2
}

Write-Host "We just created a model for '$cluster'"

Etsa liketsahalo tse latellanang

Cast e lumella deserialization e sireletsehileng. Mehlala e ka tlase e tla hloleha haeba data e sa kopane le litlhaloso tsa rona ho Cluster

# Валидация сериализованных данных

[Cluster]$cluster = Get-Content "./my-cluster.json" | ConvertFrom-Json
[Cluster[]]$clusters = Import-Csv "./my-clusters.csv"

E kenya khoutu ea hau e sebetsang

Mananeo a sebetsang a qala ka ho hlalosa libopeho tsa data, ebe o kenya tšebetsong lenaneo e le tatellano ea liphetoho holim'a meaho ea data e sa fetoheng. Leha ho na le maikutlo a hanyetsanang, litlelase li hlile li u thusa ho ngola khoutu e sebetsang ka lebaka la mekhoa ea ho fetolela mofuta.

Na Powershell eo ke e ngolang e ea sebetsa?

Batho ba bangata ba tsoang ho C # kapa semelo se tšoanang ba ngola Powershell, e ts'oanang le C #. Ka ho etsa sena, u suthela hole le ho sebelisa mehopolo e sebetsang ea mananeo 'me mohlomong u ka rua molemo ka ho qoela ka har'a lenaneo le shebaneng le ntho ho Powershell kapa ho ithuta haholoanyane ka mananeo a sebetsang.

Haeba u itšetlehile haholo ka ho fetola data e sa fetoheng u sebelisa lipeipi (|), Where-Object, ForEach-Object, Select-Object, Group-Object, Sort-Object, joalo-joalo - u na le mokhoa o sebetsang haholoanyane 'me u tla rua molemo ka ho sebelisa Powershell lihlopha ka mokhoa o sebetsang.

Tšebeliso e sebetsang ea lihlopha

Castes, leha ba sebelisa poleloana e 'ngoe, ke 'mapa feela lipakeng tsa libaka tse peli. Ka lipeipi, o ka 'mapa letoto la boleng o sebelisa ForEach-Object.

Mohlala o ka tlase, moetsi oa Node o etsoa nako le nako ha Datum e lahleloa, 'me sena se re fa monyetla oa hore re se ke ra ngola palo e nepahetseng ea khoutu. Ka lebaka leo, lipeipi tsa rona li shebane le ho botsa le ho kopanya lintlha tse phatlalalitsoeng, ha litlelase tsa rona li hlokomela ho arola le ho netefatsa data.

# Пример комбинирования классов с конвейерами для separation of concerns в конвейерах

class Node {
    [ValidateLength(3, 7)]
    [string] $Name
    [ValidateSet("INT", "PPE", "PROD")]
    [string] $FlightingRing
    [ValidateSet("EastUS", "WestUS", "NorthEurope", "WestEurope")]
    [string] $Region
    Node([string] $Name) {
        $Name -match "([a-z]+)(INT|PPE|PROD)([a-z]+)"
        $_, $this.Service, $this.FlightingRing, $this.Region = $Matches
        $this.Name = $Name
    }
}

class Datum {
    [string] $Name
    [int] $Value
    [Node] $Computer
    [int] Severity() {
        $this.Name -match "[0-9]+$"
        return $Matches[0]
    }
}

Write-Host "Urgent Security Audit Issues:"
Import-Csv "./audit-results.csv" `
    | ForEach-Object {[Datum]$_} `
    | Where-Object Value -gt 0 `
    | Group-Object {$_.Severity()} `
    | Where-Object Name -lt 2 `
    | ForEach-Object Group `
    | ForEach-Object Computer `
    | Where-Object FlightingRing -eq "PROD" `
    | Sort-Object Name, Region -Unique

Sehlopha sa ho paka bakeng sa ho sebelisoa hape

Ha ho letho le monate joalo ka ha le bonahala

Ka bomalimabe, lihlopha ha li khone ho romelloa ka li-module ka tsela e ts'oanang le mesebetsi kapa mefuta-futa; empa ho na le maqheka a mang. Ha re re litlelase tsa hau li hlalositsoe faeleng ./my-classes.ps1

  • U ka etsa dotsource file ka litlelase:. ./my-classes.ps1. Sena se tla phethahatsa my-classes.ps1 sebakeng sa hau sa hajoale mme se hlalose litlelase tsohle ho tsoa faeleng e teng.

  • O ka etsa mojule wa Powershell o romelang di-API tsa hao kaofela (cmdlets) mme wa seta ScriptsToProcess = "./my-classes.ps1" ho ponahatso ya mojule wa hao, ka sephetho se tshwanang: ./my-classes.ps1 e tla phetha ka tikoloho ya hao .

Hore na u khetha khetho efe, hopola hore sistimi ea Powershell e ke ke ea rarolla mefuta ea lebitso le le leng le laetsoeng libakeng tse fapaneng.
Leha o ka jarisa litlelase tse peli tse ts'oanang tse nang le thepa e tšoanang ho tsoa libakeng tse fapaneng, o ipeha kotsing ea ho kena mathateng.

Tsela e eang pele

Mokhoa o motle oa ho qoba mathata a ho rarolla mofuta ke ho se pepesetse litlelase tsa hau ho basebelisi. Sebakeng sa ho lebella hore mosebelisi a tlise mofuta o hlalosoang ke sehlopha, romella ntho e itseng ho tsoa mojuleng oa hau o felisang tlhoko ea ho fihlella sehlopha ka kotloloho. Bakeng sa Cluster, re ka romella mosebetsi oa New-Cluster o tla tšehetsa li-parameter tse sebetsang hantle le ho khutlisetsa Cluster.

class Cluster {
    [ValidatePattern("^[A-z]+$")]
    [string] $Service
    [ValidateSet("TEST", "STAGE", "CANARY", "PROD")]
    [string] $FlightingRing
    [ValidateSet("EastUS", "WestUS", "NorthEurope")]
    [string] $Region
    [ValidateRange(0, 255)]
    [int] $Index
}

function New-Cluster {
    [OutputType([Cluster])]
    Param(
        [Parameter(Mandatory, ParameterSetName = "Id", Position = 0)]
        [ValidateNotNullOrEmpty()]
        [string] $Id,
        [Parameter(Mandatory, ParameterSetName = "Components")]
        [string] $Service,
        [Parameter(Mandatory, ParameterSetName = "Components")]
        [string] $FlightingRing,
        [Parameter(Mandatory, ParameterSetName = "Components")]
        [string] $Region,
        [Parameter(Mandatory, ParameterSetName = "Components")]
        [int] $Index
    )

    if ($Id) {
        $Service, $FlightingRing, $Region, $Index = $Id -split "-"
    }

    [Cluster]@{
        Service       = $Service
        FlightingRing = $FlightingRing
        Region        = $Region
        Index         = $Index
    }
}

Export-ModuleMember New-Cluster

Ke eng hape eo u lokelang ho e bala

Mabapi le Lihlopha
Tšireletso PowerShell
Lenaneo le sebetsang ho PowerShell

Source: www.habr.com

Eketsa ka tlhaloso