[英]How to get Invoke-Command verbose or debug output from a PowerShell command in C#
我有一個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
調用上指定調試首選項...
首選項變量會影響PowerShell操作環境,並且所有命令都在該環境中運行。
這里的重點是“在環境中”
在其他環境上運行的命令與調用命令的偏好設置不同。
-Debug[:{$true | $false}]
顯示有關命令執行的操作的程序員級詳細信息。 僅當命令生成調試消息時,此參數才有效。 例如,當命令包含Write-Debug cmdlet時,此參數有效。
$params = @{
ComputerName = $ip
Credential = $cred
ScriptBlock = $cmd
Debug = $true
}
Invoke-Command @params
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.