1

So I'm trying to run a Powershell script from C#

        string text = System.IO.File.ReadAllText(@"C:\Users\nameofuser\Desktop\script.ps1");

        using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            PowerShellInstance.AddScript(text);

            PowerShellInstance.Invoke();
            if (PowerShellInstance.Streams.Error.Count > 0)
            {
                Console.Write("Error");
            }
            Console.ReadKey();

This is the Script File

$username = "xxx"
$password = "xxx"
$server = "xxx"
$database = "xxx"
$currentuser = "xxx"
$homepath = "C:\Users\$currentuser\Desktop"

mkdir "$homepath\csvs"
mkdir "$homepath\csvs\$database"
$AttachmentPath = "$homepath\csvs\$database\name.csv"
$QueryFmt = "SELECT * FROM TEST"
Invoke-Sqlcmd -User $username -Password $password -ServerInstance $server - 
Database $database -Query $QueryFmt | Export-CSV $AttachmentPath

However, the script only runs up through to line mkdir "$homepath\csvs\$database" and then stops working. In other words, the query inside of the script is not executing.

Any help would be greatly appreciated!

3
  • 1
    Can you confirm that running the script outside of C#, by itself, works? Commented Oct 15, 2018 at 20:30
  • Yep it works just fine Commented Oct 15, 2018 at 21:43
  • There should be an error output of some sort if it is failing at the Query. Did you perform any error handling? Commented Oct 15, 2018 at 21:50

2 Answers 2

1

Try adding a

Import-Module Sqlps

At the beginning of your powershell script and see if it's because your c# context does not have the sql module loaded during run time.

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

2 Comments

It seems to just hang up on the import now
Oddly enough it seems the script is actually hanging up by itself now with some connectivity issues that I fixed. It's working now so all the above code was correct. Thanks for the help
1

You may need to enable PowerShell scripts to execute on your computer. Your C# is running but, by default, windows does not allow PowerShell to execute.

Start Windows PowerShell with the "Run as Administrator" option. Only members of the Administrators group on the computer can change the execution policy.

Enable running unsigned scripts by entering: set-executionpolicy remotesigned

This will allow running unsigned scripts that you write on your local computer and signed scripts from Internet.

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.