30 May 2012

Verify function result

Usually a function returns an unpredictable number of results (an array object when is more than one);

We can use the count() method to count the returned number of results when we have more than one result returned, but if the function returns only one or no result at all the count() method cannot be used because the returned object will not be an array;

The solution is to use an array variable in which to save the result; This way you will allways have an arry even if it have only one or no elements in it;


function Retrive-Services{ Get-Service -DisplayName w* }

$var = @(Retrive-Services)

if ($var.count -ge 1){
     $var.gettype()
     "array-ul have " + $var.Count + " records."
     
    foreach ($v in $var){
         $v.name # here you will ussualy do some work;
    }
}
elseif ($var.count -eq 0){
    $var.gettype()
    "array-ul have zero records"
}

Array of custom objects in PowerShell

create a custom object in Powershell v1:

$CustomObject = @()

$obj = New-Object pscustomobject
$obj | Add-Member -property NoteProperty -name somename -value somevalue

$CustomObject += $obj


create a custom object in Powershell v2:

$CustomObject = @()

$obj = New-Object pscustomobject -Properties @{propertyname1= value1; propertyname2=value2}


$CustomObject += $obj


create a custom object in Powershell v2 (variation of method above):

$CustomObject = @()

$hash = @{
    propertyname1 = value1
    propertyname2 = value2
    propertyname3 = value3
}

$obj = New-Object pscustomobject -Properties $hash


$CustomObject += $obj


15 May 2012

netsh - enble / disable network interface


netsh interface set interface name="Local Area Connection" admin=disabled
sleep 10
netsh interface set interface name="Local Area Connection" admin=enabled