Import Classes in PowerShell

0

I am creating a script in powershell that will make use of classes like this:

Class Auto {

    [string]$Marca
    [string]$Color

    Auto ([string]$m,[string]$c) 
    {
        $this.Color = $c
        $this.Marca = $m
    }
}

But I want to write each class in a different file and use it in the main script as it normally does in other programming languages.

How can I get this?

    
asked by Edwin V 20.03.2016 в 17:58
source

2 answers

1

To include a Auto.ps1 file in another main.ps1 , you must know the absolute path of Auto.ps1 , do not allow relative routes.

However, you can calculate the route from the command invoked:

# Obtener el directorio base donde están los scripts a partir del que lo invoca
$base = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

# Incluir las referencias necesarias
. ($base + ".\Auto.ps1")

So, your commands can be in a directory structure like

MisScripts\
   Util\
     util.ps1
   Extra\
     extra.ps1
   actualizar.ps1
   listar.ps1

then, to include util.ps1 from list.ps1 you would write in the latter

. ($base + ".\Util\util.ps1")

A complete example could be to leave in the following structure

Ejemplo\
  Util\
    Auto.ps1
  main.ps1

where Auto.ps1 contains

Class Auto {

    [string] $Marca
    [string] $Color

    Auto ([string] $m,[string] $c)  {
        $this.Color = $c
        $this.Marca = $m
    }

    [void] Report() {
        Write-Host ("AUTO: " + $this.Marca + " (" + $this.Color + ")")
    }
}

and main.ps1 contains

# Obtener el directorio base donde están los scripts a partir del que lo invoca
$base = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

# Incluir las referencias necesarias
. ($base + ".\Util\Auto.ps1")

[Auto]::new("Audi", "Azul").Report()

then, when calling from anywhere main.ps1 you get

C:\Users\josejuan>powershell d:\datos\tmp\main.ps1
AUTO: Audi (Azul)

C:\Users\josejuan>
    
answered by 23.03.2016 / 09:28
source
1

Since PowerShell 3.0 (since 2008) there is an automatic variable called $ PSScriptRoot , which points to the directory where script is saved.

# importar 'auto.ps1' que esta ubicado en la misma carpeta que este script

. "$PSScriptRoot\auto.ps1"

# aqui auto ya esta disponible

It also works with sub folders ..

. "$PSScriptRoot\modulos\auto.ps1"

Note that it points to the folder where the Script is located, and not to the folder where the script is running, so you can build your script using relative paths.

    
answered by 23.03.2016 в 11:17