EDIT: posted too soon, I figured it out. The ManagementObjectSearcher was looking at Win32_DiskDrive, where the PS command is looking at Win32_Volume. Updated that and made some tweaks so it will only show me drives with a drive letter, and to exclude the boot drive.
Not sure why my runspace hated the initial command, but this does what I need. If someone comes across this later and needs it:
ManagementObjectSearcher mgmtObjSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Volume");
ManagementObjectCollection colDisks = mgmtObjSearcher.Get();
foreach (ManagementObject objDisk in colDisks)
{
if (objDisk["Name"].ToString().ToLower().Contains("volume") == false && objDisk["BootVolume"].ToString().ToLower() == "false")
{
MessageBox.Show("Name: " + objDisk["Name"].ToString() + "\nSerial: " + objDisk["SerialNumber"].ToString());
}
}
Trying to utilize a PowerShell runspace on a Windows Form to get the output of "Get-WmiObject -Class Win32_Volume", however, the runspace returns nothing when running that command. That same command in PS outputs a lot of information so I know that part is working, when changing the command on my Windows Form to "ipconfig" it gives me all of that command just fine so I know that part is working. Not sure what I'm doing wrong, or if this command hates C# runspaces?
My code:
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
PowerShell powerShell = PowerShell.Create();
powerShell.Runspace = runspace;
powerShell.AddScript("Get-WmiObject -Class Win32_Volume | select Name, SerialNumber");
Collection<PSObject> results = powerShell.Invoke();
MessageBox.Show(results.Count.ToString());
foreach (PSObject result in results)
{
MessageBox.Show(result.ToString());
}
runspace.Close();
Also have tried looking around online for other ways people are doing it, however, the methods I've found online all return a different serial number than the one in the above command or return nothing at all. For example, the below outputs no serial number at all, just a blank message box
ManagementObjectSearcher theSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");
foreach (ManagementObject currentObject in theSearcher.Get())
{
ManagementObject theSerialNumberObjectQuery = new ManagementObject("Win32_PhysicalMedia.Tag='" + currentObject["DeviceID"] + "'");
MessageBox.Show(theSerialNumberObjectQuery["SerialNumber"].ToString());
}
Trying it the way below returns the below error:
Code:
powerShell.AddCommand("get-wmiobject").AddParameter("Class", "Win32_Volume");
Error:
The term 'get-wmiobject' is not recognized as a name of a cmdlet, function, script file, or executable program.
Also have tried the original code with just "Get-WmiObject" by itself, and ended up with the same result it is just blank. What am I doing wrong?