mewkie
mewkie

Reputation: 37

Powershell Script Not Executing Fully from C# Application

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!

Upvotes: 1

Views: 1552

Answers (2)

user12022380
user12022380

Reputation: 11

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.

Upvotes: 1

Peter Kay
Peter Kay

Reputation: 996

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.

Upvotes: 1

Related Questions