gpt4 book ai didi

c# - 如何从 C# 中的 PowerShell 命令获取 Invoke-Command 详细或调试输出

转载 作者:太空宇宙 更新时间:2023-11-03 14:56:13 26 4
gpt4 key购买 nike

我有一个 PowerShell 命令,它调用远程机器上的命令打印出调试信息,然后在运行的机器上打印出调试信息,如下所示:

function Start-DebugTest {
[cmdletbinding()]
param ()

$cmd = {
$DebugPreference = 'Continue'
Write-Debug -Message 'This is invoked DEBUG message'
}

$params = @{
ComputerName = $ip
Credential = $cred
ScriptBlock = $cmd
}

Invoke-Command @params

Write-Debug -Message 'This is a normal DEBUG message'
}

当我在本地运行 Start-DebugTest 命令时,我看到以下输出:

DEBUG: This is invoked DEBUG message
DEBUG: This is a normal DEBUG message

当我像这样通过 C# 运行它时:

using (PowerShell powershell = PowerShell.Create())
{
var command = powershell.AddCommand("Start-DebugTest");
powershell.Runspace.SessionStateProxy.SetVariable("DebugPreference", "Continue");

PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
output.DataAdded += (sender, args) => DataAdded((PSDataCollection<PSObject>) sender, progress);
powershell.Streams.Debug.DataAdded += (sender, args) => StreamDataAdded((PSDataCollection<DebugRecord>) sender, args, "DEBUG", progress);

var resources = await Task.Factory.FromAsync(
powershell.BeginInvoke<PSObject, PSObject>(null, output),
asyncResult => powershell.EndInvoke(asyncResult));

return resources;
}

private void StreamDataAdded<T>(PSDataCollection<T> records, DataAddedEventArgs e, string msgType, IProgress<string> progress) where T : InformationalRecord
{
string msg = records[e.Index].Message;
progress.Report($"{msgType}: {msg}");
}

private void DataAdded(PSDataCollection<PSObject> myp, IProgress<string> progress)
{
Collection<PSObject> results = myp.ReadAll();
foreach (PSObject result in results)
{
progress.Report($"OUTPUT: {result.ToString()}");
}
}

我只收到在本地机器上运行的调试消息,而不是来自调用命令的调试消息,来自 DataAdded 事件之一:

DEBUG: This is a normal DEBUG message

如果我在本地运行时看到输出,则说明调试消息可用。有什么方法可以从 C# 访问它吗?

最佳答案

我认为您可能必须在 Invoke-Command 调用中指定您的调试首选项...

about_Preference_Variables

The preference variables affect the PowerShell operating environment and all commands run in the environment.

这里的重点是“在环境中”

在其他环境中运行的命令与调用命令不共享相同的首选项设置。

about_CommonParameters

-调试[:{$true | $false}]

Displays programmer-level detail about the operation performed by the command. This parameter works only when the command generates a debugging message. For example, this parameter works when a command contains the Write-Debug cmdlet.

解决方案

$params = @{
ComputerName = $ip
Credential = $cred
ScriptBlock = $cmd
Debug = $true
}

Invoke-Command @params

关于c# - 如何从 C# 中的 PowerShell 命令获取 Invoke-Command 详细或调试输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48900497/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com