0

how can i add more than one function within a script and then call them by entering parameters? for example in the code below it meants to change configuration in the local area connection so i would like to call the function like so SscriptNAme -Change 192.168.0.1, 255.255.255.255, 192.168.0.2. and I want to have other functions within the same script that i would also like to call by entering parameters:

function Change{

$S=$executionContext.InvokeCommand.NewScriptBlock("netsh interface ip set address name = 'Local              Area Connection' source=static addr=$args[0] mask=$args[1] gateway=$args[2] gwmetric=0")

}

function ChangeOne{ 

$S=$executionContext.InvokeCommand.NewScriptBlock("netsh interface ip set address name = 'Local   Area Connection' source=static addr=$args[0] mask=$args[1] gateway=$args[2] gwmetric=0")

}

can someone tell me if im in the right direction and give me some pointers on how to do it. thanks

2 Answers 2

1

You could have found this with 1 google query but here you go:

function Change{
param(
[parameter(Mandatory=$true,Position=0)]
[string] $address,
[parameter(Mandatory=$true)]
[string] $mask,
[parameter(Mandatory=$true)]
[string] $gw,
[int] $metric=0
)

Do Stuff

}

For Calling the Function:

Change -address $address -mask $mask -gw $gw -metric $metric

Metric is not mandatory and defaults to 0.

The Parameters address, mask and gw also get testet if they contain a value, in case one of the mandatory parameters are empty or just not present the function will throw an error.

You can also assign the parameters a Position so you dont have to use the flags (demonstrated on address) for a call like this:

Change $address -mask $mask -gw $gw

More about Parameters here:

Technet

But i urge you to not use netsh or even invoke-expression in that fashion, there are cmdlets for this kind of stuff! For Example:

Get-NetAdapter "Ethernet" | New-NetIPAddress $address -Defaultgateway $gw -PrefixLength $sn
Sign up to request clarification or add additional context in comments.

Comments

0
function Change
{
    param($addr, $mask, $gw, $metric=0)
    $S=$executionContext.InvokeCommand.NewScriptBlock("netsh interface ip set address name='Local              Area Connection' source=static addr=$addr mask=$mask gateway=$gw gwmetric=$metric")

}

#To call use this, note, no commas between args, and $metric is defined 0 by default.
Change 192.168.0.2 255.255.255.255 192.168.0.1  

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.