Run PowerShell script from C# - c#

I have a requirement to run a PS file from C#. PS1 file content is $ADStatus=Test-ComputerSecureChannel -Server "xyz.com";.
When I run this PS file from C# I get the following error, however when running the same PS file from a PowerShell window it runs fine. What should I do?
System.Management.Automation.CommandNotFoundException , System.Management.Automation.CommandNotFoundException: The term 'Test-ComputerSecureChannel' is not recognized as a name of a cmdlet, function, script file, or executable program.
I am using package Microsoft.Powershell.SDK v7.1.5.
C# code:
using System.Management.Automation;
using (var ps = PowerShell.Create(string scriptFilePath))
{
var result = ps.Invoke();
var results = ps.AddScript(File.ReadAllText(scriptFilePath)).Invoke();
}

Related

Create Distribution group in Outlook using Microsoft Exchange Online with .Net

I am trying to create a distribution group in Outlook with the help of powershell module ExchangeOnlineManagement I was able to write out the script and it was working fine but When I try to create the same script using .Net and it is giving error
````
using(PowerShell ps = PowerShell.Create(runspace)){
SecureString credential = GetPassword();
ps.AddCommand("Import-Module").AddParameter("Name", "ExchangeOnlineManagement");
ps.Invoke();
ps.Commands.Clear();
ps.AddCommand("Connect-ExchangeOnline");
ps.AddParameter("Credential", credential);
Collection<PSObject> results = ps.Invoke();
}
```
I am getting the following error
Unhandled exception. System.Management.Automation.CommandNotFoundException: The term 'Connect-ExchangeOnline' is not recognized as the name of a cmdlet, function, script file, or operable program.
Can anyone help me with this ?

Getting exception while running PowerShell script in C# - The term 'xxxxxx' is not recognized as the name of a cmdlet, function, script file'

I'm running PowerShell script in C# code using this method.
PowerShell psExec1 = PowerShell.Create();
string script = File.ReadAllText(downloadPathScript1);
psExec1.AddScript(script);
Collection<PSObject> results2;
results2 = psExec1.Invoke();
In downloadPathScript1 I'm giving file path of .ps1 file Even after adding correct command or script I'm getting this exception.
The term 'Get-Item C:\Program Files\OneDriveLib.dll | Unblock-File' 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.
When I run same script in PowerShell it is working as expected. I'm trying to run this script/commands. What could be the cause of this exception?
Unblock-File -Path "C:\ODTool - Copy\OneDriveLib.dll"
Import-Module "C:\ODTool - Copy\OneDriveLib.dll"
$Status = Get-ODstatus -ByPath "C:\Users\OneDrive\Documents\Test.txt"

Executing Powershell Script Remotely - MSAccess not launching

I am trying to execute a Powershell script remotely that will launch an accdb file via MSAccess. I am able to get the Powershell script to execute successfully, but MSAccess is not launching since I know that the test.accdb file that I have is not getting updated. What am I missing in my code in order to be able to launch MSAccess? Or is it not possible?
My code is running in a Windows 2012 R2 environment in IIS and is being executed by a service account that has Admin privileges to the machine. If I run the code logged in as that service account, it works fine without issues. If I execute it remotely, only part of the code is executed
My code for the .NET app is as follows (running under service account). I've changed some of the private information, but it doesn't effect the code.
internal static HttpStatusCode ExecuteRemoteCommand()
{
WSManConnectionInfo connectioninfo = new WSManConnectionInfo();
connectioninfo.ComputerName = "testcomputer";
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectioninfo))
{
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
var re = ps.AddScript(#"\\testcomputer\test\StartTest.ps1");
var results = re.Invoke();
}
}
return HttpStatusCode.Created;
}
My Powershell code is as follows:
try {
$msAccess = "C:\Program Files (x86)\Microsoft Office\Office14\msaccess.exe"
$fileLocation = "C:\test\DBT.accdb"
Start-Process -FilePath $msAccess -ArgumentList $fileLocation -Verb RunAs -WindowStyle Hidden -WorkingDirectory "C:\test"
$today = Get-Date
"SUCCESS: " + $today > "c:\test\TestExecutionSuccess.txt"
}
Catch
{
$_.Exception.Message > "c:\test\TestExecutionError.txt"
}
In both cases, the one where I run the script locally and the one where I execute it remotely, the TestExecutionSuccess.txt file is created.
However, in ONLY the local test run is the DBT.accdb file updated.
So lets talk about the problems
1 : You can run the code and open Excel when you run the code under your User account logged in.
2 : You can run the code and open Excel when you run the code under your the service account logged in.
3 : you can you the code But Excel will not load if you are not logged into the user.
Why?
This is about Interactive flag. When you are logged into a user then you have can load up GUI's using COM. If you are not logged into a user then you can not load a GUI.
Here is a more indeepth explanation from
Microsoft Interactive User
With ArcSet's guidance, I think I was able to figure out what the issue was. His answer led me down the path of investigating which version of powershell was running. Turned out the C# code was running Powershell x64 instead of x86 (32-bit) version. The office installation is 32-bit and hence why I couldn't run MSAccess.
I couldn't figure out how to run x86 version of Powershell from the C# code, but what I did was put the launch of MSAccess into a batch file and then executed the batch file from my powershell code. Not super clean, but it worked. Access is now running properly.
Here is the batch file code:
cd "C:\Program Files (x86)\Microsoft Office\Office14"
MSACCESS.EXE C:\test\DBT.accdb
and the new version of the PowerShell script:
try {
$msAccess = "C:\Program Files (x86)\Microsoft Office\Office14\msaccess.exe"
$fileLocation = "C:\test\executeTest.bat"
cmd.exe /c $fileLocation
$today = Get-Date
"SUCCESS: " + $today > "c:\test\TestExecutionSuccess.txt"
}
Catch
{
$_.Exception.Message > "c:\test\TestExecutionError.txt"
}

Run powershell command from C# application

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

Running Powershell "IEX" from C#

I am trying to automate the running of a powershell script along with the running of other programs.
To run the powershell script manually, I would normally do this in a command prompt:
powershell "IEX (New-Object Net.WebClient).DownloadString('http://serverurl/Script.ps1'); Invoke-Method"
I can't seem to replicate this in c# to save my life using built in "PowerShell" commands. I"d rather NOT have to use things like "Process", so any advice would be helpful.
Since System.Net.WebClient is a .NET class, you don't need PowerShell to use it:
string script = (new System.Net.WebClient()).DownloadString('http://serverurl/Script.ps1');
To execute the script, use the System.Management.Automation.PowerShell class:
using System.Management.Automation;
// ...
using(PowerShell ps = PowerShell.Create())
{
ps.AddScript(script).AddScript("Invoke-Method");
ps.Invoke();
}

Categories

Resources