0

I know there are other ways (may be even easier) to get this done... my questions is why I'm getting an error when using a variable instead of a session ID (i.e. 1, 2, 3)

cls
$pc = Read-Host "Computer Name: "
echo $pc
Get-Service -Name WinRM -ComputerName $pc | Set-Service -Status Running
Invoke-Command -ComputerName $pc -ScriptBlock { quser }
$session = Read-Host "Session ID: "
$session = $session -as [int]
echo $session
Invoke-Command -ComputerName $pc -ScriptBlock { logoff $session }

if I run:

Invoke-Command -ComputerName $pc -ScriptBlock { logoff 1 }

I get no error... any easy way to get it working with my current script?

Thank you in advance!

user1245735
  • 43
  • 1
  • 9
  • I changed it to say: Invoke-Command -ComputerName $pc -ArgumentList $session -ScriptBlock { logoff $session } but getting same error... thank you... – user1245735 Nov 30 '20 at 22:48
  • Yeah that's not what it's saying. If you want to pass the argument in, then you need to either use param block designating your own variable or `args[0]` - or like the answer there says use `$using:session` – Doug Maurer Nov 30 '20 at 23:01

1 Answers1

1

You have several options.

Use the using scope modifier

Invoke-Command -ComputerName $pc -ScriptBlock { logoff $using:session }

Use -ArgumentList with your own defined parameter. They are named the same here for convenience, the param statement could have any variable name*.

Invoke-Command -ComputerName $pc -ScriptBlock {Param($session) logoff $session} -argumentlist $session

Use -ArgumentList with the automatic args variable. Since it's the first argument you reference with [0]

Invoke-Command -ComputerName $pc -ScriptBlock {logoff $args[0]} -argumentlist $session

*Any variable name that is not automatic or reserved

Doug Maurer
  • 8,090
  • 3
  • 12
  • 13
  • right on, works beautifully, thank you so much, any document or key words I can search to help me understand the why behind it or it really works? ty – user1245735 Dec 01 '20 at 15:45
  • https://stackoverflow.com/questions/36328690/how-do-i-pass-variables-with-the-invoke-command-cmdlet – Doug Maurer Dec 01 '20 at 16:05
  • https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-7.1 – Doug Maurer Dec 01 '20 at 16:10