I would like to run the following powershell commands from my C# application:
Enter-PSSession –ComputerName fedsrv01.domain.local
Start-ADSyncSyncCycle -PolicyType Delta
I found some information on the Powershell Class but struggling to achieve what I want due to my lack of experience.
https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.powershell?redirectedfrom=MSDN&view=pscore-6.2.0
This is what I have so far:
I have added the assembly and referenced system.management.automation
using (var powershell = PowerShell.Create())
{
//powershell.AddCommand("get-process");
powershell.AddCommand("Enter-PSSession -ComputerName fedsrv01.domain.local");
powershell.Invoke();
}
I get an error saying, 'The term 'Enter-PSSession -ComputerName fedsrv01.domain.local' is not recognized as the name of a cmdlet, function, script file, or operable program.
if I use: powershell.AddCommand("get-process") it executes fine.
If I launch Powershell on the same PC and enter, Enter-PSSession -ComputerName fedsrv01.domain.local it works fine.
Any assistance would be much appreciated.
Cheers,
Jono
Try compiling your application as x64. If it is compiled as x86 platform then it will be using the virtualized System32 dir so the function you require may not exist.
Powershell commands from C# 'the term is not recognizes as cmdlet'
Ok, after more research into the PowerShell class I now realise that you have to add the parameters separately using the .addparameter method.
.addcommand is just for the PowerShell commands. It now makes sense why I got the error saying the command could not be found. It was assuming the entire string was a command.
Problem solved!
Jono
Related
The problem is about sending command to Powershell,
My C# application sends commands one by one in order to get right directory to execute some files but even I downloaded all the necessary packages application throws an error
An exception of type 'System.Management.Automation.CommandNotFoundException' in 'cd C:\\Users\\User1\\Documents\\pathToFileforExecute\\ ' is not recognized as the name of a cmdlet, function, script file, or operable program.
My NuGet Packages ;
My code is like
ps.AddCommand("Set-ExecutionPolicy").AddParameter("ExecutionPolicy", "Unrestricted");
ps.Invoke();
ps.AddCommand("cd C:\\Users\\User1\\Documents\\pathToFileforExecute\\");
ps.AddCommand("./executeTheFile");
ps.AddCommand("pwd");
Collection<System.Management.Automation.PSObject> results = ps.Invoke();
Please help me to solve problem I found this feed but it didn't work for me https://github.com/PowerShell/PowerShell/issues/8119
I tried deleting the System.Management.Automation because I read this package shouldn't use by itself.
You are using AddCommand without the AddParameter option. The path is a parameter.
Try the following code:
ps.AddCommand("Set-Location").AddParameter("Path", C:\\Users\\User1\\Documents\\pathToFileforExecute\\);
Or you may use the AddScript method instead of AddCommand like in this post.
Note that the cd command is an alias for Set-Location in PowerShell.
I have an automation issue that I've tracked down to the following situation:
The PS script is being loaded via process.start in a C# program. If I run the script in the ISE, it runs fine. When running via process.start, it fails on the command:
Add-PSSnapin 'Microsoft.SharePoint.PowerShell'
With the error:
Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 4.
The command I'm using for process.start in .net is:
var Arguments #"-version 4.0 -ExecutionPolicy Bypass -noexit -file """ + filePath + #""" -XmlString """ + args + #""" -Verb RunAs"
var FileName = "powershell.exe"
var process = Process.Start(FileName, Arguments);
filePath is the path to the powershell script that is being executed.
This runs and attempts to run the script, but fails on the command shown above inside the script. The user account is the admin service account for the machine. The issue seems to be in how the .Net program is starting PowerShell, as I can run this script and these commands via the ISE and console if I do it manually (under the same service account). I just can't seem to find some combination of tricks to get the .Net program to be able to execute the PowerShell script under the correct profile, I guess.
Any thoughts?
PetSerAl's request was spot-on... when running the PowerShell script via the .Net program, it was running under x86, but when running it via ISE, it was running in x64. I re-compiled the .Net program against x64 and everything now works.
Thanks for the advice!
I am trying to use this azure commandlets form C# application that is console job hosted in my azure Virtual machine. this job runs more then once in a day automatically but my azure commandlets are fails to execute. yesterday that works fine but after a day it is not working please help me. ☺
Note : here i am doing some administration task and i am using organizational account. but it fails to add account other commandlets goes fail to work.
Install the Azure PowerShell tools. The download link is here: https://azure.microsoft.com/en-us/documentation/articles/powershell-install-configure/#how-to-install-azure-powershell
It's renamed to Add-AzureAccount.
I'm assuming that the original question was "The term 'Login-AzureRmAccount' is not recognized as the name of a cmdlet, function, script file. I'm seeing the same thing, despite "Install-Module AzureRM" having been done (from an elevated powershell prompt) and "Get-Module AzureRM" returning a version of 4.3.1 (i.e. powershell tools being installed).
The first part of the solution for me was to also do "Install-Module Azure" (from an elevated powershell prompt) as well after which "Add-AzureAccount" worked. However a command such as "New-AzureRmResourceGroup" still failed with "Run Login-AzureRmAccount to login".
The second part of the solution was simply to reboot, after which:
Add-AzureRmAccount
New-AzureRmResourceGroup -Name wibble -Location UKSouth
worked.
I am trying to use a custom snapin for powershell in my C# program. (The C# program is a modified version this)
I'm using the standard approach to setup the runspace:
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
If I run this as is and scriptText contains the command "Get-PSSnapin" my snapin is missing. If I run "Get-PSSnapin -Registered" then I can see my snapin. If I use Add-PSSnapin, then it returns nothing and followup commands that I issue (which are implemented in the snapin will return):
...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
So, I amended my code to add the cmdlet to the runconfig:
RunspaceConfiguration runConfig = RunspaceConfiguration.Create();
PSSnapInException psEx = null;
runConfig.AddPSSnapIn("mySnapin", out psEx);
Runspace runspace = RunspaceFactory.CreateRunspace(runConfig);
Now, when I run it, I get:
error in script : Cannot invoke this function because the current host
does not implement it.
I tried both the x86 and 64 version. The snapin gets installed in the x86 programs so I did this by compiling for x86. If I do the 64 version, I get:
"Error in script : The Windows PowerShell snap-in 'mySnapin' is not
installed on this machine".
Confirming that this is specific to x86.
I also tried loading this as a module (desperation), but it doesn't work that way either. When I run:
get-command <command in mySnapin> | select Module, PsSnapin
The output doesn't have a module, just the snapin, hence it was silly to begin with.
I should note that this is installed by another program and I have no control over where it is install. I thought that might be a factor, but since it shows up with -Register I think it is finding without issue.
Edit:
I also tried import-module <path to dll>. This doesn't output anything and subsequent calls to functions in my snapin yield:
error in script : Cannot invoke this function because the current
host does not implement it.
Then again in C# since I wasn't clear on whether the import will be preserved across calls.
pipeline.Commands.Add("Import-Module");
var command = pipeline.Commands[0];
command.Parameters.Add("Name", #"<path to my snapin .dll>");
Any help getting this rolling would be greatly appreciated. Thank you!
I have a Powershell script that starts a service on a remote machine.
It does something like this:
Invoke-Command -ComputerName $serverName -ScriptBlock { param($serviceexe) & $serviceexe -install }-ArgumentList $localExePath
It works OK in a local machine and also in Teamcity as a Build step.
But when I am trying to start the service from some other tool, I am getting the message:
"cannot start service from the command line or a debugger".
This other tool is written in C#, using System.Management.Automation.
I´ve also tried it using Process class, but still the same problem.
Any idea?
Have you considered Powershell Remote Requirements already?