Question:
This script is throwing a null exception and I am not certain why that is the case…
1 2 3 4 5 6 7 8 9 10 11 |
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:
1 2 |
powershell cannot validate argument on parameter 'computername' the argument is null or empty |
I am wondering what they are talking about, Neither is empty…
1 2 |
StopServices("DUMMY","VALUES") |
Neither of those are empty. Why is it throwing that exception?
Answer:
Unlike most languages, PowerShell does not use parenthesis to call a function.
This means three things:
("DUMMY","VALUES")
is actually being interpreted as an array. In other words, you are only givingStopServices
one argument instead of the two that it requires.- This array is being assigned to
$ServiceName
. - Due to the lack of arguments,
$Remoteserver
is assigned to null.
To fix the problem, you need to call StopServices
like this:
1 2 |
PS > StopServices DUMMY VALUES |