protected override void BeginProcessing() { base.BeginProcessing(); if (hostFile == string.Empty) { hostFile = Path.Combine(Environment.SystemDirectory, "drivers\\etc\\hosts"); } WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent()); if (!wp.IsInRole(WindowsBuiltInRole.Administrator)) { ThrowTerminatingError(new ErrorRecord(new UnauthorizedAccessException("You must have Administrative permissions to run this command"), "100", ErrorCategory.PermissionDenied, null)); } else { HostEntryCollection entryCollection = HostFileHandler.GetHostEntryColletion(hostFile); IPAddress setAddress = System.Net.IPAddress.Parse(setIP); foreach (string newHost in setHostnames) { if (entryCollection[newHost] == null) { if (entryCollection[setAddress] == null) { HostEntry newEntry = new HostEntry(); newEntry.IPAddress = setAddress; newEntry.AddHostname(newHost); newEntry.Comment = comment; entryCollection.Add(newEntry); } else { entryCollection[setAddress].AddHostname(newHost); } } else { WriteError(new ErrorRecord(new InvalidDataException(string.Format("Host '{0}' already present in the host file and will not be added", newHost)), "200", ErrorCategory.InvalidData, null)); } } HostFileHandler.PersistHostEntryCollection(hostFile, entryCollection); } }
public static HostEntryCollection GetHostEntryColletion(string hostFile) { HostEntryCollection result = new HostEntryCollection(); if (hostFile == string.Empty) { hostFile = Path.Combine(Environment.SystemDirectory, "drivers\\etc\\hosts"); } string[] fileContent = File.ReadAllLines(hostFile); foreach (string fileRow in fileContent) { string dataToProcess = fileRow.Trim(); if (!dataToProcess.StartsWith("#")) { if (dataToProcess.Contains(' ')) { string[] fileValues = dataToProcess.Split(new char[] { ' ' }, 2); // Get the IPAddress IPAddress ipAddresser = IPAddress.Parse(fileValues[0].Trim()); HostEntry hostEntry = result[ipAddresser]; if (hostEntry == null) { hostEntry = new HostEntry(); hostEntry.IPAddress = ipAddresser; result.Add(hostEntry); } // Get the Comment & hostnames string[] commentValue = fileValues[1].Split('#'); string hostnameString = string.Empty; if (commentValue.Length > 1) { string commentString = commentValue[1].Trim(); if (commentString.Length > 0) { hostEntry.Comment = (commentValue[1] + " " + hostEntry.Comment).Trim(); hostnameString = fileValues[1].Replace(commentValue[1], "").Replace("#", "").Trim(); } else { hostnameString = fileValues[1].Replace("#", "").Trim(); } } else { hostnameString = fileValues[1].Trim(); } List <string> hostNames = new List <string>(); string[] fileHosts = hostnameString.Split(' '); foreach (string fileHost in fileHosts) { string addFile = fileHost.Trim(); if (addFile != null && addFile != string.Empty) { if (!hostEntry.ContainsHostname(addFile)) { hostEntry.AddHostname(addFile); } } } } } } return(result); }