从Windows应用程序运行powershell脚本时出错 [英] Error while running powershell script from windows application

查看:304
本文介绍了从Windows应用程序运行powershell脚本时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我第一次按下按钮时我工作正常如果再次按下按钮会引发异常

无法调用此功能,因为当前主机没有实现它。

如果我删除了在脚本执行期间创建的文件夹,那么它再次起作用

when first time i pressed the button i works fine if i again pressed the button it will raise the exception
Cannot invoke this function because the current host does not implement it.
if i deleted the folder which is created during script execution then again it works

ClasssLibrary1:Class
	Public string RunScript(string scriptText)
   {
      
       Runspace runspace = RunspaceFactory.CreateRunspace();
       runspace.Open();

       Pipeline pipeline = runspace.CreatePipeline();
       pipeline.Commands.AddScript(scriptText);

       pipeline.Commands.Add("Out-String");

       Collection<PSObject> results = pipeline.Invoke();

       runspace.Close();

       StringBuilder stringBuilder = new StringBuilder();
       foreach (PSObject obj in results)
       {
           stringBuilder.AppendLine(obj.ToString());
       }

       return stringBuilder.ToString();
   }
   
    public string LoadScript(string filename)
        {
            try
            {

                using (StreamReader sr = new StreamReader(filename))
                {

                    StringBuilder fileContents = new StringBuilder();

                    string curLine;

                    while ((curLine = sr.ReadLine()) != null)
                    {
                       
                        fileContents.Append(curLine + "\n");
                    }

                    return fileContents.ToString();
                }
            }
            catch (Exception e)
            {
               
                string errorText = "The file could not be read:";
                errorText += e.Message + "\n";
                return errorText;
            }

        }



这是我的脚本:


Here is my script to:

rmdir D:\Logs

mkdir D:\Logs

Get-EventLog Application |Format-List | Out-File D:\Logs\app.txt
Get-EventLog System |Format-List | Out-File D:\Logs\app.txt





我尝试过:



我将powershell的所有dll文件添加到我的项目中也手动添加了使用它的引用:< reference include =System.Management.Automation>



What I have tried:

I added all the dll files of powershell to my project also manually added refernce to it using this:<reference include="System.Management.Automation">

推荐答案

引用:

如果我删除了在脚本执行期间创建的文件夹然后再次它的工作原理

if i deleted the folder which is created during script execution then again it works

看起来像 rmdir D:\ Logs 无效。

你检查了吗?

rmdir 之前,你确定目录是空的吗?

Looks like rmdir D:\Logs is not working.
Did you check ?
Did you ensure the directory is empty before rmdir ?


这篇关于从Windows应用程序运行powershell脚本时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆