在PowerShell中进行.NET跟踪而无需创建.config文件

Mar*_*ryl 6 .net powershell app-config

我知道我可以通过在PowerShell安装文件夹中的App config()中添加元素来启用.NET跟踪在Powershell中的System.Net跟踪中对此进行了介绍。<system.diagnostics>powershell.exe.config

实际上,我也想记录System.Net跟踪源(例如FtpWebRequest

但是,有什么方法可以启用本地跟踪吗?像代码本身一样?还是可能使用某些命令行开关?还是至少可以在本地文件夹中拥有App配置文件,而不必修改系统范围的设置?

Pet*_*art 7

Trace.Information在代码中(因此在Powershell中)启用默认跟踪源(等)相对容易。

System.Net跟踪源执行此操作更为复杂,因为它们无法公开访问。

之前我已经看到过,在C#中,调用一个System.Net方法(例如Dns.ResolveTraceSource对于创建要创建的对象是必需的,但是在Powershell中似乎并不需要。

因此,这不是一个很好的解决方案...但是,我猜这取决于您的替代方案:

$id = [Environment]::TickCount;
$fileName = "${PSScriptRoot}\Powershell_log_${id}.txt"
$listener1 = [System.Diagnostics.TextWriterTraceListener]::New($fileName, "text_listener")
$listener2 = [System.Diagnostics.ConsoleTraceListener]::New()
$listener2.Name = "console_listener"

[System.Diagnostics.Trace]::AutoFlush = $true
[System.Diagnostics.Trace]::Listeners.Add($listener1) | out-null
[System.Diagnostics.Trace]::Listeners.Add($listener2) | out-null

# Use reflection to enable and hook up the TraceSource
$logging = [System.Net.Sockets.Socket].Assembly.GetType("System.Net.Logging")
$flags = [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static
$logging.GetField("s_LoggingEnabled", $flags).SetValue($null, $true)
$webTracing = $logging.GetProperty("Web", $flags);
$webTraceSource = [System.Diagnostics.Tracesource]$webTracing.GetValue($null, $null);
$webTraceSource.Switch.Level = [System.Diagnostics.SourceLevels]::Information
$webTracesource.Listeners.Add($listener1) | out-null
$webTracesource.Listeners.Add($listener2)  | out-null

[System.Diagnostics.Trace]::TraceInformation("About to do net stuff");
[System.Net.FtpWebRequest]::Create("ftp://www.google.com") | out-null
[System.Diagnostics.Trace]::TraceInformation("Finished doing net stuff");

#get rid of the listeners
[System.Diagnostics.Trace]::Listeners.Clear();
$webTraceSource.Listeners.Clear();
$listener1.Dispose();
$listener2.Dispose();
Run Code Online (Sandbox Code Playgroud)