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.
Related
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();
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]])
So I am aware that in general, this is not possible because Jon Skeet said so.
But my .cs files are simple classes with one or two usings at the top. And I need one file with all the classes in it so I can paste it into a web browser IDE as a single file to compile and run.
I tried using PowerShell, and just copy all files into one like this:
get-content *.cs | out-file bigBadFile.cs
But this file will not compile because it has usings in the middle, which isn't allowed:
CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations
If you are curious why I need that - it's for the CodinGame platform, and I'm sick of keeping all my code in a single file.
Sample files to merge:
GameData.cs:
using System.Collections.Generic;
public class GameData
{
public GameData(int width, int height)
{
...
}
public int Width { get; set; }
public int Height { get; set; }
public List<int> List { get; set; }
...
}
Player.cs:
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
public class Player
{
private static string[] inputs;
private static bool isFirstTurn = true;
public static StringBuilder MoveBuilder;
public static GameData Game;
static void Main()
{
...
}
}
Just to offer a more concise and faster PSv4+ alternative to your own helpful answer:
$usings, $rest = (Get-Content *.cs).Where({ $_ -match '^\s*using\s' }, 'Split')
# Encoding note: Creates a BOM-less UTF-8 file in PowerShell [Core] 6+,
# and an ANSI file in Windows PowerShell. Use -Encoding as needed.
Set-Content bigBadFile.txt -Value (#($usings | Select-Object -Unique) + $rest)
Finally I managed to do this. Those PowerShell commands worked for me:
get-content *.cs | where { $_ -match "^using" } | Select-Object -Unique | out-file bigBadFile.txt
get-content *.cs | where { $_ -notmatch "^using" } | out-file -append bigBadFile.txt
So what I do here is I take all the usings from all files and put them into bigBadFile.txt. Then I take all code without usings from all files, and append it to the bigBadFile.txt
The result is working for me, even though it has duplicated using statements. I've added | Select-Object -Unique as Theo suggested in his comment to avoid usings duplication.
After -match the code inside braces "^using" is just a regular expression, so if your usings have spaces before them in .cs files (which is unusual, you can just change this to "^[ ]*using".
This is a project doing specifically what you need:
https://github.com/nima-ghomri/SingleCS
Just add your cs files as arguments and it combines all of them:
SingleCS.exe "MyProject\**\*.cs" "D:\Helpers\Utils.cs"
Download:
https://github.com/nima-ghomri/SingleCS/releases/latest
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" }
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