首页 > 解决方案 > C# DHCP 脚本使用大量 cpu

问题描述

我是 C# 新手,但被迫使用它从我们的 Windows DHCP 服务器中正确获取数据。我有一个脚本,它将数据作为 JSON 报告给我们的 Web 应用程序。我们在服务器上大约有 700 个范围,发现 .NET 应用程序使用大约 50% 的 CPU 来收集数据,大约需要 30 分钟才能完成。

        // 
    // PowerShell Function Wrapper
    static private Collection<PSObject> Execute(string Command, IDictionary<string, string> Parameters)
    {
        Console.WriteLine("Attempting to execute command: " + Command);
        using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
            // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
            PowerShellInstance.AddCommand("Import-Module");
            PowerShellInstance.AddParameter("Name", "DHCPServer");
            PowerShellInstance.Invoke();
            PowerShellInstance.Commands.Clear();

            //
            // Actual Commands we can to see
            PowerShellInstance.AddCommand(Command);
            foreach (KeyValuePair<string, string> param in Parameters)
            {
                // use "AddParameter" to add a single parameter to the last command/script on the pipeline.
                PowerShellInstance.AddParameter(param.Key.ToString(), param.Value);
            }

            return PowerShellInstance.Invoke();

        }
    }

    //
    // Function to check if agent is already running.
    static public bool AmIRunning()
    {
        // 
        // Only one of me can exist at a time

        // Get Reference to the current Process
        Process thisProc = Process.GetCurrentProcess();

        // Check how many total processes have the same name as the current one
        if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
        {
            return true;
        }
        return false;


    }

    //
    // Grab DHCP Statics from server.
    static public string FetchReport(Config Config)
    {

        // DHCP Server Scopes 
        IDictionary<string, string> Paramaters = new Dictionary<string, string>() {
            { "ComputerName", Config.Get("PrimaryServer") },
        };
        var response = Scripts.Execute("Get-DhcpServerv4Scope", Paramaters);
        List<Dictionary<string, dynamic>> ScopeInfo = new List<Dictionary<string, dynamic>>();
        foreach (PSObject outputItem in response)
        {
            object ScopeId = 0;
            Dictionary<string, dynamic> ScopeDetails = new Dictionary<string, dynamic>();
            foreach (PSPropertyInfo scope in outputItem.Properties)
            {
                if (scope.Name == "ScopeId")
                {
                    ScopeId = scope.Value;
                    Console.WriteLine("Fetching details for Scope " + ScopeId);
                }

                if (
                    scope.Name == "Name" || 
                    scope.Name == "ScopeId" ||
                    scope.Name == "SubnetMask" ||
                    scope.Name == "State" ||
                    scope.Name == "StartRange" ||
                    scope.Name == "EndRange" ||
                    scope.Name == "LeaseDuration")
                {
                    ScopeDetails.Add(scope.Name, scope.Value);
                }


            }
            // Setup Params for next query on DHCP server.
            IDictionary<string, string> ScopeParamaters = new Dictionary<string, string>() {
                    { "ComputerName", Config.Get("PrimaryServer") },
                    { "ScopeId", ScopeId.ToString() }
                };



            //
            // Exclusion Ranges
            List<Dictionary<string, dynamic>> ExclusionList = new List<Dictionary<string, dynamic>>();
            var ExclusionResults = Scripts.Execute("Get-DhcpServerv4ExclusionRange", ScopeParamaters);
            foreach (PSObject ExclusionObj in ExclusionResults)
            {
                Dictionary<string, dynamic> ExclusionDetails = new Dictionary<string, dynamic>();
                foreach (PSPropertyInfo Exclusion in ExclusionObj.Properties)
                {
                    if (Exclusion.Name == "StartRange" || Exclusion.Name == "EndRange")
                    {
                        try
                        {
                            if (Exclusion.Value.Equals(null))
                            {
                                ExclusionDetails.Add(Exclusion.Name, "None");
                            }
                            else
                            {
                                ExclusionDetails.Add(Exclusion.Name, Exclusion.Value);
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Could not add field to array: " + Exclusion.Name);
                        }
                    }
                }
                ExclusionList.Add(ExclusionDetails);
            }
            // Add Leases into larger list. JSONized
            ScopeDetails.Add("ExclusionDetails", ExclusionList);


            // Scope specific options
            var ScopeOptions = Scripts.Execute("Get-DhcpServerv4OptionValue", ScopeParamaters);
            foreach (PSObject OptionsObj in ScopeOptions)
            {
                int OptionId = Convert.ToInt32(OptionsObj.Properties["OptionId"].Value);
                string Value = JsonConvert.SerializeObject(OptionsObj.Properties["Value"].Value);

                if (OptionId == 3)
                {
                    ScopeDetails.Add("Gateway", Value);
                }
                else if (OptionId == 15)
                {
                    ScopeDetails.Add("DomainName", Value);
                }
                else if (OptionId == 6)
                {
                    ScopeDetails.Add("DNS", Value);
                }

            }

            // Add everything to the larger report
            ScopeInfo.Add(ScopeDetails);
        }

        // Send back final JSON
        string FinalData = JsonConvert.SerializeObject(ScopeInfo);
        return FinalData;  // Go Home.

    }

标签: c#powershelldhcp

解决方案


推荐阅读