c# - 将 powershell 内容保存为 JSON 格式,值为空
问题描述
我必须使用 command 保存一些信息Get-NetFirewallRule
,并将它们保存在 .JSON 文件中。这就是我所做的
Get-NetFirewallRule |
select-object -Property Name,
DisplayName,
DisplayGroup,
@{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}},
@{Name='LocalPort';Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}},
@{Name='RemotePort';Expression={($PSItem | Get-NetFirewallPortFilter).RemotePort}},
@{Name='RemoteAddress';Expression={($PSItem | Get-NetFirewallAddressFilter).RemoteAddress}},
Enabled,
Profile,
Direction,
Action |
ConvertTo-Json | Out-File "C:\Users\Administrator\Desktop\firewall.txt"
输出文件是这个(这是文件的一小部分)
"Name": "Microsoft-Windows-PeerDist-WSD-Out",
"DisplayName": "BranchCache Peer Discovery (WSD-Out)",
"DisplayGroup": "BranchCache - Peer Discovery (Uses WSD)",
"Protocol": "UDP",
"LocalPort": "Any",
"RemotePort": "3702",
"RemoteAddress": "LocalSubnet",
"Enabled": 2,
"Profile": 0,
"Direction": 2,
"Action": 2
},
{
"Name": "Microsoft-Windows-PeerDist-HostedServer-In",
"DisplayName": "BranchCache Hosted Cache Server (HTTP-In)",
"DisplayGroup": "BranchCache - Hosted Cache Server (Uses HTTPS)",
"Protocol": "TCP",
"LocalPort": {
"value": [
"80",
"443"
],
"Count": 2
},
"RemotePort": "Any",
"RemoteAddress": "Any",
"Enabled": 2,
"Profile": 0,
"Direction": 1,
"Action": 2
}
如您所见,powershell 以两种不同的方式保存 LocalPort:第一种使用 1 值,第二种使用 2 值和 Count;在我的代码(C#)中,我写了这个来读取我的 JSON 文件
string file = File.ReadAllText(MainWindow.path + @"\..\..\misc\json\FirewallRules.json");
List<GetSetFRules> rulesList = JsonConvert.DeserializeObject<List<GetSetFRules>>(file);
但有个问题; 该类GetSetFRules
无法保存 JSON 的内容,因为每个规则的 JSON 格式都不相同
class GetSetFRules
{
public string Name { get; set; }
public string DisplayName { get; set; }
public string DisplayGroup { get; set; }
public string Protocol { get; set; }
public Localport LocalPort { get; set; }
public string RemotePort { get; set; }
public string RemoteAddress { get; set; }
public int Enabled { get; set; }
public int Profile { get; set; }
public int Direction { get; set; }
public int Action { get; set; }
}
public class Localport
{
public string[] value { get; set; }
public int Count { get; set; }
}
所以,问题是,有没有办法像这样用空值保存每个规则?
[...]"LocalPort": "Any",[...]
⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇</p>
[...]"LocalPort": {
"value": [
"Any",
],
"Count": 1
}[...]
或这个
[...]"LocalPort": {
"value": [
"",
],
"Count": 0
}[...]
解决方案
我想我找到了解决方案
用类替换GetSetFRules
类dynamic
List<dynamic> rulesList = JsonConvert.DeserializeObject<List<dynamic>>(file);
推荐阅读
- python - 为什么'return'在生成器方法中不起作用?
- reporting-services - SSRS 浏览器的渲染与 SSDT 不同
- java - JavaFX 的 ImageView 中的屏幕共享
- azure-ad-b2c - 如果用户不是成人,则尝试获取用户的出生日期
- python - pyenv:没有这样的命令“virtualenv”
- bash - bash函数在后台运行命令
- typo3 - Typo3:如何在页眉和页脚中设置常用数据,如徽标?
- selenium-ide - 无法在 Selenium IDE 中导出测试用例
- node.js - UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“正文”
- html - 表格单元格内的 HTML 输入