我有一个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#访问它?
答案 0 :(得分:0)
我估计您可能需要在Invoke-Command
调用...
首选项变量会影响PowerShell操作环境,并且所有命令都会在环境中运行。
这里的关键点是 “在环境中”
在其他环境中运行的命令与调用命令不共享相同的首选项设置。
-Debug[:{$true | $false}]
显示有关命令执行的操作的程序员级详细信息。该参数仅在命令生成调试消息时有效。例如,当命令包含Write-Debug cmdlet时,此参数有效。
$params = @{
ComputerName = $ip
Credential = $cred
ScriptBlock = $cmd
Debug = $true
}
Invoke-Command @params