如何解决此cmdlet中的输入字符串问题?

时间:2019-06-14 14:50:33

标签: c# powershell

所以在过去的一个月中,我一直试图学习一些C#,目的是编写一些PowerShell模块。我查看了一些articlesdocumentation(使用C#创建客户端-Microsoft.Management.Infrastructure),尝试将一个简单的CIM cmdlet放在一起,该cmdlet将返回本地网络适配器。

类库可以编译,但是当我在PowerShell中运行命令时,它会显示格式异常。

Show-LocalAdapter : Input string was not in a correct format.

在基于函数的问题中,我通常会在错误报告中看到一行问题,但是该错误并没有使用cmdlet指向正确的方向。

希望我能用尽我有限的调试此问题的知识,能在这里为我提供帮助。

这是cmdlet的代码。

using System.Collections;
using System.Linq;
using System.Management.Automation;
using System.Text.RegularExpressions;
using Microsoft.Management.Infrastructure;

namespace NetTest
{
    [Cmdlet(VerbsCommon.Show, "LocalAdapter")]
    [OutputType(typeof(NetworkAdapter))]
    public class ShowLocalAdapterCmdlet : PSCmdlet
    {
        private string[] _manufacturer;
        private string _name;
        private bool? _physicalAdapter;
        private int _maxEntries = 100;

        [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        [Alias("Vendor")]
        public string[] Manufacturer
        {
            get { return this._manufacturer; }
            set { _manufacturer = value; }
        }

        [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)]
        public string Name
        {
            get { return this._name; }
            set { _name = value; }
        }

        [Parameter(Position = 2, ValueFromPipelineByPropertyName = true)]
        public bool? PhysicalAdapter
        {
            get { return this._physicalAdapter; }
            set { _physicalAdapter = value; }
        }

        [Parameter(Position = 3)]
        public int MaxEntries
        {
            get { return this._maxEntries; }
            set { _maxEntries = value; }
        }

        protected override void BeginProcessing()
        {
            base.BeginProcessing();
        }

        protected override void ProcessRecord()
        {
            CimSession session = CimSession.Create("localHost");
            IEnumerable cimResults = session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_NetworkAdapter");
            var query = cimResults.Cast<CimInstance>().Select(ReturnNetworkAdapter);

            // Filter Name
            if (Name != null)
            {
                query = query.Where(adapter => adapter.Name != null && adapter.Name.StartsWith(Name));
            }

            // Manufacturer Filter
            if (Manufacturer != null)
            {
                query = query.Where(
                    adapter =>
                        adapter.Manufacturer != null &&
                        Regex.IsMatch(adapter.Manufacturer.ToString(),
                            string.Format("^(?:{0})", string.Join("|", Manufacturer))));
            }

            // Physical Adapter: true or false
            if (PhysicalAdapter != null)
            {
                query = query.Where(adapter =>
                    adapter.PhysicalAdapter == PhysicalAdapter);
            }

            // Return objects
            query.Take(MaxEntries).ToList().ForEach(WriteObject);
        }

        private static NetworkAdapter ReturnNetworkAdapter(CimInstance item)
        {
            return new NetworkAdapter
            {
                Name            = item.CimInstanceProperties["Name"].ToString(),
                Description     = item.CimInstanceProperties["Description"].ToString(),
                DeviceId        = int.Parse(item.CimInstanceProperties["DeviceId"].ToString()),
                Manufacturer    = item.CimInstanceProperties["Manufacturer"].ToString(),
                NetConnectionId = item.CimInstanceProperties["NetConnectionId"].ToString(),
                PhysicalAdapter = bool.Parse(item.CimInstanceProperties["PhysicalAdapter"].ToString())
            };
        }
    }
}

这是网络适配器对象的类。

namespace NetTest
{
    public class NetworkAdapter
    {
        private string _name;
        private string _description;
        private int _deviceId;
        private string _manufacturer;
        private string _netConnectionId;
        private bool _physicalAdapter;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }
        public int DeviceId
        {
            get { return _deviceId; }
            set { _deviceId = value; }
        }
        public string Manufacturer
        {
            get { return _manufacturer; }
            set { _manufacturer = value; }
        }
        public string NetConnectionId
        {
            get { return _netConnectionId; }
            set { _netConnectionId = value; }
        }
        public bool PhysicalAdapter
        {
            get { return _physicalAdapter; }
            set { _physicalAdapter = value; }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

像这样的item.CimInstanceProperties["Name"].ToString()呼叫不是您所期望的。您应该查看属性Value

private static NetworkAdapter ReturnNetworkAdapter(CimInstance item)
{
    return new NetworkAdapter
    {
        Name = item.CimInstanceProperties["Name"].Value.ToString(),
        Description = item.CimInstanceProperties["Description"].Value?.ToString(),
        DeviceId = int.Parse(item.CimInstanceProperties["DeviceId"].Value.ToString()),
        Manufacturer = item.CimInstanceProperties["Manufacturer"].Value?.ToString(),
        NetConnectionId = item.CimInstanceProperties["NetConnectionId"].Value?.ToString(),
        PhysicalAdapter = bool.Parse(item.CimInstanceProperties["PhysicalAdapter"].Value.ToString())
    };
}