PowerShell 7.3 - How to Properly Use Invoke-Command with Session Variable Scope for Remote Execution?
This might be a silly question, but I'm trying to execute a script block remotely using `Invoke-Command`, but I'm running into scoping issues with variables. I've set up a session using `New-PSSession` and when I try to access a variable defined in the local scope, I'm getting the behavior `You want to call a method on a null-valued expression`. Here's my code snippet: ```powershell # Create a new session $session = New-PSSession -ComputerName 'RemotePC' # Define a variable in the local scope $localVar = 'Hello from local scope' # Attempt to invoke a command that accesses the local variable Invoke-Command -Session $session -ScriptBlock { Write-Output $localVar } ``` I expected `Hello from local scope` to be printed, but instead, I see the behavior message. I've tried using `-ArgumentList` to pass the variable, but that doesn't seem to work as intended either. Here's what I attempted: ```powershell Invoke-Command -Session $session -ScriptBlock { param($arg) Write-Output $arg } -ArgumentList $localVar ``` This one runs without behavior, but it outputs nothing. I suspect the scenario is with how I'm passing the variable or the differences in scope between the local and remote sessions. Any guidance on how to correctly pass variables or reference them in a remote execution environment would be greatly appreciated! I'm working on a web app that needs to handle this. Any ideas what could be causing this?