SoftwareSavant
SoftwareSavant

Reputation: 9767

Powershell function with Parameters throwing null exception

This script is throwing a null exception and I am not certain why that is the case...

Function StopServices{    
    Param
    (
        $ServiceName,     
        $Remoteserver
    )
    write-host($Remoteserver)
    write-host($ServiceName)
    [System.ServiceProcess.ServiceController]$service = Get-Service -Name $ServiceName -ComputerName $Remoteserver
}

the write-host writes the variable. The Get-Service -ComputerName method throws this exception:

powershell cannot validate argument on parameter 'computername' the argument is null or empty

I am wondering what they are talking about, Neither is empty...

StopServices("DUMMY","VALUES")

Neither of those are empty. Why is it throwing that exception?

Upvotes: 4

Views: 4666

Answers (3)

user2555451
user2555451

Reputation:

Unlike most languages, PowerShell does not use parenthesis to call a function.

This means three things:

  1. ("DUMMY","VALUES") is actually being interpreted as an array. In other words, you are only giving StopServices one argument instead of the two that it requires.

  2. This array is being assigned to $ServiceName.

  3. Due to the lack of arguments, $Remoteserver is assigned to null.


To fix the problem, you need to call StopServices like this:

PS > StopServices DUMMY VALUES

Upvotes: 6

mikekol
mikekol

Reputation: 1862

Actually, $RemoteServer is null.

StopServices("Dummy", "Values") isn't doing what you think it's doing - PowerShell doesn't take arguments to functions in the same way that other programming languages do. PowerShell is interpreting the syntax you're using as an expression to create an array with two values in it ("DUMMY" and "VALUES), and to store that array in $ServiceName, leaving $RemoteServer as $null.

One of the following examples will give you the behavior you're after:

StopServices "Dummy" "Values"

-or-

StopServices -ServiceName "Dummy" -RemoteServer "Values"

Upvotes: 5

KevinD
KevinD

Reputation: 3163

You're calling the function incorrectly. You should be calling it like this:

StopServices "DUMMY" "VALUES"

Or, if you want to be more clear:

StopServices -ServiceName DUMMY -Remoteserver VALUES

The way you are passing the parameters to the function, PowerShell interprets ("DUMMY", "VALUES") as an array, which would get assigned to $ServiceName, leaving $Remoteserver null.

Upvotes: 4

Related Questions