从C#调用运行SQL脚本的powershell
问题描述:
我试图运行从C#执行sql脚本的powershell脚本。从C#调用运行SQL脚本的powershell
如果我运行从PowerShell命令的PowerShell脚本提示它的工作原理,但是当我尝试从C#
这里运行它,它不工作是我使用运行PowerShell脚本
public static void RunPowershell(string fileName, string functionName, Dictionary<string, string> parameters)
{
string fullPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);
string script = File.ReadAllText(fullPath);
try
{
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
PowerShell instance = PowerShell.Create();
instance.Runspace = runspace;
instance.AddScript(script);
instance.Invoke();
instance.Commands.Clear();
var command = instance.AddCommand(functionName);
if (null != parameters)
{
foreach (var parameter in parameters)
{
command.AddParameter(parameter.Key, parameter.Value);
}
}
var result = instance.Invoke();
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
功能
和我的PowerShell脚本是(Test2.ps1):
function RunScript(){
Import-Module "SQLPS" -DisableNameChecking
Invoke-Sqlcmd -inputfile ".\TestSQL.sql" -ServerInstance . -Verbose
}
function ShowMessage(){
[System.Windows.Forms.MessageBox]::Show("Hi from Powershell !")
}
TestSQL.sql看起来是这样的:
USE TEST
GO
INSERT INTO Employee VALUES('1', 'abc')
它显示的消息框,当我尝试:
PowershellHelper.RunPowershell("Test2.ps1", "ShowMessage", null);
但不插入到表时,我尝试:
PowershellHelper.RunPowershell("Test2.ps1", "RunScript", null);
答
这是因为你probalby没有TestSQL脚本在当前目录中。您将不得不提供完整路径或切换当前目录。
Invoke-Sqlcmd -inputfile "C:\FolderWhereYouhavetheSQL\TestSQL.sql" -ServerInstance . -Verbose
或
cd "C:\FolderWhereYouhavetheSQL"
Invoke-Sqlcmd -inputfile ".\TestSQL.sql" -ServerInstance . -Verbose
TestSQL.sql是在相同的目录中Test2.ps1。我尝试了完整路径,但没有奏效。 –
当您从PowerShell中单独运行Test2.ps1时,您获得的输出是什么? –
当我从PowerShell命令提示符运行Test2.ps1时,我可以看到脚本正确执行并且在表中添加了值。 –