Why does this LINQPad Util.Cmd() call fail? - c#

I'm trying to execute the Windows find command from LINQPad but it isn't working and I don't understand why. This is my LINQPad script and I'm executing it in LINQPad as C# Statement(s).
string find = #"find ""Processing request to "" ""Y:\Services\DynaMiX.Services.DatabaseMaintenance\*.log""";
find.Dump("find");
var results = Util.Cmd(find);
results.Dump();
The find.Dump("find") statement displays the following as expected.
find "Processing request to " "Y:\Services\SteveC.Services.DatabaseMaintenance\*.log"
When I copy that and paste it in a CMD window it executes the find as it should but when running the script in LINQPad it throws CommandExecutionException with the ErrorText FIND: Parameter format not correct.
Can anyone shed any light on why this might happen?

Turns out to be an incorrect use of Util.Cmd on my part. Instead of Util.Cmd(string commandText) I needed to use the Util.Cmd(string commandText, string args) overload. The following statement works.
var results = Util.Cmd("find", #"""Processing request to "" ""Y:\Services\SteveC.Services.DatabaseMaintenance\*.log""");

Related

Cannot process command because of one or more missing mandatory parameters: Identity

I'm getting a, possibly misleading, error when i try to execute powershell from my c# app using powershell.
The error, as in the title, suggests that i'm missing the Identity parameter, but it isn't missing.
I tried debugging through, and confirming that the parameter is added to the Command object, before invoking.
var x = ps.AddScript("Remove-CsOnlineVoiceRoutingPolicy")
.AddParameter("Identity", "DK")
.AddParameter("-Force");
x.Invoke();
I'm running powershell 7.2, and using System.Management.Automation.Powershell version 7.2.1.0
Any ideas as to why this happens ?
I've tried both parameters with and without the dash, making no difference.
The error was using AddScript in addition with addParameter.
When using add scripts the params should be inline in the script, if you want to use addPArameter, it should be following the AddCommand.
dashes in the parameter name in AddParameter() seems to be completely ignored.
a working example would look like this.
var x = ps.AddCommand"Remove-CsOnlineVoiceRoutingPolicy")
.AddParameter("Identity", "DK")
.AddParameter("Force");
x.Invoke();

PowerShell Invoke to get CPU usage

Really frustrating because it seems to be so close to solution but can't get the last piece working.
I need to get CPU usage using C#. PerformanceCounter is out the question because it takes forever to load the first time. So trying to use PowerShell (System.Management.Automation.dll) to execute what looks like a simple line:
(Get-CimInstance Win32_Processor).LoadPercentage
This is C#:
var cpuUsage = powerShell.AddCommand("Get-CimInstance").AddArgument("Win32_Processor").AddCommand("LoadPercentage").Invoke();
So you can see I'm trying to pipe LoadPercentage command but it won't work.
System.Management.Automation.CommandNotFoundException: 'The term
'LoadPercentage' 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 included, verify that the path is correct and try
again.'
The rest of code works.
Can anyone please spot the issue here?
Thank you in advance!
The issue here is that LoadPercentage is a property of the object, not a command. If you capture the result of the command and iterate through it's members, you should find what you're looking for:
var results = PowerShell.Create()
.AddCommand("Get-CimInstance")
.AddArgument("Win32_Processor")
.Invoke();
foreach (var result in results)
{
Console.WriteLine(result.Members["LoadPercentage"]?.Value);
}

Running a powershell script from C# ends in error

I want to trigger a site design from powershell. It works here but when I try to run it through c# I get this error:
Cannot convert value "param" to type
"Microsoft.Online.SharePoint.PowerShell.SPOSiteDesignPipeBind". Error:
"Guid should contain 32 digits with 4 dashes
(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
I have tested several versions of the addScript string but none have worked. This is the code I'm trying to run. And it works fine in powershell.
PowerShellInstance.AddScript("Invoke-SPOSiteDesign -Identity param($paramSiteDesignId) -WebUrl param($paramUrl)");
PowerShellInstance.AddParameter("paramSiteDesignId", "176d2af0-1772-41b2-9ad7-acfceefc8851");
PowerShellInstance.AddParameter("paramUrl", "https://TenantName.sharepoint.com/sites/TMVTest13");
Any help pointing me in the right direction is very appreciated.
I found a way doing it directly in C# with Tenant.ApplySiteDesign. It works great see link for more info https://laurakokkarinen.com/the-ultimate-guide-to-sharepoint-site-designs-and-site-scripts/#applying-site-designs-programmatically
As you can see on learn.microsoft.com, AddParameter doesn't work by replacing placeholders the way you are doing it, but instead works by adding parameter/value pairs to the given command as parameters.
Your code probably results in something like this:
Invoke-SPOSiteDesign -Identity param($paramSiteDesignId) -WebUrl param($paramUrl) -paramSiteDesignId 176d2af0-1772-41b2-9ad7-acfceefc8851 -paramUrl https://TenantName.sharepoint.com/sites/TMVTest13
According to the documentation, this should do what you want:
PowerShellInstance = PowerShellInstance.AddScript("Invoke-SPOSiteDesign");
PowerShellInstance = PowerShellInstance.AddParameter("Identity", "176d2af0-1772-41b2-9ad7-acfceefc8851");
PowerShellInstance = PowerShellInstance.AddParameter("WebUrl", "https://TenantName.sharepoint.com/sites/TMVTest13");```

c# Provide packet source in pcap.net

I am following Pcap.net tutorials from its wiki on github. I tried to run code from here:
https://github.com/PcapDotNet/Pcap.Net/wiki/Pcap.Net-Tutorial-Handling-offline-dump-files
I didn't understand the following part:
if (args.Length != 1)
{
Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
return;
}
But I run this code and Bingo, nothings happen (no output).
I tried to figure out and found that args has the value "0".
I comment return command and it start working fine till I got IndexOutOfBound exception here:
using (PacketDumpFile dumpFile = communicator.OpenDump(args[0]))
Did I missed any thing?
This program require 1 argument (i.e. 'filename'in this case) that you should pass through command line.
Compile the code and run the program through command line with argument value.
For Example:
In CLI >MyProg.exe fileNmae

Calling a Python script from C# - changing the script's filepath causes the program to not work

The following code works perfectly without flaw:
public partial class MainForm : Form
{
string pyInterp = File.ReadAllText(Directory.GetCurrentDirectory() + #"\config\pathToPythonInterpreter.txt");
string pyWeather = #"C:\getWeather.py";
public MainForm()
{
InitializeComponent();
UpdateWeather();
}
public void UpdateWeather()
{
labelWeather.Text = PySharp.ExecutePy(pyInterp, pyWeather);
}
}
However, when I change the path to getWeather.py to not be in an arbitrary random location, like this:
string pyWeather = Directory.GetCurrentDirectory() + #"\scripts\getWeather.py";
Then my program no longer obtains the script's output. The script still works: I launched it using IDLE and it completed its function properly. When I call it using C#, the console opens, yet no output is obtained.
The Python script is the following:
from requests import get
from bs4 import BeautifulSoup as soup
r = get("http://www.ilmateenistus.ee/ilm/prognoosid/4-oopaeva-prognoos/")
parsed = soup(r.content, "html.parser")
container = parsed.find("div",{"class":"point kuusiku"})
print(str(container["data-title"]))
(It webscrapes my local weather)
PySharp.ExecutePy() can be viewed here
By far the strangest bug I've ever encountered. Any ideas?
EDIT 1: It seems that C# is indeed reading something from the script. It just appears that this something is.. nothing. I gave the label a default sample text, and after running the program, the label's text is simply changed to an empty string. Hope this incredible discovery helps somehow.
EDIT 2: The program fails to call the script correctly when its filepath contains spaces. For example:
C:\foo bar\testing\pyWeather.py
does not work!
Try surrounding the path that contains spaces with 2 double quotes.
For e.g.
string pyWeather = #"""C:\Users\[myname]\Documents\Visual Studio 2017\Projects\testing\testing\scripts\getWeather.py""";
Similarly, you can do string pyWeather = Directory.GetCurrentDirectory() + #"\scripts\getWeather.py"; followed by pyWeather = "\"" + pyWeather + "\"";.
I would want you to return the answer instead of printing. Printer is an I/O based solution to display. So it will work super fine with IDLE however it may not return results as you expected. I strongly believe this will solve your problem.
instead of printing please try return. I can give more support after trying this.
return(str(container["data-title"]))

Categories

Resources