BigBearFreddy
BigBearFreddy

Reputation: 11

How to use Function parameters

I'm trying to parse different variables to a parameters and used them named parameters.

This method works:

Function Read-AdEnvironment {
    Param([string[]]$Results)
    Write-Host "Server: ",$Results[0]
    Write-Host "SecretName: "$Results[1]
}

Output:

Server:  10.0.11.110    
SecretName:  AD-NL                              
Server:  192.168.50.101 
SecretName:  AD-DE
Server:  192.168.13.9   
SecretName:  AD-I 
Server:  192.168.8.251  
SecretName:  AD-CH

However, I prefer named parameters, but can't get this to function properly:

Function Read-AdEnvironment {
    param ([string]$Server, [string]$SecretName)
    Write-Host "Server: ",$Server
    Write-Host "SecretName: ",$SecretName
}

Output:

Server:  10.0.11.110 AD-NL   
SecretName:                                          
Server:  192.168.50.101 AD-DE
SecretName:
Server:  192.168.13.9 AD-I
SecretName:
Server:  192.168.8.251 AD-CH
SecretName:

Any help appreciated.

Upvotes: 0

Views: 67

Answers (1)

user459872
user459872

Reputation: 24562

I think most likely you would be calling the function like this.

Read-AdEnvironment("Some ServerName", "Some Secret Name")

When you call the function like this, PowerShell treats the input as a single array containing two elements and pass it positionally to the first variable(In this case it's $Server).

Instead your should call the function like this to get the expected behavior.

Read-AdEnvironment "Some ServerName" "Some SecretName"

or

Read-AdEnvironment -Server "Some ServerName" -SecretName "Some SecretName"

Upvotes: 3

Related Questions