Script not reading input on Powershell 7.0 Ubuntu

PowerShell 7.0
Ubuntu 18.04
Windows 2019
OpenSSh

writing a simple script on Ubuntu to get service info on a windows server

#! /opt/microsoft/powershell/7-lts/pwsh

$server = $args[0]
$service = $args[1]
invoke-command -hostname $server -scriptblock {get-service $service}

when I run the script

thomas@serv017:/opt/microsoft/powershell/7-lts/Modules$ ./test.psm1 serv027-n1 nscp
Get-Service: Cannot validate argument on parameter ‘Name’. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

Any ideas?

Thank you

Tom

Tom,

That code looks so much better, thank you! Check out these links on this very topic. Be sure to search the internet and this forum before posting, there is a good chance it’s already been answered!

https://powershell.org/forums/topic/invoke-command-scriptblock-variables/

https://powershell.org/forums/topic/passing-local-variables-to-remote-invoke-command-filepath-to-script/

https://powershell.org/forums/topic/invoke-command-with-variables/

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/invoke-command?view=powershell-7

https://stackoverflow.com/questions/40247384/passing-string-variable-to-invoke-command-scriptblock-parameter-name

This should get you going.

Doug,

Yes I was searching on the web first I found -ArgumentList but could not get that to work

You one link had something I did not find before and that worked.

$server = $args[0]
$service = $args[1]

write-host $server
write-host $service

invoke-command -computername $server -ScriptBlock { Get-Service $Using:service }

This works now $Using:

Thanks now off to the Ubuntu server to test this.

Yes using is one way. The point of the exercise is to understand your local variables will not be present in the remote session unless you provide it in one way or another. Of course, you got using working. Just understand with it, any local variable just turns into $using:variable in the remote session.

$variable = 'some service name' #local variable
invoke-command -hostname $server -scriptblock {
get-service $using:variable
}

For the args to work, you would need to pass them in with the arguments parameter and reference them with the index.

$variable = 'some service name' #local variable
invoke-command -hostname $server -scriptblock {get-service $args[0]} -argumentlist $variable

You can also handle the parameter naming yourself and again pass it through with argumentlist

$variable = 'some service name' #local variable
invoke-command -hostname $server -scriptblock {
Param($Service)
get-service $service
} -argumentlist $variable