========================================================================
方法1:直接调用
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "wscript";
proc.StartInfo.Arguments = " hello.js";
proc.StartInfo.UseShellExecute = false;
proc.Start();
方法2:
使用MS的Windows Script Control
string scr = "function hello(){var WshShell = new ActiveXObject("WScript.Shell");"
+ "var code = "WScript hello.js";"
+ "WshShell.Exec(code);}";
MSScriptControl.ScriptControl sc = new ScriptControl();
sc.Language = "JScript";
sc.AllowUI = true;
sc.AddCode(scr);
object[] parameters = new Object[0];
sc.Run("hello", ref parameters);
出处:https://bbs.csdn.net/topics/340163504
==========================================================================================
public void RunVBScript() { string strPath = ""; System.Diagnostics.Process proc = new System.Diagnostics.Process(); string scriptPath = strPath + @"\Driver\driver.vbs";//可以是vbs文件或js文件 proc.StartInfo.FileName = "wscript"; proc.StartInfo.Arguments = scriptPath; proc.StartInfo.UseShellExecute = false; proc.Start(); proc.Close(); proc.Dispose(); } static private string RunCmd(string command) { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "cmd.exe"; //确定程序名 p.StartInfo.Arguments = "/c " + command; //确定程序命令行 p.StartInfo.UseShellExecute = false; //Shell的使用 p.StartInfo.RedirectStandardInput = true; //重定向输入 p.StartInfo.RedirectStandardOutput = true; //重定向输出 p.StartInfo.RedirectStandardError = true; //重定向输出错误 p.StartInfo.CreateNoWindow = true; //设置置不显示示窗口¿ p.Start(); //00 //p.StandardInput.WriteLine(command); //也可以用这种方式输入入要行的命令 //p.StandardInput.WriteLine("exit"); //需要加上Exit要不然下一行程式 string res = p.StandardOutput.ReadToEnd(); //输出出流取得命令行结果果 p.Close(); p.Dispose(); return res; }
参考:https://blog.csdn.net/hwm831002/article/details/8263699
===================================================================================================================
C#利用ScriptControl动态执行JS和VBS脚本
属性名称 |
类型 |
备注 |
AllowUI |
BOOL |
检测是否允许运行用户的接口元素。如果为False,则诸如消息框之类的界面元素不可见。 |
CodeObject |
Object |
脚本暴露给宿主调用的对象。只读。 |
Modules |
Modules |
宿主提供给脚本的组件库模块。只读。(COM组件通常都是以对象收集的形式向用户提供可以留给用户二次开发的对象集合,每一个收集即一个Modules) |
Language |
String |
设置或获取脚本引擎解释的语言,例如:VBScript、JScript。 |
Name |
String |
脚本引擎的名称。只读。 |
Procedures |
Procedures |
返回模块中定义的过程的集合 |
SitehWnd |
HWND |
在脚本中显示UI的父窗口句柄 |
State |
Enum |
设置或返回控件的状态,如果为0,控件只执行语句但不转发事件,为1则为加入的本控件接受的对象转发事件。 |
Timeout |
Long |
控件的执行脚本的超时值,-1表示不超时 |
UseSafeSubset |
BOOL |
设置或返回宿主程序是否关心安全。宿主程序的安全级别可以从此属性设置 |
Error |
Error |
错误对象,发生错误时,此属性返回一个错误对象 |
方法名称 |
参数 |
功能 |
AddCode |
Code As String |
往脚本引擎中加入要执行的脚本 |
AddObject |
Name As String, Object As Object, [AddMembers As Boolean = False] |
往脚本引擎加入一个对象,以便在脚本中可以使用该对象提供的方法等。 |
Eval |
Expression As String |
表达式求值 |
ExecuteStatement |
Statement As String |
解释并执行脚本语句 |
Reset |
丢弃所有的对象和代码,将State属性置0。 |
|
Run |
ProcedureName As String, ParamArray Parameters() As Variant |
运行一个指定的过程 |
事件名称 |
功能 |
Error |
有错误发生时激发该事件 |
TimeOut |
执行过程超时时发生 |
/* 添加COM引用:
Library MSScriptControl
C:WINDOWSsystem32msscript.ocx
Microsoft Script Control 1.0
*/
例子:
using MSScriptControl;
namespace zz
{
/// <summary>
/// scriptengine类
/// </summary>
public class ScriptEngine
{
private ScriptControl msc;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="language">脚本类型,VBscriptJavaScript</param>
public ScriptEngine(string language)
{
msc = new ScriptControlClass();
msc.UseSafeSubset = true;
msc.Language = language;
((DScriptControlSource_Event)msc).Error += new DScriptControlSource_ErrorEventHandler(ScriptEngine_Error);
((DScriptControlSource_Event)msc).Timeout += new DScriptControlSource_TimeoutEventHandler(ScriptEngine_Timeout);
}
/// <summary>
/// 运行eval方法
/// </summary>
/// <param name="expression">表达式</param>
/// <returns>返回值object</returns>
public object eval(string expression)
{
return msc.Eval(expression);
}
/// <summary>
/// 运行run方法
/// </summary>
/// <param name="mainfunctionname">入口函数名称</param>
/// <param name="parameters">参数</param>
/// <returns>返回值object</returns>
public object Run(string mainFunctionName, object[] parameters)
{
return msc.Run(mainFunctionName, ref parameters);
}
/// <summary>
/// 加入要执行的脚本
/// </summary>
/// <param name="Code"></param>
public void AddCode(string Code)
{
msc.AddCode(Code);
}
/// <summary>
/// 解析并运行
/// </summary>
/// <param name="Code">代码</param>
public void ExecuteStatement(string Code)
{
msc.ExecuteStatement(Code);
}
/// <summary>
/// 放弃所有已经添加到 scriptcontrol 中的 script 代码和对象
/// </summary>
public void Reset()
{
msc.Reset();
}
/// <summary>
/// 获取或设置脚本语言
/// </summary>
public string Language
{
get { return msc.Language; }
set { msc.Language = value; }
}
/// <summary>
/// 获取或设置脚本执行时间,单位为毫秒
/// </summary>
public int Timeout
{
get { return ((IScriptControl)msc).Timeout; }
set { ((IScriptControl)msc).Timeout = value; }
}
/// <summary>
/// 设置是否显示用户界面元素
/// </summary>
public bool AllowUI
{
get { return msc.AllowUI; }
set { msc.AllowUI = value; }
}
/// <summary>
/// 宿主应用程序是否有保密性要求
/// </summary>
public bool UseSafeSubset
{
get { return msc.UseSafeSubset; }
set { msc.UseSafeSubset = true; }
}
private void ScriptEngine_Error()
{
//错误事件
}
private void ScriptEngine_Timeout()
{
//超时事件
}
}
}
出处:https://www.jb51.net/article/35314.htm
==============================================================================
解决方案
1.工程引用 Interop.MSScriptControl.dll
2.创建一个类,代码如下:
using System.Collections.Generic;
using System.Text;
using MSScriptControl;
namespace myClass
{
///<summary>
/// 脚本类型
///</summary>
publicenum ScriptLanguage
{
///<summary>
/// JScript脚本语言
///</summary>
JScript,
///<summary>
/// VBscript脚本语言
///</summary>
VBScript,
///<summary>
/// JavaScript脚本语言
///</summary>
JavaScript
}
///<summary>
/// 脚本运行错误代理
///</summary>
publicdelegatevoid RunErrorHandler();
///<summary>
/// 脚本运行超时代理
///</summary>
publicdelegatevoid RunTimeoutHandler();
///<summary>
/// ScriptEngine类
///</summary>
publicclass clsScriptEngine
{
private ScriptControl msc;
//定义脚本运行错误事件
publicevent RunErrorHandler RunError;
//定义脚本运行超时事件
publicevent RunTimeoutHandler RunTimeout;
///<summary>
///构造函数
///</summary>
public clsScriptEngine()
: this(ScriptLanguage.VBScript)
{
}
///<summary>
/// 构造函数
///</summary>
///<param name="language">脚本类型</param>
public clsScriptEngine(ScriptLanguage language)
{
this.msc =new ScriptControlClass();
//this.msc.UseSafeSubset = true; //使用安全的子集,如果等于true则无法连接数据库
this.msc.Language = language.ToString();
((DScriptControlSource_Event)this.msc).Error +=new DScriptControlSource_ErrorEventHandler(ScriptEngine_Error);
((DScriptControlSource_Event)this.msc).Timeout +=new DScriptControlSource_TimeoutEventHandler(ScriptEngine_Timeout);
}
///<summary>
/// 运行Eval方法
///</summary>
///<param name="expression">表达式</param>
///<param name="codeBody">函数体</param>
///<returns>返回值object</returns>
publicobject Eval(string expression, string codeBody)
{
msc.AddCode(codeBody);
return msc.Eval(expression);
}
///<summary>
/// 运行Eval方法
///</summary>
///<param name="language">脚本语言</param>
///<param name="expression">表达式</param>
///<param name="codeBody">函数体</param>
///<returns>返回值object</returns>
publicobject Eval(ScriptLanguage language, string expression, string codeBody)
{
if (this.Language != language)
this.Language = language;
return Eval(expression, codeBody);
}
///<summary>
/// 运行Run方法
///</summary>
///<param name="mainFunctionName">入口函数名称</param>
///<param name="parameters">参数</param>
///<param name="codeBody">函数体</param>
///<returns>返回值object</returns>
publicobject Run(string mainFunctionName, object[] parameters, string codeBody)
{
this.msc.AddCode(codeBody);
return msc.Run(mainFunctionName, ref parameters);
}
///<summary>
/// 运行Run方法
///</summary>
///<param name="language">脚本语言</param>
///<param name="mainFunctionName">入口函数名称</param>
///<param name="parameters">参数</param>
///<param name="codeBody">函数体</param>
///<returns>返回值object</returns>
publicobject Run(ScriptLanguage language, string mainFunctionName, object[] parameters, string codeBody)
{
if (this.Language != language)
this.Language = language;
return Run(mainFunctionName, parameters, codeBody);
}
///<summary>
/// 放弃所有已经添加到 ScriptControl 中的 Script 代码和对象
///</summary>
publicvoid Reset()
{
this.msc.Reset();
}
///<summary>
/// 获取或设置脚本语言
///</summary>
public ScriptLanguage Language
{
get { return (ScriptLanguage)Enum.Parse(typeof(ScriptLanguage), this.msc.Language, false); }
set { this.msc.Language = value.ToString(); }
}
///<summary>
/// 获取或设置脚本执行时间,单位为毫秒
///</summary>
///<summary>
/// 设置是否显示用户界面元素
///</summary>
publicbool AllowUI
{
get { returnthis.msc.AllowUI; }
set { this.msc.AllowUI = value; }
}
///<summary>
/// 宿主应用程序是否有保密性要求
///</summary>
publicbool UseSafeSubset
{
get { returnthis.msc.UseSafeSubset; }
set { this.msc.UseSafeSubset =true; }
}
///<summary>
/// RunError事件激发
///</summary>
privatevoid OnError()
{
if (RunError !=null)
RunError();
}
///<summary>
/// OnTimeout事件激发
///</summary>
privatevoid OnTimeout()
{
if (RunTimeout !=null)
RunTimeout();
}
privatevoid ScriptEngine_Error()
{
OnError();
}
privatevoid ScriptEngine_Timeout()
{
OnTimeout();
}
}
}
3.创建一个名为vbs_Record.vbs 的VbScrpt,代码如下:
msgbox strChId &" , "& strDate &" , "& strStartTime &" , "& strStopTime &" , "& strTimeLen &" , "& strTimeLenS &" , "& strCallType &" , "& strCallResult &" , "& strCallerId &" , "& strDtmf &" , "& strRecordFile &" , "& strSessionId
Set cn = CreateObject("ADODB.Connection")
strCn ="provider=SQLOLEDB.1;"& _
"Persist Security Info=False;"& _
"User ID=sa;"& _
"password=*******;"& _
"Initial Catalog=DataBase;"& _
"data source=(local)"
cn.Open strCn
if strCallerId<>"" then
strPhoneNumber=strCallerId
else
strPhoneNumber=strDtmf
end if
str ="insert into cti_Record(SessionId,StartDate,StartTime,StopTime,TimeLen,PhoneNumber,CallType,RecordFile) values('"+strSessionId+"','"+strDate+"','"+strStartTime+"','"+strStopTime+"','"+strTimeLenS+"','"+strPhoneNumber+"','"+strCallType+"','"+strRecordFile+"')"
cn.Execute str
msgbox "OK"
End function
4.C#调用此VB脚本,代码如下:
System.IO.StreamReader myReader;
strScriptFile="d:\vbs_Record.vbs";
strScript=myReader.ReadLine();
while(myReader.EndOfStream==false)
{
strScript=strScript +@"
"+ myReader.ReadLine();
}
clsScriptEngine scriptEngine =new clsScriptEngine();
scriptEngine.Language = (ScriptLanguage)Enum.Parse(typeof(ScriptLanguage), "VBScript");
string[] strParameter=this._strParameter.Split(',');
Object[] objParameter=new Object[12];
objParameter.SetValue(strParameter[0],0);
objParameter.SetValue(strParameter[1],1);
objParameter.SetValue(strParameter[2],2);
objParameter.SetValue(strParameter[3],3);
objParameter.SetValue(strParameter[4],4);
objParameter.SetValue(strParameter[5],5);
objParameter.SetValue(strParameter[6],6);
objParameter.SetValue(strParameter[7],7);
objParameter.SetValue(strParameter[8],8);
objParameter.SetValue(strParameter[9],9);
objParameter.SetValue(strParameter[10],10);
objParameter.SetValue(strParameter[11],11);
scriptEngine.Reset();
scriptEngine.Run("vbs_Record", objParameter, strScript);
scriptEngine =null;
出处:https://www.cnblogs.com/hailexuexi/archive/2011/02/15/1955166.html