我需要在powershell中解析netsh命令提供的输出。下面是我使用的命令
Netsh advfirewall show private它证明了下面的输出
Private Profile Settings:
----------------------------------------------------------------------
State ON
Firewall Policy BlockInbound,AllowOutbound
LocalFirewallRules N/A (GPO-store only)
LocalConSecRules N/A (GPO-store only)
InboundUserNotification Enable
RemoteManagement Disable
UnicastResponseToMulticast Enable
Logging:
LogAllowedConnections Disable
LogDroppedConnections Disable
FileName %systemroot%\system32\LogFiles\Firewall\pfirewall.log
MaxFileSize 4096我的要求是访问上述输出中的每个值。有点像$result.state / $result.InboundUserNotification
我对PowerShell非常陌生,我在谷歌上搜索过这件事,却什么也找不到。
发布于 2020-11-11 15:50:55
如果必须解析此输出,则可以执行以下操作:
$netsh = (Netsh advfirewall show private |
Select-String -Pattern "\s{2,}") -replace '\s{2,}','=' -replace '\\','\\' -join [System.Environment]::NewLine
$result = [pscustomobject](ConvertFrom-StringData $netsh)ConvertFrom-StringData方法的问题是哈希表输出没有排序。如果顺序很重要,您只需将每行拆分为属性/值对,就可以创建哈希表:
$hash = [ordered]@{}
Netsh advfirewall show private | Select-String -Pattern "\s{2,}" |
Foreach-Object {
$key,$value = $_ -split '\s{2,}'
$hash[$key] = $value
}
$result = [pscustomobject]$hash发布于 2020-11-11 15:56:38
下面是AdminOfThings答案使用ConvertFrom-StringData以及Foreach-Object的-Begin和-End参数的类似方法。
Netsh advfirewall show private |
ForEach-Object -Begin{$ht = [ordered]@{}} {
if($_ -match '\s{10,}')
{
$ht += $_ -replace '\\','\\' -replace '\s{10,}','=' | ConvertFrom-StringData
}
} -End{[PSCustomObject]$ht} -OutVariable result和轻微的变化
Netsh advfirewall show private | Where-Object {$_ -match '\s{10,}'} |
ForEach-Object -Begin{$ht = [ordered]@{}} {
$ht += $_ -replace '\\','\\' -replace '\s{10,}','=' | ConvertFrom-StringData
} -End{[PSCustomObject]$ht} -OutVariable resulthttps://stackoverflow.com/questions/64789327
复制相似问题