[英]How do I get environment variable value from remote powershell C# code?
我正在通過 C# Powershell 庫連接到遠程機器,並希望通過 C# 代碼從該機器獲取環境變量。 通過搜索其他堆棧溢出線程,我認為類似以下內容會起作用:
using (var psShell = PowerShell.Create())
{
using (var remoteRunspace = RunspaceFactory.CreateRunspace(CreateSession()))
{
remoteRunspace.Open();
psShell.Runspace = remoteRunspace;
string userProfilePath = remoteRunspace.SessionStateProxy.PSVariable.GetValue("env:USERPROFILE").ToString();
}
}
但是它不起作用。 我得到一個Specified method is not supported
異常......進一步鑽探,我看到SessionStateProxy
具有由於PSNotSupportedException
而未啟動的屬性:
Looking at powershell code, this makes sense too: https://github.com/PowerShell/PowerShell/blob/b1e998046e12ebe5da9dee479f20d479aa2256d7/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs#L3310
那么我如何通過 C# 遠程 powershell 代碼獲取環境變量值,而無需簡單地運行遠程腳本到 output 值或其他東西(我不想要什么正確的方式)?
如果您需要目標機器上的完整環境變量列表,或者只需要其中一個,請使用以下代碼:
using (var psShell = PowerShell.Create())
{
// Set up remote connection code
// Empty means that you will get all environment variables on target machine.
// You can use specific environment variable name to get only one.
var environmentVariableName = string.Empty;
psShell.AddCommand("Get-ChildItem")
.AddParameter("Path", $"Env:\\{environmentVariableName}");
var environmentVariablesDictionary = psShell.Invoke<DictionaryEntry>(); // Here will be dictionary of environment variables.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.