如何使用 powershell 将 vpn 日志记录用户名导出到 csv?

how to export vpn logging username to csv with powershell?

我使用powershell导出vpn日志信息,代码如下

Get-RemoteAccessConnectionStatistics | Select-Object -Property ClientIPAddress, ClientExternalAddress, ConnectionStartTime, Username, TunnelType

带{}的“用户名”输出
https://i.stack.imgur.com/h8sB2.jpg

如果我使用此代码导出到 csv,用户名显示 System.String[]

Get-RemoteAccessConnectionStatistics | Select-Object -Property ClientIPAddress, ClientExternalAddress, ConnectionStartTime, Username, TunnelType | Export-Csv C:\pvn.csv

输出结果,用户名显示System.String[]

#TYPE Selected.Microsoft.Management.Infrastructure.CimInstance
"ClientIPAddress","ClientExternalAddress","ConnectionStartTime","Username","TunnelType"
"192.168.1.233","123.123.1.4","2021/3/9 ?? 05:31:18","System.String[]","L2tp"

我把用户名改成{$.用户名},导出csv,音量正常,但标题显示{$.用户名}

Get-RemoteAccessConnectionStatistics | Select-Object -Property ClientIPAddress, ClientExternalAddress, ConnectionStartTime, {$_.Username, TunnelType | Export-Csv C:\pvn.csv

输出结果

#TYPE Selected.Microsoft.Management.Infrastructure.CimInstance
"ClientIPAddress","ClientExternalAddress","ConnectionStartTime","$_.Username","TunnelType"
"192.168.1.233","123.123.1.4","2021/3/9 ?? 05:31:18","domain user\tester","L2tp"

我的问题:
1.how 显示不带 {} 的用户名?
2.how 导出到 csv 用用户名替换标题 {$_.Username}?

您只需将 属性 转换为字符串。有几种方法可以实现这一点:

Get-RemoteAccessConnectionStatistics | Select-Object -Property ClientIPAddress, ClientExternalAddress, ConnectionStartTime, @{n='Username';e={($_.Username|Out-String).trim()}}, TunnelType | Export-Csv C:\pvn.csv

Get-RemoteAccessConnectionStatistics | Select-Object -Property ClientIPAddress, ClientExternalAddress, ConnectionStartTime, @{n='Username';e={"$($_.Username)".trim()}}, TunnelType | Export-Csv C:\pvn.csv

#If there are multiple users and you want them on one line joined by commas.
Get-RemoteAccessConnectionStatistics | Select-Object -Property ClientIPAddress, ClientExternalAddress, ConnectionStartTime, @{n='Username';e={$_.Username -join ','}}, TunnelType | Export-Csv C:\pvn.csv