El TecnoBaúl de Kiquenet

Kiquenet boring stories

Arrays in Powershell

Posted by kiquenet en 9 enero 2015

Collections, Hashtables, Arrays, strings
https://www.simple-talk.com/sysadmin/powershell/powershell-one-liners–collections,-hashtables,-arrays-and-strings/

Define Array

$configs = @(

     "C:\tfs\Arquitectura\ConnectionStrings.config"; 
     "C:\tfs\VSIntegration\Test\App.config"; 
)

Foreach Array

for( $i = 0; $i -lt $configs.length; $i++) {
  $config = $configs[$i]
 
  Write-Host setting $config
 
}

Alternative

function ConvertTo-MyTypeOfItem
{
    PARAM (
        [ValidatePattern("([^_]+_){3}[^_]+")]
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$StringToParse
    )

    PROCESS {
        $custId, $invId, $prodId, [int]$value = $StringToParse -split "_"
        $myObject = New-Object PSObject -Property @{
            CustomerID = $custId;
            InvoiceID = $invId;
            ProductID = $prodId;
            Value = $value
        }
        Write-Output $myObject
    }
}

# In the test scenario I have replaced getting the list of files
# with an array of names. Just uncomment the first and second lines
# following this comment and remove the other $baseNames setter, to
# get the $baseNames from the file listing

#$files = Get-ChildItem test *.txt
#$baseNames = $files.BaseName
$baseNames = @(
    "cust1_inv1_prod1_1";
    "cust2_inv2_prod2_2";
    "cust3_inv3_prod3_3";
    "cust4_inv4_prod4_4";
)

$myObjectArray = $baseNames | ConvertTo-MyTypeOfItem

$myObjectArray

Sources:
http://stackoverflow.com/questions/21884828/powershell-array-to-store-strings
http://stackoverflow.com/questions/25191803/powershell-cli-foreach-loop-with-multiple-arrays
http://www.powershellpro.com/powershell-tutorial-introduction/variables-arrays-hashes/

Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

 
A %d blogueros les gusta esto: