Link to home
Create AccountLog in
ASP.NET

ASP.NET

--

Questions

--

Followers

Top Experts

Avatar of Brian
Brian🇺🇸

ASP.NET Core MVC Powershell Scripts
Hello Experts,

Is there any way within an ASP.NET Core MVC Web Appplication to retrieve data from a PowerShell Script, call a PowerShell Script or retrieve the following information below from the PowerShell Script that I have now?

PowerShell Code:
$bios = Get-WmiObject -Class Win32_BIOS
$cpu  = Get-WmiObject -Class Win32_Processor
$os   = Get-WmiObject -Class Win32_OperatingSystem
$sys  = Get-WmiObject -Class Win32_ComputerSystem
$key  = Get-WmiObject -Class SoftwareLicensingService

$sysProperties = [ordered]@{
	'-- PC --' = ''

        'Domain' = $sys.domain
	'PC Name' = $os.pscomputername
	'User Name' = $sys.UserName

	'-- Model --' = ''

	'Manufacturer' = $sys.manufacturer
	'Model' = $sys.model
	'Serial Number' = $bios.serialnumber
	'Product Number' = $sys.SystemSKUNumber

	'-- Hardware --' = ''

	'Processor' = $cpu.Name
	'Installed RAM' = $sys.totalphysicalmemory / 1GB -as [int]

	'-- OS --' = ''

	'Edition' = $os.caption
	'OS System Type' = $os.osarchitecture
	'OS Build' = $os.buildnumber
        'Product Key' =$key.OA3xOriginalProductKey;
}
$Separator = '-' * ($sysProperties.Values | Measure-Object -Property Length -Maximum).Maximum
@($sysProperties.Keys) | Where-Object {$_ -like '--*'} | ForEach-Object {$sysProperties[$_] = $Separator}
$sysProperties

Open in new window

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


SOLUTION
Avatar of Mlanda TMlanda T🇿🇦

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account

Avatar of BrianBrian🇺🇸

ASKER

@MlandaT, 1st link is dead and the other 2 are the same. Also, it does not show those values are retrieved from the code to Razor View.

Avatar of Mlanda TMlanda T🇿🇦

I was initially just pointing out a Rearsby path to getting this information in a cross platform way.

Your power shell script the uses, and you can directly query WMI from C#. Living issue is that WMI is obviously Windows only, so this precludes possible situations for you all to run on Linux, which is one of the key Core objectives. You can get a lot of information by querying  the different WMI classes as shown here:

https://www.codeproject.com/Articles/66273/Retrieving-Motherboard-Serial-Number-using-WMI

Avatar of BrianBrian🇺🇸

ASKER

@MlandaT, you are correct. ASP.NET Core will run on other Hosts. I just need this to run on an ASP.NET Core website for recovering the info from Windows machines. I looked at the post you provided but it doesn't go into great detail nor shows how to retrieve the data in an MVC Razor View. Also, not sure if it will work with ASP.NET Core since the System.Management Class is unable to be added to the ASP.NET Core project that I have with is running. ASP.NET Core 1.1

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Mlanda TMlanda T🇿🇦

If you are not looking at multi platform deployment, you can run your application targeting the full .NET Framework and not dotnetcore - it will still be an ASP.NET Core application though. That will give you access to all the System.Management classes. We use that option in some of our applications in order to access ADO.NET classes

https://jonhilton.net/2016/09/07/using-asp-net-core-against-net-4-6/

For accessing this data in your Razor view, you just need to return an object from a controller method.
Just like you would create a controller loading data from a database, populating a model and passing the model to a view. Instead of database, you just load the data from WMI.

Avatar of BrianBrian🇺🇸

ASKER

@MlandaT,

I apologize for the late reply back! Yes, I could create an ASP.NET Web App NOT using DotNetCore. But what I need help with is HOW to create such a Controller/Razor View to retrieve the WMI data. I know how to retrieve data from my DB using MVC but not WMI. Is there anyway you could possibly provide some code for me to look at?

ASKER CERTIFIED SOLUTION
Avatar of Mlanda TMlanda T🇿🇦

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.

Avatar of BrianBrian🇺🇸

ASKER

Yes, I have experience performing CRUD operations against SQL Server DB. I'm very new to WMI. I created a new Project with ASP.NET Web Application (.NET Framework 4.6.1) using C#. However, when I add the code you supplied and checked the link that you supplied I'm unable to use that Class. I'm getting an error that I'm missing a reference or assembly.

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Mlanda TMlanda T🇿🇦

  1. Did you add a "using System.Management" to the top of the file?
  2. Visual Studio will usually fix missing references for you, suggesting fixes using the light bulb tool (https://msdn.microsoft.com/en-us/library/dn872466.aspx)

Avatar of BrianBrian🇺🇸

ASKER

Yes, I added that to the top of the Controller. Still getting same missing reference or assembly reference.

Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WmiWebApp.Models
{
    public class wmi
    {
        public class VolumeData
        {
            public string DriveLetter { get; set; }
            public long Size { get; set; }
            public long SizeRemaining { get; set; }
        }
        public class DiskData
        {
            public string DeviceId { get; set; }
            public string Model { get; set; }
            public string SerialNumber { get; set; }
        }
        public class StorageData
        {
            public List<VolumeData> Volumes { get; set; }
            public List<DiskData> Disks { get; set; }
        }
    }
}

Open in new window


Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Management;
using System.Management.Instrumentation;
using System.Text;
using System.Threading;


namespace WmiWebApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            // Use the Storage management scope
            ManagementScope scope = new ManagementScope(@"\\localhost\ROOT\Microsoft\Windows\Storage");
            // Define the query for volumes
            ObjectQuery query = new ObjectQuery("SELECT * FROM MSFT_Volume");

            // create the search for volumes
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            // Get the volumes
            ManagementObjectCollection allVolumes = searcher.Get();
            // Loop through all volumes
            var volumes = allVolumes
                .Cast<ManagementObject>()
                .Where(oneVolume => oneVolume["DriveLetter"].ToString()[0] > ' ')
                .Select(oneVolume => new VolumeData
                {
                    DriveLetter = oneVolume["DriveLetter"].ToString(),
                    Size = Convert.ToInt64(oneVolume["Size"]),
                    SizeRemaining = Convert.ToInt64(oneVolume["SizeRemaining"])
                })
                .ToList();

            // Define the query for physical disks
            query = new ObjectQuery("SELECT * FROM MSFT_PhysicalDisk");

            // create the search for physical disks
            searcher = new ManagementObjectSearcher(scope, query);

            // Get the physical disks
            ManagementObjectCollection allPDisks = searcher.Get();
            var disks = allPDisks
                .Cast<ManagementObject>()
                .Select(onePDisk => new DiskData
                {
                    DeviceId = onePDisk["DeviceId"].ToString(),
                    Model = onePDisk["Model"]?.ToString(),
                    SerialNumber = onePDisk["SerialNumber"]?.ToString()
                })
                .ToList();

            var model = new StorageData
            {
                Volumes = volumes,
                Disks = disks
            };

            return View(model);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

Open in new window


Avatar of Mlanda TMlanda T🇿🇦

You need to add a reference to System.Management.dll to your project.

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of Mlanda TMlanda T🇿🇦

To add a reference in Visual Basic
  1. In Solution Explorer, double-click the My Project node for the project.
  2. In the Project Designer, click the References tab.
  3. Click the Add button to open the Add Reference dialog box.
  4. In the Add Reference dialog box, select the tab indicating the type of component you want to reference.
  5. Select the components you want to reference, and then click OK.
To add a reference in Visual C#
  1. In Solution Explorer, right-click the project node and click Add Reference.
  2. In the Add Reference dialog box, select the tab indicating the type of component you want to reference.
  3. Select the components you want to reference, and then click OK.

Avatar of BrianBrian🇺🇸

ASKER

Ok, thanks MlandaT, those nasty red lines went away. Were can I look to find more information on how to query and retrieve data related to the Computer and OS? I use PowerShell now with the following classes below. Not sure if I can get the same information or not assuming the user is using Windows OS. Also, no big deal but when I ran the code I get the error:

.Where(oneVolume => oneVolume["DriveLetter"].ToString()[0] > ' ')

System.NullReferenceException occurred
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>


Get-WmiObject -Class Win32_BIOS
Get-WmiObject -Class Win32_Processor
Get-WmiObject -Class Win32_OperatingSystem
Get-WmiObject -Class Win32_ComputerSystem
Get-WmiObject -Class SoftwareLicensingService

Avatar of Mlanda TMlanda T🇿🇦

You should be able to get the same classes and properties as you got with Powershell. PowerShell or C# will just be different ways of getting to the same WMI netabase.

Not sure why you get the error on the Where. Try adding a check for null...

.Where(oneVolume => oneVolume["DriveLetter"] != null && oneVolume["DriveLetter"].ToString()[0] > ' ')

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of BrianBrian🇺🇸

ASKER

I added what you mentioned above and it worked :)

Is there a link that you can provide that can give me all the classess and methods that I can use the get WMI data that I need?

Avatar of BrianBrian🇺🇸

ASKER

Thank you MlandaT, I'm sorry it took this long to get back.
ASP.NET

ASP.NET

--

Questions

--

Followers

Top Experts

The successor to Active Server Pages, ASP.NET websites utilize the .NET framework to produce dynamic, data and content-driven web applications and services. ASP.NET code can be written using any .NET supported language. As of 2009, ASP.NET can also apply the Model-View-Controller (MVC) pattern to web applications