I am using this function below to create powershell script
public static void joinDomain()
{
string path = #"C:\Windows\Temp\Test.ps1";
if(!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("add-computer –domainname ad.contoso.com -Credential AD\adminuser -restart –force");
}
}
}
After successfully script creation I run that script using this below code
Classes.Functions.joinDomain();
string strCmdText = #"C:\Windows\Temp\Test.ps1";
System.Diagnostics.Process.Start("C:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe ", strCmdText);
If i run script from Powershell ISE it prompts for password so the script works.
Even calling it works but i just got blue powershell commandline and then it disseaper it wont ask for password and i dont know why.
Any ideas would be appreciated?
Found solution:
It was cause by windows restricted policy for unsigned scripts.
Solution here:
https://github.com/eapowertools/ReactivateUsers/wiki/Changing-Execution-Signing-Policy-in-Powershell
Related
I'm trying to run powershell script from relative path (script is placed in project folder) with arguments.
This is what i tried:
public static void RunPSScriptWithArgumentsFromScriptsFolder(string NameOfScriptFile, string arguments)
{
string RelativePathToApp = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Process proc = Process.Start("C:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe ", #"-noexit -File """+RelativePathToApp+"\\Scripts\"" +NameOfScriptFile +arguments);
proc.WaitForExit();
}
Problem is when i run it my powershell window just flash once and disseapers even with -noexit switch.
This is script which im trying to run for better reproducing problem:
https://community.spiceworks.com/scripts/show/4378-windows-10-decrapifier-18xx-19xx
Any ideas what could be wrong?
PS: My Set-ExecutionPolicy is set to Unrestricted
I'm creating a simple C# program used to check various settings on windows 10 builds we're testing. I need to capture the output from a CMD or Powershell invoke and display the result as a string (human-readable). Specifically, I'm trying to capture the output from get-bitlockervolume to check if the drives are encrypted. The program should be able to run without using admin creds.
Get Powershell command's output when invoked through code
unfortunately doesn't quite seem to work, so I thought I'd attempt to capture the output to a txt file and read it from there, but for some reason, the txt ends up being empty. For my latest attempts, I've ditched PowerShell and attempted to get it done using simple CMD.
Process bl = new Process();
bl.StartInfo.WindowStyle = ProcessWindowStyle.Hidden ;
bl.StartInfo.FileName = "cmd.exe";
bl.StartInfo.Arguments = #"/c manage-bde -status > C:\windows\temp\bitlockerstatus.txt";
bl.StartInfo.RedirectStandardOutput = true;
bl.StartInfo.UseShellExecute = false;
bl.Start();
This seems to create the output file I was looking for in the right location, but it always turns up empty. When running the command directly from cmd, there doesn't seem to be an issue recording the output.
I'm still quite new to C#, self-learning as I go along, so any suggestions for an alternate method/way of doing this would be appreciated.
Very late edit:
I've figured out a way by using a Collection.
code:
StringBuilder str = new Stringbuilder();
using (Powershell ps = Powershell.create())
{
ps.addscript ("manage-bde -status");
Collection<PSObject> psoutp = ps.Invoke();
foreach(PSObject outp in psoutp)
{
if (outp != null)
{
str.Append(outp);
}
else str.Append ("Error");
}
return str.ToString();
}
This for a Method that returns the output of manage-bde - status from powershell back to main. If there's no output at all (not even an errormessage) , it'll simply return "error" back to main.
Here's hoping this helps someone else one day.
I think the answer is here:
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
// do something with line
}
I have tried executing RemoteDesktop commandlets in powershell using C#.
The following is my program :
static void Main(string[] args)
{
using (var powershell = PowerShell.Create())
{
powershell.Commands.AddCommand("Import-Module").AddArgument("remotedesktop");
powershell.Invoke();
powershell.Commands.Clear();
powershell.AddCommand(#"Get-RDRemoteApp");
powershell.AddCommand(#"out-string");
foreach (var result in powershell.Invoke())
{
Console.WriteLine(result);
}
}
}
When I invoke command it gives the error System.Management.Automation.CommandNotFoundException: The term 'Get-RDRemoteApp' is not recognized as the name of a cmdlet, function, script file, or operable program.
How can I achieve calling RemoteDesktop commandlets ?
I solved this. I change run mode to x64 from Any CPU.
You need to set a persistent runspace for all of your commands. The way your code is now, each command is being executed in it's own isolated runspace. Adding the following code:
var runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
powershell.Runspace = runspace;
to the beginning of the using block should fix your problem.
I faced the same issue and found your post.
Default InitialSessionState only loads Core commandlets and ExecutionPolicy is set to the most restrictive: Microsoft.PowerShell.ExecutionPolicy.Default.
To work around this, I had to set the ExecutionPolicy as shown below :
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
iss.ImportPSModule("RemoteDesktop");
PowerShell powershell = PowerShell.Create(iss);
...
I am trying to run a PowerShell script inside C# using .NET 4.6
I have tried to install the PowerShell NuGet but it doesn´t target .NET 4.6
Is there another way I could execute the PowerShell script?
I needed to specify powershell.exe to be able to run the script. But now I have another problem the PowerShell window closes immediately so I am not able to see the error message. I am using the following command
var s = Process.Start(#"Powershell.exe", $#"-noexit -ExecutionPolicy Bypass -file ""MyScript.ps1; MyFunction"" ""{arguments}""");
s.WaitForExit();
Yes, you can run it as you run any external program. System.Diagnostics.Process will help you out.
Here is a code example from Microsoft community:
using System.Diagnostics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Process myProcess = new Process();
myProcess.StartInfo.FileName = #"ConsoleApplication1.exe";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.Start();
string redirectedOutput=string.Empty;
while ((redirectedOutput += (char)myProcess.StandardOutput.Read()) != "Enter File Name:") ;
myProcess.StandardInput.WriteLine("passedFileName.txt");
myProcess.WaitForExit();
//verifying that the job was successfull or not?!
Process.Start("explorer.exe", "passedFileName.txt");
}
}
}
ConsoleApplication1.exe should be replaced with YourApplication.ps1
Why would you ever use System.Diagnostics.Process rather than System.Management.Automation which is recommended? Because powershell is slow and if you ever need to replace it, using System.Diagnostics.Process will allow doing it immediately.
I was wondering if there is an online tool that can convert c# code to powershell cmdlet code. I have following code that i need to have it powershell. I dont have visual studio to turn this into an exe or dll. any help or ideas would be great.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace CopyUsersBetweenGroupsInSharepointByRR
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This tool will copy the users from one group to another group");
Console.WriteLine("Please enter the URL of the site where your groups are available");
String siteUrl = Console.ReadLine();
using (SPSite site = new SPSite(siteUrl))
{
try
{
SPWeb web = site.OpenWeb();
Console.WriteLine("Please enter the name of the source group");
String sourceGroupName = Console.ReadLine();
Console.WriteLine("Please enter the name of the destination group");
String destinationGroupName = Console.ReadLine();
SPGroup sourceGroup = web.Groups[sourceGroupName];
SPGroup destinationGroup = web.Groups[destinationGroupName];
SPUserCollection sourceUsers = sourceGroup.Users;
SPUserInfo[] sourceUserInfoArray = new SPUserInfo[sourceUsers.Count];
for (int i = 0; i < sourceUsers.Count; i++)
{
sourceUserInfoArray[i] = new SPUserInfo();
sourceUserInfoArray[i].LoginName = sourceUsers[i].LoginName;
sourceUserInfoArray[i].Name = sourceUsers[i].Name;
}
destinationGroup.Users.AddCollection(sourceUserInfoArray);
destinationGroup.Update();
web.Update();
Console.WriteLine("Operation Completed Successfully");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
}
}
It's comments like those above that are turning people away from SO in droves. The OP's question was unambiguous and displayed genuine need.
There are several ways to achieve this. Rewriting your entire C# code repository is not one of them.
As already discussed, as of PS 2 you are able to either run C# (or most any other language) inline, or refer to well-formed external file. I've had mixed success with this and I don't believe it's what the OP was really after.
If you genuinely want to convert code (particularly compiled assemblies) then a decompiler like Reflector is able to do this and - with the PowerShell addon - is also able to convert it on-the-fly.
http://blog.lekman.com/2011/10/converting-c-to-powershell.html
If you want your input and output to take place within the PS console then you'd still have to perform some obvious re-writes. But this method has proved incredibly useful to me.
The fastest way to do it is to write the PowerShell code yourself.
Below is how the code will look in PowerShell, i would say that most C# developers should be able to grasp the concepts of converting C# code to PowerShell in a very short time.
Functions can be a little odd at the beginning, since the usual PS syntax is
myFunction Parameter1 Parameter2
Also you really should install PowerShell 3.0 and use the Windows PowerShell ISE tool to develop the code.
Anyways it should not take you more than 1-2 hours to get your C# code running along in PowerShell.
[System.Reflection.Assembly]::LoadWithPartialName(”Microsoft.SharePoint”)
Write-Host "This tool will copy the users from one group to another group"
Write-Host "Please enter the URL of the site where your groups are available"
[string] $siteUrl = [Console]::ReadLine()
$site = new-object Microsoft.SharePoint.SPSite($siteUrl)
try
{
$web = $site.OpenWeb()
Write-Host "Please enter the name of the source group"
[string] $sourceGroupName = [Console]::ReadLine()
Write-Host "Please enter the name of the destination group"
[string] $destinationGroupName = [Console]::ReadLine()
$sourceUsers = $web.Groups[$sourceGroupName]
(and so on)
}
catch
{
Write-Error ("Failed to copy sharepoint users." + $_)
}
I doubt there is anything remotely like that, however Visual Studio is not required to compile c# code. You could compile an exe without VS. The compiler (csc.exe) and msbuild are included as part of framework. They are located in C:\Windows\Microsoft.NET\Framework\{version}.
If you really want to call this from powershell, have a look at the Add-Type cmdlet. You provide it the source code and it will compile the source on the fly, then load the assembly into your session.
Not sure about online tools, but download the free Visual Studio Express & follow this tutorial should have you creating a cmdlet in no time