Get CPU use/temp using PowerShell and the lib OpenHardwareMonitorLib - c#

I have compiled the source of openhardwaremonitor (C#) it generates a DLL OpenHardwareMonitorLib.dll
Using the PowerShell script below, I was able to get my CPU temp, would like to ask for help in also getting CPU use, RAM use/ RAM left, and if possible GPU temp
Add-Type -Path .\OpenHardwareMonitorLib.dll
$cmptr = New-Object -TypeName OpenHardwareMonitor.Hardware.Computer
$cmptr.CPUEnabled= 1;
$cmptr.Open();
foreach ($hardwareItem in $cmptr.Hardware)
{
if($hardwareItem.HardwareType -eq [OpenHardwareMonitor.Hardware.HardwareType]::CPU){
$hardwareItem.Update()
foreach ($sensor in $hardwareItem.Sensors)
{
if ($sensor.SensorType -eq [OpenHardwareMonitor.Hardware.SensorType]::Temperature)
{
Write-Output $sensor.Name
Write-Output $sensor.Value.ToString()
}
}
}
}
$cmptr.Close();

Related

How to compile C# / VB code with string interpolation using PowerShell?

I'm on Windows 10.0.18363.959 with PowerShell 5.1.18362.752
When trying to compile a C# or VB.NET code within PowerShell like this:
$Source = #'
Imports Microsoft.VisualBasic
Imports System
Public NotInheritable Class MainClass
Public Shared Sub Main()
Console.WriteLine($"{True}")
End Sub
End Class
'#
$vbType = Add-Type -TypeDefinition $Source `
-CodeDomProvider (New-Object Microsoft.VisualBasic.VBCodeProvider) `
-PassThru `
-ReferencedAssemblies "Microsoft.VisualBasic.dll", `
"System.dll" `
| where { $_.IsPublic }
[MainClass]::Main()
$Console = [System.Console]
$Console::WriteLine("Press any key to exit...")
$Console::ReadKey($true)
Exit(0)
I get a compiler error because the '$' character used for string interpolation:
C:\Users\Administrador\AppData\Local\Temp\oshdpbp1\oshdpbp1.0.vb(12) : >>> Console.WriteLine($"{1}")
I'm aware that I could use String.Format() function instead, but I would like to know whether this issue can be solved without modifying the original VB.NET code (which of course it compiles right on Visual Studio).
Note that string interpolation was added in VB14. Maybe I'm missing how to specify the right VB compiler version, I don't have idea how to do so with PowerShell.
The VBCodeProvider has a constructor with an IDictionary parameter which allows you to specify the compiler version.
This could work, but I can't test it right now:
$provOptions = [System.Collections.Generic.Dictionary[string,string]]::new()
$provOptions['CompilerVersion'] = 'v14.0'
$vbType = Add-Type -TypeDefinition $Source `
-CodeDomProvider (New-Object Microsoft.VisualBasic.VBCodeProvider $provOptions) `
-PassThru `
-ReferencedAssemblies "Microsoft.VisualBasic.dll", `
"System.dll" `
| where { $_.IsPublic }

How can i get a Windows.System.User in PowerShell that I can use with the GetForUser() method of Windows.UI.Notifications.ToastNotificationManager?

I have been creating a powershell script to display toast notifications, this code works but there is one method on the toastnotification object I dont understand how to use:
$Load = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
$Load = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($App).Show($ToastXml)
Looking at the [Windows.UI.Notifications.ToastNotificationManager] object there is one method named "GetForUser()"
https://learn.microsoft.com/en-us/uwp/api/windows.ui.notifications.toastnotificationmanager.getforuser?view=winrt-19041
This method needs a Windows.System.User object as input.
https://learn.microsoft.com/en-us/uwp/api/windows.system.user?view=winrt-19041
I have tried the following code
$Load = [Windows.System.User, Windows.System, ContentType = WindowsRuntime]
$users = [Windows.System.User]::FindAllAsync()
$users is then a "System.__ComObject" without any methods.
So the question is, how can i get a Windows.System.User in PowerShell that I can use with the GetForUser() method of Windows.UI.Notifications.ToastNotificationManager?
I have also tried managed code
$code = #"
using Windows.System;
namespace CUser
{
public static class GetUsers{
public static void Main(){
IReadOnlyList<User> users = await User.FindAllAsync(UserType.LocalUser, UserAuthenticationStatus.LocallyAuthenticated);
User user = users.FirstOrDefault();
}
}
}
"#
Add-Type -TypeDefinition $code -Language CSharp
But that gives the error:
"The type or namespace name 'System' does not exist in the namespace 'Windows' (are
you missing an assembly reference?)"
I am not sure what assembly or dll contains the "Windows.System" reference.
I was searching for a similar problem with DeviceInformation and ran across your question. The solution turned out to be in this blog post https://fleexlab.blogspot.com/2018/02/using-winrts-iasyncoperation-in.html
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
Function Await($WinRtTask, $ResultType) {
$asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
$netTask = $asTask.Invoke($null, #($WinRtTask))
$netTask.Wait(-1) | Out-Null
$netTask.Result
}
You can then run FindAllAsync() like this
$windowsSystemUserClass = [Windows.System.User, Windows.System, ContentType = WindowsRuntime]
$users = Await ([Windows.System.User]::FindAllAsync()) ([System.Collections.Generic.IReadOnlyList`1[Windows.System.User]])

Powershell [WMI] type methods

using WMI with PowerShell I found something I don't understand:
gwmi -class MIIS_ManagementAgent -namespace "root/MicrosoftIdentityIntegrationServer" | foreach
If ($_.Name -eq "contoso.com") {
$foo= $_
}
else {
$boo= $_
}
}
$state= $foo.ResumeState("FullSync")
$res = $foo.execute("FullSync")
$details = $foo.RunDetails()
$RunStatus = $foo.RunStatus()
I know that $foo contains [WMI] type accelerator but I cannot find any documentation of what are the methods of this type. I have no idea what ResumeState, execute, RunDetails and RunStatus methods are doing. I want to transfer this calls to C# but I have to understand what those calls are.

Using PowerShell in nuget package to edit Global.asax

Using a Install.ps1 script with a Nuget Package, I'm attempting to add code to the Global.asax.cs file for customization purposes. With my Install.ps1 script the -replace command is not working. Infact I'm not able to assign any text to the variable $a I'm using with -replace and have it written to the "Global.asax.cs" file. The 3 lines of script involving -replace and the clipboard do work with "Windows PowerShell" outside of nuget. I know that the variable $a is passing along content from the clipboard since commenting out "#$customGlobalAsax.Document.Selection.Copy()" will write whatever happens to be in the clipboard into the Global.asax.cs file.
Any Suggestions? Thanks.
param($installPath, $toolsPath, $package, $project)
$customGlobalAsax = $project.ProjectItems | ForEach-Object { $_.ProjectItems } | where { $_.Name -eq "Global.asax.cs" }
$customGlobalAsax.Open()
$customGlobalAsax.Document.Activate()
$customGlobalAsax.Document.Selection.SelectAll()
$customGlobalAsax.Document.Selection.Copy()
$a = [System.Windows.Forms.Clipboard]::GetText()
$a = $a -replace "using Company.Web.Mvc.ViewBase;","using Company.Web.Mvc.ViewBase;`r`nusing Company.Web.Address;"
[System.Windows.Forms.Clipboard]::SetText($a)
$customGlobalAsax.Document.Selection.Delete()
$customGlobalAsax.Document.Selection.Paste()
from what I can see, there is some problem with this line since it will return nothing:
$customGlobalAsax = $project.ProjectItems | ForEach-Object { $_.ProjectItems } | where { $_.Name -eq "Global.asax.cs" }
The following is my test:
$directory = dir *
$directory | foreach {$_.name}
The above run successfully.
But the following returns nothing:
$directory = dir *
$directory.name | foreach {$_.name}
I believe in the latter case $_.name represents $directory.name.name which doesn't exist.
So it seems like this line in your script
$customGlobalAsax = $project.ProjectItems | ForEach-Object { $_.ProjectItems } | where { $_.Name -eq "Global.asax.cs" }
should be changed to:
$customGlobalAsax = $project | ForEach-Object { $_.ProjectItems } | where { $_.Name -eq "Global.asax.cs" }

could not able to copy the proxy file using vs2008 powershell

Hi I have written new functionality in the existing webservice.
I am copying the proxy file when rebuilding and copying to the specific location
i am using powershell but its not working .i get the following error.
**The term 'wsdl.exe' is not recognized as the name of a cmdlet, function, script
file, or operable program. Check the spelling of the name, or if a path was in
cluded, verify that the path is correct and try again.
At C:\[path edited for security]\RebuildProxy.ps1:30 char:9
+ wsdl.exe <<<< /fields "/l:CS" "/n:$namespace" "/out:$outCSFile" "/urlkey:Tes
tEndpoint" "$wsdlUrl";
+ CategoryInfo : ObjectNotFound: (wsdl.exe:String) [], CommandNot
FoundException
+ FullyQualifiedErrorId : CommandNotFoundException**
After rebuild i get the message the file has been modified outside the source editor[ the generated proxy file already there in the location]
could you please help me on this
posted below the powershell code
param (
[string]$webServiceProjFile = $(throw "webServiceProjFile paramter is required." ),
[string]$serviceFile = $(throw "serviceFile parameter is required."),
[string]$outCSFile = $(throw "outCSFile paramter is required." )
)
if (! [IO.File]::Exists($webServiceProjFile))
{
throw "$webServiceProjFile note found.";
}
if (! [IO.File]::Exists($outCSFile))
{
throw "$outCSFile note found.";
}
# read the project file into an XML document.
$projectFileXml = [xml] (Get-Content $webServiceProjFile );
# access the configured IIS URL
$serviceWsdlUrl = [string]::Concat($projectFileXml.Project.ProjectExtensions.VisualStudio.FlavorProperties.WebProjectProperties.IISUrl.Trim(), '/', $serviceFile);
$namespace = "";
# Read the namespace for the proxy from the proxy C# file
Get-Content $outCSFile | ForEach-Object { if ($_ -match "^\s*namespace\s+([A-Za-z._]+)\s+{\s*$") { $namespace = $matches[1] }};
$wsdlUrl = [string]::Concat("$serviceWsdlUrl", '?wsdl');
# Regenerate the proxy using WSDL.exe
wsdl.exe /fields "/l:CS" "/n:$namespace" "/out:$outCSFile" "/urlkey:TestEndpoint" "$wsdlUrl";
# Update the generated C# file so the proxy class interits from WSE2 base class.
(Get-Content $outCSFile) |
ForEach-Object { $_ -replace "\s+\:\s+System\.Web\.Services\.Protocols\.SoapHttpClientProtocol", " : Microsoft.Web.Services2.WebServicesClientProtocol" } |
Set-Content $outCSFile ;
$projectDirectory = [IO.Path]::GetDirectoryName($outCSFile);
$appConfigFilePath = [IO.Path]::Combine($projectDirectory, "App.config");
(Get-Content $appConfigFilePath) |
ForEach-Object { $_ -replace '<add\s+key="TestEndpoint"\s+value="[^"]*"\s+/>', "<add key=""TestEndpoint"" value=""$serviceWsdlUrl"" />" } |
Set-Content $appConfigFilePath ;
WSDL.EXE is not in the path. On my computer it comes with the visual studio.
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\x64\wsdl.exe

Categories