Mostrando postagens com marcador powershell. Mostrar todas as postagens
Mostrando postagens com marcador powershell. Mostrar todas as postagens

terça-feira, 26 de dezembro de 2023

Decorator Powershell Design Patterns

 Powershell Design Patterns Decorator

```powershell

# Classe base 'Beverage'

class Beverage {

    [string]$description = "Unknown Beverage"

    [string] getDescription() {

        return $this.description

    }

    [decimal] cost() {

        return 0

    }

}

# Subclasses concretas de 'Beverage'

class HouseBlend : Beverage {

    HouseBlend() {

        $this.description = "House Blend Coffee"

    }

    [decimal] cost() {

        return .89

    }

}

class DarkRoast : Beverage {

    DarkRoast() {

        $this.description = "Dark Roast Coffee"

    }

    [decimal] cost() {

        return .99

    }

}

class Espresso : Beverage {

    Espresso() {

        $this.description = "Espresso"

    }

    [decimal] cost() {

        return 1.99

    }

}

class Decaf : Beverage {

    Decaf() {

        $this.description = "Decaf Coffee"

    }

    [decimal] cost() {

        return 1.05

    }

}

class Latte : Beverage {

    Latte() {

        $this.description = "Latte Coffee"

    }

    [decimal] cost() {

        return 1.25

    }

}

# Classe decoradora 'CondimentDecorator'

class CondimentDecorator : Beverage {

    [Beverage]$beverage

    CondimentDecorator([Beverage]$beverage) {

        $this.beverage = $beverage

    }

    [string] getDescription() {

        return $this.beverage.getDescription()

    }

}

# Subclasses concretas de 'CondimentDecorator'

class Milk : CondimentDecorator {

    Milk([Beverage]$beverage) : base($beverage) {

        $this.description = "Milk"

    }

    [string] getDescription() {

        return $this.beverage.getDescription() + ", Milk"

    }

    [decimal] cost() {

        return $this.beverage.cost() + .10

    }

}

class Mocha : CondimentDecorator {

    Mocha([Beverage]$beverage) : base($beverage) {

        $this.description = "Mocha"

    }

    [string] getDescription() {

        return $this.beverage.getDescription() + ", Mocha"

    }

    [decimal] cost() {

        return $this.beverage.cost() + .20

    }

}

class Soy : CondimentDecorator {

    Soy([Beverage]$beverage) : base($beverage) {

        $this.description = "Soy"

    }

    [string] getDescription() {

        return $this.beverage.getDescription() + ", Soy"

    }

    [decimal] cost() {

        return $this.beverage.cost() + .15

    }

}

class Whip : CondimentDecorator {

    Whip([Beverage]$beverage) : base($beverage) {

        $this.description = "Whip"

    }

    [string] getDescription() {

        return $this.beverage.getDescription() + ", Whip"

    }

    [decimal] cost() {

        return $this.beverage.cost() + .10

    }

}

class Caramel : CondimentDecorator {

    Caramel([Beverage]$beverage) : base($beverage) {

        $this.description = "Caramel"

    }

    [string] getDescription() {

        return $this.beverage.getDescription() + ", Caramel"

    }

    [decimal] cost() {

        return $this.beverage.cost() + .15

    }

}

# Definições de classes como antes...

# Hashtable para mapear tipos de bebidas a suas respectivas classes

$beverageTypes = @{

    "HouseBlend" = { [HouseBlend]::new() }

    "DarkRoast" = { [DarkRoast]::new() }

    "Espresso" = { [Espresso]::new() }

    "Decaf" = { [Decaf]::new() }

}

# Hashtable para mapear tipos de condimentos a suas respectivas classes

$condimentTypes = @{

    "Milk" = { param($beverage) [Milk]::new($beverage) }

    "Mocha" = { param($beverage) [Mocha]::new($beverage) }

    "Soy" = { param($beverage) [Soy]::new($beverage) }

    "Whip" = { param($beverage) [Whip]::new($beverage) }

}

# Função para criar a bebida base usando a hashtable

function CreateBaseBeverage([string]$beverageType) {

    if ($beverageTypes.ContainsKey($beverageType)) {

        return & $beverageTypes[$beverageType]

    } else {

        throw "Invalid beverage type: $beverageType"

    }

}

# Função para adicionar condimentos usando a hashtable

function AddCondiment([Beverage]$beverage, [string]$condimentType) {

    if ($condimentTypes.ContainsKey($condimentType)) {

        return & $condimentTypes[$condimentType] $beverage

    } else {

        throw "Invalid condiment type: $condimentType"

    }

}


# Criacao de novos tipos

$beverageTypes["Latte"] = { [Latte]::new() }

$condimentTypes["Caramel"] = { param($beverage) [Caramel]::new($beverage) }


# Solicitar entrada do usuário para a bebida base

$beverageChoice = Read-Host "Please enter the type of coffee (HouseBlend, DarkRoast, Espresso, Decaf)"

$beverage = CreateBaseBeverage $beverageChoice

# Laço para adicionar condimentos

do {

    $condimentChoice = Read-Host "Add a condiment (Milk, Mocha, Soy, Whip) or 'Done' to finish"

    if ($condimentChoice -ne 'Done') {

        $beverage = AddCondiment $beverage $condimentChoice

    }

} while ($condimentChoice -ne 'Done')

# Exibir descrição e custo da bebida finalizada

Write-Host "Your final beverage: " $beverage.getDescription()

Write-Host "Total cost: $" $beverage.cost()


```

quarta-feira, 9 de março de 2022

 Powershell Design Patterns Prototype

class Person {
[int] $Age
[DateTime] $BirthDate
[string] $Name
[IdInfo] $IdInfo

[Person] ShallowCopy() {
return [Person] $this.MemberwiseClone()
}

[Person] DeepCopy() {
[Person] $clone = [Person] $this.MemberwiseClone()
$clone.IdInfo = [IdInfo]::new($this.IdInfo.IdNumber)
$clone.Name = $($this.Name).ToString()
return $clone
}
}

class IdInfo {
[int] $IdNumber
IdInfo([int] $idNumber) {
$this.IdNumber = $idNumber
}
}

class Program {
Main() {
[Person] $p1 = [Person]::new()
$p1.Age = 42
$p1.BirthDate = "1977-01-01"
$p1.Name = "Jack Daniels"
$p1.IdInfo = [IdInfo]::new(777)

[Person] $p2 = $p1.ShallowCopy()
[Person] $p3 = $p1.DeepCopy()
Write-Host "Original values of p1, p2, p3:"
Write-Host " p1 instance values: "
$this.DisplayValues($p1)
Write-Host " p2 instance values:"
$this.DisplayValues($p2)
Write-Host " p3 instance values:"
$this.DisplayValues($p3)

$p1.Age = 32
$p1.BirthDate = "1983-01-01"
$p1.Name = "Frank"
$p1.IdInfo.IdNumber = 7878
Write-Host "\nValues of p1, p2 and p3 after changes to p1:"
Write-Host " p1 instance values: "
$this.DisplayValues($p1)
Write-Host " p2 instance values (reference values have changed):"
$this.DisplayValues($p2)
Write-Host " p3 instance values (everything was kept the same):"
$this.DisplayValues($p3)
}

[void] DisplayValues([Person] $p) {
Write-Host ("Name: {0:s}, Age: {1:d}, BirthDate: {2:dd/MM/yyyy}" -f $p.Name, $p.Age, $p.BirthDate)
Write-Host " ID"
}
}
[Program]::new().Main()

 Powershell Design Patterns Abstract Factory


class AbstractFactory {
CreateProductA() {}
CreateProductB() {}
}
class ConcreteFactory1 : AbstractFactory {
[AbstractProductA] CreateProductA() {
return [ConcreteProductA1]::new()
}
[AbstractProductB] CreateProductB() {
return [ConcreteProductB1]::new()
}
}
class ConcreteFactory2 : AbstractFactory {
[AbstractProductA] CreateProductA() {
return [ConcreteProductA2]::new()
}
[AbstractProductB] CreateProductB() {
return [ConcreteProductB2]::new()
}
}
class AbstractProductA {
UsefulFunctionA() {}
}
class ConcreteProductA1 : AbstractProductA {
[string] UsefulFunctionA() {
return "The result of the product A1."
}
}
class ConcreteProductA2 : AbstractProductA {
[string] UsefulFunctionA() {
return "The result of the product A2."
}
}
class AbstractProductB {
UsefulFunctionB() {}
AnotherUsefulFunctionB([AbstractProductA] $collaborator) {}
}
class ConcreteProductB1 : AbstractProductB {
[string] UsefulFunctionB() {
return "The result of the product B1."
}
[string] AnotherUsefulFunctionB([AbstractProductA] $collaborator) {
$result = $collaborator.UsefulFunctionA()
return "The result of the B1 collaborating with the ({0})" -f $result
}
}
class ConcreteProductB2 : AbstractProductB {
[string] UsefulFunctionB() {
return "The result of the product B2."
}
[string] AnotherUsefulFunctionB([AbstractProductA] $collaborator) {
$result = $collaborator.UsefulFunctionA()
return "The result of the B2 collaborating with the ({0})" -f $result
}
}
class Client {

[void] ClientMethod([AbstractFactory] $factory) {
$productA = $factory.CreateProductA()
$productB = $factory.CreateProductB()
Write-Host $productB.UsefulFunctionB()
Write-Host $productB.AnotherUsefulFunctionB($productA)
}
[void] Main() {
Write-Host "Client: Testing client code with the first factory type..."
$this.ClientMethod([ConcreteFactory1]::new())
Write-Host
Write-Host "Client: Testing the same client code with the second factory type..."
$this.ClientMethod([ConcreteFactory2]::new())
}
}
class Program {
Main() {
[Client]::new().Main()
}
}
[Program]::new().Main()

terça-feira, 8 de março de 2022

 Powershell Design Patterns Command


class Command {
# Declara uma interface para comandos abstratos como Execute().
Execute() {}
}

class Receiver {
# Sabe como executar um comando particular.
SwitchOn() {
Write-Host "Switch on from: " $this.GetType().Name
}
}

class OnCommand: Command {
[Receiver] $Receiver

OnCommand([Receiver] $Receiver) {
$this.Receiver = $Receiver
}
Execute() {
$this.Receiver.SwitchOn()
}
}

class Invoker {
[Command] $Command

Invoker([Command] $Command) {
$this.Command = $Command
}

Execute() {
$this.Command.Execute()
}
}

class TV: Receiver {
[String] toString() {
return $this.GetType().Name
}
}

class DVDPlayer: Receiver {
[String] toString() {
return $this.GetType().Name
}
}

class Main {
Main() {
# Receiver é quem recebe o sabe como realizar o comando.
[Receiver] $Receiver = [TV]::new()
# O Comando do tipo OnCommand recebe o receiver acima.
[Command] $OnCommand = [OnCommand]::new($Receiver)
# O invoker recebe o OnCommand acima, que tem o receiver
[Invoker] $Invoker = [Invoker]::new($OnCommand)
# O comando é chamado pelo Invoker.
$Invoker.Execute()
# On command for DVDPlayer with same invoker
[Receiver] $Receiver = [DVDPlayer]::new()
[Command] $OnCommand = [OnCommand]::new($Receiver)
[Invoker] $Invoker = [Invoker]::new($OnCommand)
$Invoker.Execute()
}
}

[Main]::new()

 Powershell Design Patterns Builder

class Car {}
class Manual {}

class Builder {
Reset() {}
SetSeats([int] $NumeroDeAssentos) {}
SetEngine([String] $TipoDeMotor) {}
SetTripComputer([String] $TipoComputadorBordo) {}
SetGPS([String] $TipoGPS) {}
}

class CarBuilder: Builder {
[Car] $Car
CarBuilder() {
$this.Reset()
}
Reset() {
$this.Car = [Car]::new()
}
SetSeats([int] $NumeroDeAssentos) {
Write-Host "O numero de assentos deste carro é: " $NumeroDeAssentos
}
SetEngine([String] $TipoDeMotor) {
Write-Host "O tipo de motor deste carro é: " $TipoDeMotor
}
SetTripComputer([String] $TipoComputadorBordo) {
Write-Host "O tipo de Computador de Bordo deste carro é: " $TipoComputadorBordo
}
SetGPS([String] $TipoGPS) {
Write-Host "O tipo de GPS deste carro é: " $TipoGPS
}

[Car] GetProduct() {
$Product = $this.Car
$this.Reset()
return $Product
}

}
class CarManualBuilder: Builder {
[Manual] $Manual
CarManualBuilder() {
$this.Reset()
}
Reset() {
$this.Manual = [Manual]::new()
}
SetSeats([int] $NumeroDeAssentos) {
Write-Host "O numero de assentos deste carro é: " $NumeroDeAssentos
}
SetEngine([String] $TipoDeMotor) {
Write-Host "O tipo de motor deste carro é: "$TipoDeMotor
}
SetTripComputer([String] $TipoComputadorBordo) {
Write-Host "O tipo de Computador de Bordo deste carro é: " $TipoComputadorBordo
}
SetGPS([String] $TipoGPS) {
Write-Host "O tipo de GPS deste carro é: " $TipoGPS
}

[Manual] GetProduct() {
$Product = $this.Manual
$this.Reset()
return $Product
}

}

class Director {

[Builder] $Builder

SetBuilder([Builder] $Builder) {
$this.Builder = $Builder
}
ConstructSportsCar([Builder] $Builder) {
$this.Builder = $Builder
$this.Builder.Reset()
$this.Builder.SetSeats(2)
$this.Builder.SetEngine("Super Motor")
$this.Builder.SetTripComputer("Super Computador")
$this.Builder.SetGPS("Super GPS")
}
ConstructSUV([Builder] $Builder) {
$this.Builder = $Builder
$this.Builder.Reset()
$this.Builder.SetSeats(6)
$this.Builder.SetEngine("Motor popular.")
$this.Builder.SetTripComputer("Computador popular.")
$this.Builder.SetGPS("GPS popular.")
}
}

class Application {
MakeCar() {
$Director = [Director]::new()
[Builder] $Builder = [CarBuilder]::new()
$Director.ConstructSportsCar($Builder)
[Car] $Car = $Builder.GetProduct()


[Builder] $Builder = [CarBuilder]::new()
$Director.ConstructSUV($Builder)
[Car] $Car = $Builder.GetProduct()

[Builder] $Builder = [CarManualBuilder]::new()
$Director.ConstructSportsCar($Builder)
# O produto final é frequentemente retornado de um
# objeto Builder uma vez que o diretor não está
# ciente e não é dependente de Builders e produtos
# concretos.
[Manual] $Manual = $Builder.GetProduct()
}

}

[Application] $Application = [Application]::new()
$Application.MakeCar()

 Powershell Composite Design Pattern Logger

class ILogger {
Log([String] $Message) {}
}

class CompositeLogger: ILogger {

# Declarando um array de ILoggers
[ILogger[]] $_loggers

CompositeLogger([ILogger[]] $_loggers) {
$this._loggers = $_loggers
}

Log([String] $Message) {
foreach ($obj_logger in $this._loggers) {
$obj_logger.Log($Message)
}
}
}

class ConsoleLogger: ILogger {
Log([String] $Message) {
Write-Host "Escrevendo no console."
Write-Host "Esta é a mensagem: $Message."
}
}

class FileLogger: ILogger {
Log([String] $Message) {
Write-Host "Escrevendo em arquivo."
Write-Host "Esta é a mensagem: $Message."
}
}

$MeuArrayDeLogs = @([ConsoleLogger]::new(), [FileLogger]::new())
[CompositeLogger] $CompositeLogger = [CompositeLogger]::new($MeuArrayDeLogs)
$CompositeLogger.Log("Esta eh a mensagem.")


 Powershell Observer Pattern


# classe Abstrata Revista
class Revista {
Assinar([Assinante] $Assinante) {}
CancelarAssinatura([Assinante] $Assinante) {}
NotificarAssinantes() {}
AjustaMensalidade([int] $ValorDaAssinatura) {}
}

# classe concreta de Revista
class RevistaDeBairro: Revista {
[System.Collections.Generic.List[object]]$ListaDeAssinantes
[int] $ValorDaAssinatura = 100

RevistaDeBairro() {
$this.ListaDeAssinantes = @()
}

Assinar([Assinante] $Assinante) {
$this.ListaDeAssinantes.Add($Assinante)
}
CancelarAssinatura([Assinante] $Assinante) {
$this.ListaDeAssinantes.Remove($Assinante)
}

NotificarAssinantes() {
foreach ($Assinante in $this.ListaDeAssinantes) {
$Assinante.Atualizar($this.ValorDaAssinatura)
}
}

AjustaMensalidade([int] $ValorDaAssinatura) {
$this.ValorDaAssinatura = $ValorDaAssinatura
$this.NotificarAssinantes()
}
}

class Assinante {
Atualizar([int] $ValorDaAssinatura) {
Write-Host "Estou atualizando o valor da assinatura..."
Write-Host "Este eh meu novo valor: " + $ValorDaAssinatura
}
}

# concreto
class AssinanteAnual: Assinante {
[Revista] $RevistaDeBairro

AssinanteAnual([Revista] $RevistaDeBairro) {
$this.RevistaDeBairro = $RevistaDeBairro
$this.RevistaDeBairro.Assinar($this)
}
}


[Revista] $RevistaOCentro = [RevistaDeBairro]::new()

[Assinante] $ZeDasCoves = [AssinanteAnual]::new($RevistaOCentro)
[Assinante] $BarbeiroNeves = [AssinanteAnual]::new($RevistaOCentro)


$RevistaOCentro.AjustaMensalidade(300)

sexta-feira, 4 de março de 2022

 Here weŕe going to start a series of Powershell Desing Patterns. The first one is "Chain of Resposability" pattern.

class DocumentHandler {

    [DocumentHandler] $next


    DocumentHandler([DocumentHandler] $next) {

        $this.next = $next

    }


    [void] openDocument([String] $FileExtension) {

        if ($null -ne $FileExtension) {

            $this.next.openDocument($fileExtension);

        }

    }

}


class SlideshowHandler:  DocumentHandler {

    SlideshowHandler ([DocumentHandler] $handler) : base ($handler) {}

    

    [void] openDocument([String] $FileExtension) {

        if ("ppt" -eq $FileExtension) {

            Write-Host "Opening Slideshow document..."

        }

        else {

            ([DocumentHandler]$this).openDocument($FileExtension)

        }

    }


}


class SpreadsheetHandler:  DocumentHandler {

    SpreadsheetHandler ([DocumentHandler] $handler) : base ($handler) {}

    

    [void] openDocument([String] $FileExtension) {

        if ("xlsx" -eq $FileExtension) {

            Write-Host "Opening Spreadsheet document..."

        }

        else {

            ([DocumentHandler]$this).openDocument($FileExtension)

        }

    }


}


class TextDocumentHandler:  DocumentHandler {

    TextDocumentHandler ([DocumentHandler] $handler) : base ($handler) {}

    

    [void] openDocument([String] $FileExtension) {

        if ("txt" -eq $FileExtension) {

            Write-Host "Opening Text document..."

        }

        else {

            ([DocumentHandler]$this).openDocument($FileExtension)

        }

    }


}


class Client {

    static [void] Main() {

        [DocumentHandler] $Chain = [SlideshowHandler]::new([SpreadsheetHandler]::new([TextDocumentHandler]::new($null)))

        $Chain.openDocument("txt")

    }

}

[Client]::Main()

sábado, 26 de fevereiro de 2022

 Como instalar Powershell no Linux Ubuntu (from Microsoft):


  • PowerShell 7.2.1 (pacote universal) para qualquer versão de suporte do Ubuntu
    • https://github.com/PowerShell/PowerShell/releases/download/v7.2.1/powershell-lts_7.2.1-1.deb_amd64.deb
    • # Install the downloaded package sudo dpkg -i powershell-lts_7.2.1-1.deb_amd64.deb
    • # Resolve missing dependencies and finish the install (if necessary) sudo apt-get install -f

# Start PowerShell pwsh



quarta-feira, 20 de fevereiro de 2019

How to use Powershell script inside SCCM program.

Just use this syntax:

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -File \\local\folder1\folder2\folder3\scripts\Start-PowershellScript.ps1

First create a program with program wizard without this ugly command line, just select script name normally. After the program has been created, in properties panel put the command line.


Decorator Powershell Design Patterns

 Powershell Design Patterns Decorator ```powershell # Classe base 'Beverage' class Beverage {     [string]$description = "Unkno...