| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1110 人关注过本帖
标题:C#调用.ps1
只看楼主 加入收藏
Aviva_Wang
Rank: 11Rank: 11Rank: 11Rank: 11
来 自:苏州
等 级:贵宾
威 望:26
帖 子:701
专家分:2382
注 册:2013-3-12
结帖率:100%
收藏
 问题点数:0 回复次数:2 
C#调用.ps1
C#调用.ps1
写程序调用.ps1,不仅仅只是执行.ps1文件,还需要改掉.ps1中的内容
再执行.ps1这个文件
2013-04-17 14:40
yms123
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:209
帖 子:12488
专家分:19042
注 册:2004-7-17
收藏
得分:0 
/*

* C#调用PowerShell代码示例  

*

* 需要引用System.Management.Automantion.dll

*/

using System;

using System.Collections.Generic;

using System.Collections.ObjectModel;

using System.Management.Automation;

using System.Management.Automation.Runspaces;

using System.Text;

namespace ConsoleApplication

{

    class Program

    {

        static void Main(string[] args)

        {

            string result = RunScript("get-process");

Console.Write(result);

            Console.Read();

        }

/// <summary>

        /// 运行脚本信息,返回脚本输出

        /// </summary>

        /// <param name="scriptText">需要运行的脚本</param>

        /// <returns>output of the script</returns>

        private static string RunScript(string scriptText)

        {

            // create Powershell runspace

            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it

            runspace.Open();

            // create a pipeline and feed it the script text

            Pipeline pipeline = runspace.CreatePipeline();

            (scriptText);

            // add an extra command to transform the script output objects into nicely formatted strings

            // remove this line to get the actual objects that the script returns. For example, the script

            // "Get-Process" returns a collection of System.Diagnostics.Process instances.

            ("Out-String");

            // execute the script

            Collection results = pipeline.Invoke();

            // close the runspace

            runspace.Close();

            // convert the script result into a single string

            StringBuilder stringBuilder = new StringBuilder();

            foreach (PSObject obj in results)

            {

                stringBuilder.AppendLine(obj.ToString());

            }

            return stringBuilder.ToString();

        }

    }

}
如果说ps1文件内部是类似于cmd的文本文件一种,可以尝试用修改文本文件的方法来修改ps1文件的内容
收到的鲜花
  • Aviva_Wang2013-04-20 20:50 送鲜花  20朵   附言:很好
2013-04-20 10:08
Aviva_Wang
Rank: 11Rank: 11Rank: 11Rank: 11
来 自:苏州
等 级:贵宾
威 望:26
帖 子:701
专家分:2382
注 册:2013-3-12
收藏
得分:0 
这个是直接操作powershell指令,请问有调用.ps1文档相关事例吗

asp
2013-04-20 20:52
快速回复:C#调用.ps1
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014963 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved