CodexBloom - Programming Q&A Platform

PowerShell 7.3 - how to Retrieve Environment Variables When Executing Scripts with `Invoke-Command`

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-19
powershell remote invoke-command PowerShell

I'm sure I'm missing something obvious here, but Quick question that's been bugging me - I've searched everywhere and can't find a clear answer. I'm relatively new to this, so bear with me. I'm wondering if anyone has experience with I'm stuck trying to I've looked through the documentation and I'm still confused about I'm having trouble accessing environment variables when executing a PowerShell script remotely using `Invoke-Command`..... I am running PowerShell 7.3 and trying to access a specific environment variable that is set on the remote machine. However, when I attempt to retrieve the variable, it seems to return `$null` instead of the expected value. Here’s a snippet of my code: ```powershell $session = New-PSSession -ComputerName 'RemotePC' Invoke-Command -Session $session -ScriptBlock { $env:MY_ENV_VAR } Remove-PSSession -Session $session ``` I expected this to return the value of `MY_ENV_VAR`, but it results in `$null`. I've verified that `MY_ENV_VAR` is indeed set on the remote machine, as I can access it from a direct PowerShell session. I also tried using `Get-ChildItem Env:` to list all environment variables within the script block, and it does not show `MY_ENV_VAR` in the output. I've checked the execution policy and the user context under which the command is being executed, and it seems correct. Additionally, I attempted to run it with `-Credential`, but that didn't resolve the scenario either. This behavior is quite perplexing since other environment variables are accessible. Is there an scenario with how environment variables are scoped in remote sessions, or is there something I might be missing? This is part of a larger web app I'm building. Is there a better approach? I appreciate any insights! Hoping someone can shed some light on this. What's the correct way to implement this? This issue appeared after updating to Powershell stable. I'm on Linux using the latest version of Powershell. Thanks, I really appreciate it! I'm using Powershell LTS in this project. I'm open to any suggestions.