1

How I will execute the Powershell script in C# without use of UserName and Password?

Powershell Script:

#Script:This Script generate the Package (Zip file) dynamically for unittest 
#DirectoryName is Out Directory of Unittest execution
#location  is Out\Resource Directory
#locationdetail is Array of files Directory for generate the Package
#FileName is name of Package generated through this script
#option is use for switch case implementation,currently not implemented 

 param(   
        [string]$DirectoryName="."
    ,   [string]$location=""
    ,   [string]$FileName="Test.zip"
    ,   [int] $option
)

 [System.Reflection.Assembly]::LoadFrom($DirectoryName+"\\"+"Ionic.Zip.dll");
  $locationdetail =  "Package\\Resource", "Package\\ResourceBad", "Package\\ResourceEmptymetada","Package\\ResourceEmptydatafile","Package\\EmptyTest"
  $directoryToZip=""

  foreach ($element in $locationdetail) 
  {
    If($element -eq "Package\\Resource")
    {
        $directoryToZip= $location+"\\"+"Package\\Resource"
        $FileName ="Package (Good Data).zip"        
    }
    If($element -eq "Package\\ResourceBad")
    {
        $directoryToZip= $location+"\\"+"Package\\ResourceBad"
        $FileName ="Package (Bad Data).zip"     
    }
    If($element -eq "Package\\ResourceEmptymetada")
    {
        $directoryToZip= $location+"\\"+"Package\\ResourceEmptymetada"
        $FileName ="Package (Bad with ManifestEmpty).zip"               
    }
    If($element -eq "Package\\ResourceEmptydatafile")
    {
        $directoryToZip= $location+"\\"+"Package\\ResourceEmptydatafile"
        $FileName ="Package (Bad with Datafile Empty).zip"      
    }
    If($element -eq "Package\\EmptyTest")
    {
        $directoryToZip= $location+"\\"+"Package\\EmptyTest"
        $FileName ="EmptyTest.zip"      
    }
    $zipfile =  new-object Ionic.Zip.ZipFile
    $e= $zipfile.AddDirectory($directoryToZip)
    $zipfile.Save( $location+"\\"+$FileName)
    $zipfile.Dispose()
    $directoryToZip=""
  }

and My C# code

private static void StartPowerShell(string args,string TempScript)
    {

        string powerShellPath ="C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
        string commandLine = @" -Sta -Command ""& {{ try {{ {0} }} catch {{throw}} }} """.InvariantCultureFormat(args);

        var info = new ProcessStartInfo();
        info.FileName = powerShellPath;
        info.Arguments = commandLine;
        info.WorkingDirectory = Environment.CurrentDirectory;
        info.UseShellExecute = false;
        info.CreateNoWindow = false;
        info.RedirectStandardError = true;
        info.RedirectStandardOutput = true;

        //Pass the Username and Password here in  ProcessStartInfo
        info.UserName = "Saroop";
        string pw = "saroop";
        System.Security.SecureString password = new System.Security.SecureString();
        foreach (var item in pw)
        {
            password.AppendChar(item);
        }
        info.Password = password;
        info.RedirectStandardError = true;
        info.RedirectStandardOutput = true;
        Process p = new Process();
        p.StartInfo = info;
        bool flag = p.Start();
        string error = p.StandardError.ReadToEnd();

        p.WaitForExit();
    }

Please guide me anyone. I try to use runas command to start my Powershell.exe as a User(Administrator) but it's also ask for Username and Password. I try for System.Management.Automation. dll but it's no more existed in .Net4.0 Reference link : http://msdn.microsoft.com/en-us/library/system.management.automation(v=vs.85).aspx

Please help me.

1
  • I found the answer of my query . FOR EXECUTE THE POWERSHELL SCRIPT MUST EXECUTE THE POLICY COMMAND FOR SYSTEM32 C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe AND IF YOUR SYSTEM IS 64BIT THEN ALSO EXECUTE SAME POLICY FOR 64BIT POWERSHELL.EXE TOO. C:\Windows\SysWOW64\WindowsPowerShell\v1.0\POWERSHELL.EXE COMMAND : Set-ExecutionPolicy Unrestricted Commented Jan 27, 2012 at 13:40

2 Answers 2

1

What you wrote in the comment will works, but i'd like to give you another direction to run powershell scripts from C# code.

You can use System.Management.Automation.Runspaces namespace which expose really easy and more elegant way to run powershell commands and retrieve the results from C# (and using the returned objects and not just the output textual stream). Try to read about it.

Sign up to request clarification or add additional context in comments.

3 Comments

Download the PowerShell SDK, microsoft.com/download/en/details.aspx?id=2560 it has examples in C# how to call PowerShell.
This Dll not avaliable in .Net 4.0.
@Shanhar,Phil : Your way also not wrong but for that I need to Install Powershell SDK. But if i don't have any rights to install SDK then it's required to run as Process.My script is run on TFS 2010 and I don't know anything about TFS server configuration.So we both are correct in different scenarios
1

I found the answer of my query . FOR EXECUTE THE POWERSHELL SCRIPT MUST EXECUTE THE POLICY COMMAND FOR SYSTEM32 C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe AND IF YOUR SYSTEM IS 64BIT THEN ALSO EXECUTE SAME POLICY FOR 64BIT POWERSHELL.EXE TOO. C:\Windows\SysWOW64\WindowsPowerShell\v1.0\POWERSHELL.EXE

    /// COMMAND : `Set-ExecutionPolicy Unrestricted`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.