Is there a way to find out if rabbitmq is installed on the machine?
Either a command line or powershell script or something in C# because I am trying to check it in my c# code.
I searched for it and found only this one, but it did not help much for my case
Verify version of rabbitmq
EDIT
Just found this code snippet in one of the answers of the above post, but not sure it is the right way
public string GetRabbitMqVersion()
{
string prefix = "rabbitmq_server-";
var dirs = System.IO.Directory.EnumerateDirectories(#"C:\Program Files (x86)\RabbitMQ Server", string.Format("{0}*",prefix));
foreach (var dir in dirs)
{
//Just grab the text after 'rabbitmq_server-' and return the first item found
var i = dir.LastIndexOf(prefix);
return dir.Substring(i+16);
}
return "Unknown";
}
As the documentation says you should have a directory with the file rabbitmqctl.bat
The file should be placed on C:\Program Files\RabbitMQ\rabbitmq_server-x.x.x\sbin\
Then you can run any command in a cmd like this rabbitmq-service.bat status
https://www.rabbitmq.com/install-windows-manual.html
A list of installed software is available. What is the name of the RabbitMQ app in this list? Once this is known, it is easy to identify.
powershell -NoLogo -NoProfile -Command ^
"Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |" ^
"Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |" ^
"Sort-Object -Property DisplayName"
Related
I was looking for the answer at least 3 hours, but without success.
Everywhere are just pieces of code and I have no idea how to connect them together.
What I want to achieve:
I am creating dotnet-tool in which I need to process current working directory (value which is printed using pwd command in PS).
Dotnet tool will be installed in default directory C:\Users\Samuel\.dotnet\.store\myTool... but command can be invoked in any directory in PS using dotnet tool run myTool.
For example:
In PS I am in: C:\Users\Samuel\AxisRepos> and I run dotnet tool run myTool
In this case I want to retrieve C:\Users\Samuel\AxisRepos in C# code to find out, in which directory command was invoked.
So simply put, I want to do something like this in my dotnet tool:
class Program
{
static void Main(string[] args)
{
var pwd = GetPwdFromPowerShell();
}
static string GetPwdFromPowerShell()
{
string pwd = "";
// Retrieve current working directory from PS in which dotnet tool was invoked
return pwd;
}
}
pwd is just an alias for Get-Location which shows the current directory...
From c# you can use the built-in .net class System.IO.Directory specifically the method GetCurrentDirectory
So just update your code to:
static string GetPwd()
{
return System.IO.Directory.GetCurrentDirectory();
}
And from powershell this will have the same results:
[System.IO.Directory]::GetCurrentDirectory()
If I create a file called "dir.exe" and run PowerShell command Get-Command dir -Type Application, I get and error because dir is not an application (although that file exists):
gcm : The term 'dir' 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.
At line:1 char:2
+ (gcm dir -Type Application)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (dir:String) [Get-Command], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand
Suggestion [3,General]: The command dir was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\dir". See "get-help about_Command_Precedence" for more details.
Notice the Suggestion at the bottom: Suggestion [3,General]: The command dir was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\dir". See "get-help about_Command_Precedence" for more details.
I'm trying to catch that suggestion in my C# code:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management.Automation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Helpers.Tests {
[TestClass]
public class PowerShellRunner_Tests {
[TestMethod]
public void GetCommand_Test() {
// create file called "dir.exe" to see how PowerShell handles
// "Get-Command dir -Type Application":
File.Create("dir.exe").Dispose();
using (PowerShell powerShell = PowerShell.Create()) {
powerShell.AddCommand("get-command")
.AddArgument("dir")
.AddParameter("Type", CommandTypes.Application.ToString());
// run "Get-Command dir -Type Application":
CommandInfo commandInfo = powerShell.Invoke<CommandInfo>().FirstOrDefault();
// get the error:
ErrorRecord error = powerShell.Streams.Error.FirstOrDefault();
// emit the "Suggestion":
Trace.WriteLine(error.ErrorDetails.RecommendedAction);
}
}
}
}
However error.ErrorDetails is null. How can I get that Suggestion?
(I'm trying to get the behavior of where.exe but without the hassle of running a whole process for that).
Given that the end goal is to emulate where.exe's behavior, try the following:
(Get-Command -Type Application .\dir, dir -ErrorAction Ignore).Path
Note the use of -Type Application to limit results to executables and exclude PowerShell-internal commands such as function and aliases.
This will look in the current directory first, as where.exe does.
Give a mere name such as dir, Get-Command doesn't look in the current directory, because PowerShell does not permit invoking executables located in the current directory by name only - for security reasons; using relative path .\, however, makes Get-Command find such an executable.
From cmd.exe, however - whose behavior where.exe assumes - invoking a current-directory-only dir.exe with just dir (by name only) works fine.
If the output is just one path, and that path is a file in the current directory, you can infer that the dir executable exists only in the current directory, which is the condition under which PowerShell emits the suggestion to use an explicit path on invocation.
$fullPaths = (Get-Command -Type Application .\dir, dir -ErrorAction Ignore).Path
$emitSuggestion = $fullPaths.Count -eq 1 -and
(Test-Path ('.\' + (Split-Path -Leaf $fullPaths[0]))
Note: Strictly speaking, you'd also to have rule out the case where the current directory just so happens be one that is listed in $env:PATH:
$env:PATH -split ';' -ne '' -notcontains (Split-Path -Parent $fullPaths[0])
You can report that to your C# code by writing a custom version of the suggestion to the error stream via Write-Error, or, preferably, to the warning stream, with Write-Warning.
To use the above commands via the PowerShell SDK, it's simplest to use the .AddScript() method; e.g.:
powerShell.AddScript("(Get-Command -Type Application .\dir, dir -ErrorAction Ignore).Path");
As for capturing or silencing PowerShell's suggestions:
Unfortunately, you cannot gain access to suggestions programmatically (written as of Windows PowerShell v5.1 / PowerShell Core 6.1.0):
Using the PowerShell SDK, as you do, involves the PowerShell default host, which fundamentally doesn't emit suggestions.
It is only the console host, as used in console (terminal) windows that emits suggestions, but even there suggestions are printed directly to the screen, bypassing PowerShell's system of output streams.
In short: Suggestions only show in console windows (terminals), and can only be viewed, not captured there.
A quick demonstration of the behavior of suggestions in a console window (assumes Windows, with a file named dir.exe in the current dir and not also in $env:PATH):
PS> & { try { Get-Command dir.exe } catch {} } *>$null
Suggestion [3,General]: The command dir.exe was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\dir.exe". See "get-help about_Command_Precedence" for more details.
As you can see, despite the attempt to suppress all output (*>$null), the suggestion still printed to the screen, which also implies that you cannot capture suggestions.
However, there is a way to silence suggestions, namely with -ErrorAction Ignore (PSv3+); by contrast, with -ErrorAction SilentlyContinue the suggestion still prints(!):
PS> & { try { Get-Command dir.exe -ErrorAction Ignore } catch {} } *>$null
# no output
I need to programmatically get the last author of a specific line in the Git history with C#.
I tried using libgit2sharp :
var repo = new LibGit2Sharp.Repository(gitRepositoryPath);
string relativePath = MakeRelativeSimple(filename);
var blameHunks = repo.Blame(relativePath);
// next : find the hunk which overlap the desired line number
But this is the equivalent of the command
git blame <file>
And in fact I need
git blame -w <file> (to ignore whitespace when comparing)
Libgit2sharp do not set the -w switch and don't provide any parameter/option to set it.
What are my options ? Do you know any other library compatible with the -w switch of the blame command ?
When I hit similar advanced scenarios where the git lib isn't cutting it, I just shell out using start process to the real git command line. It's not sexy, but it's mighty effective.
Maybe using NGIT library will help. That is direct (automatic) port of java JGIT library. Install via nuget package, then:
static void Main() {
var git = Git.Init().SetDirectory("C:\\MyGitRepo").Call();
string relativePath = "MyFolder/MyFile.cs";
var blameHunks = git.Blame().SetFilePath(relativePath).SetTextComparator(RawTextComparator.WS_IGNORE_ALL).Call();
blameHunks.ComputeAll();
var firstLineCommit = blameHunks.GetSourceCommit(0);
// next : find the hunk which overlap the desired line number
Console.ReadKey();
}
Note SetTextComparator(RawTextComparator.WS_IGNORE_ALL) part.
Unfortunately, libgit2sharp is too slow on extracting blames and using this feature is impractical in real scenarios. So, the best way I think is to employ a Powershell script to use the underlying superfast native git. And then redirect the result to your application.
git blame -l -e -c {commit-sha} -- "{file-path}" | where { $_ -match '(?<sha>\w{40})\s+\(<(?<email>[\w\.\-]+#[\w\-]+\.\w{2,3})>\s+(?<datetime>\d\d\d\d-\d\d-\d\d\s\d\d\:\d\d:\d\d\s-\d\d\d\d)\s+(?<lineNumber>\d+)\)\w*' } |
foreach { new-object PSObject –prop #{ Email = $matches['email'];lineNumber = $matches['lineNumber'];dateTime = $matches['dateTime'];Sha = $matches['sha']}}
I've tried to do my due diligence in searching before I post but I am having trouble with a space in a file path when launching a powershell script in a C# app. I have tried escaping quotes, using # pretty much anywhere, single quotes. What am I missing here?
This is how I am defining the path:
public string importMusicLocation = #"C:\Program Files\Automation Toolbox\Scripts\Music_Import.ps1";
Then I launch a powershell process and point to the path, previously I had this working just fine without spaces when pointing to the path on my Desktop, but now that I want to put the application in Program Files the powershell window only detects the path up to the space.
private void LaunchPshell(string script) {
string strCmdText = Path.Combine(Directory.GetCurrentDirectory(), script);
var process = System.Diagnostics.Process.Start(#"C:\windows\system32\windowspowershell\v1.0\powershell.exe", strCmdText);
process.WaitForExit();
}
Like 5 minutes after I posted this I realized I don't need to be combining a directory, I was going to delete this but I can post the solution in case anyone else needs it. The general syntax for powershell to launch a script is & 'C:\Program Files\Some Path':
public string importMusicLocation = #"& 'C:\Program Files\Automation Toolbox\Scripts\Music_Import.ps1'";
and
private void LaunchPshell(string script) {
var process = System.Diagnostics.Process.Start(#"C:\windows\system32\windowspowershell\v1.0\powershell.exe", script);
process.WaitForExit();
}
Try quoting your path value with double quotes like
string importMusicLocation = #"""C:\Program Files\Automation Toolbox\Scripts\Music_Import.ps1""";
So, PowerShell.exe utility will receive the argument as quoted string and the spacing issue shouldn't arise
"C:\Program Files\Automation Toolbox\Scripts\Music_Import.ps1"
I'm developing a test project in ASP.NET MVC, where Im using System.Management.Automation to execute some PowerShell cmdlets.
Some of the cmdlets are from the Azure Powershell module.
The code is working fine when I run it from Visual Studio. But when I Published the website to IIS the some cmdlets and these scripts don't work.
Example, see the comments before:
var shell = PowerShell.Create();
var script1 = "Get-AzureSubscription | Out-String"; // cant execute the cmdlet
var script2 = "C:\\inetpub\\wwwroot\\App1\\Scripts\\test.ps1"; //Cant execute the script.
var script3 = "Get-Date"; //Work fine
try
{
shell.Commands.AddScript(script); // here insert the script.
Collection<PSObject> results = shell.Invoke();
//Search for errors, if some error is found redirect to an Error page.
if (shell.Streams.Error.Count > 0)
{
foreach (ErrorRecord err in shell.Streams.Error)
{
string error = err.ToString();
TempData["pserror"] = error;
return RedirectToAction("Powershellerror");
}
}
else
if (results.Count > 0)
{
foreach (var psObject in results)
{
string result2 = psObject.ToString();
TempData["psoutput"] = result2;
return RedirectToAction("PowershellOutput");
}
}
Both, script1 and script2 give this error:
The term 'C:\inetpub\wwwroot\App1\Scripts\test.ps1' 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.
and
The term 'Get-AzureSubscription' 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.
What could be??? Something is missing in the IIS setup?
You probably need to import the Azure module, try as suggested here:
https://stackoverflow.com/a/6267517/1183475
var ps = PowerShell.Create(myRS);
ps.Commands.AddCommand("Import-Module").AddArgument(#"g:\...\PowerDbg.psm1")
ps.Invoke()
I don't have the Azure PS tools installed on this machine, but the path should be:
"C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\Azure\Azure.psd1