I have to save some informations using command Get-NetFirewallRule
, and save them in a .JSON file. This is how I have done
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"
and the output file is this (this is a little part of file)
"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
}
As you can see, powershell save the LocalPort in 2 different ways: the first with 1 value, and the second with 2 value and Count; in my code (C#) I wrote this to read my JSON file
string file = File.ReadAllText(MainWindow.path + @"\..\..\misc\json\FirewallRules.json");
List<GetSetFRules> rulesList = JsonConvert.DeserializeObject<List<GetSetFRules>>(file);
but there is a problem; the class GetSetFRules
cannot save the content of JSON, because the format in JSON isn't the same for each rules
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; }
}
So, the question is, Is there a way to save each rules with empty value like this?
[...]"LocalPort": "Any",[...]
⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇
[...]"LocalPort": {
"value": [
"Any",
],
"Count": 1
}[...]
or this
[...]"LocalPort": {
"value": [
"",
],
"Count": 0
}[...]