NEWS

[C#] Hướng dẫn chạy Script Windows Power Shell trong lập trình Winform

[C#] Hướng dẫn chạy Script Windows Power Shell trong lập trình Winform
Đăng bởi: Thảo Meo - Lượt xem: 7721 11:28:42, 27/08/2019C#   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách thực hiện lệnh Script Power Shell trong lập trình C# Winform.

[C#] Hướng dẫn thực hiện Script Windows PowerShell trên Winform

Windows PowerShell chắc còn không xa lạ với chúng ta, trong bài viết này mình chỉ hướng dẫn các bạn cách chạy lệnh powershell trong winform C#.

Và lấy dữ liệu kết quả trả về và xử lý theo ý muốn của chúng ta.

VD: Trong Power Shell chúng ta có lệnh như: check hashfile sha1 hay md5..., thì chúng ta cũng có thể sử dụng script để lấy.

Hoặc sử dụng các hàm cơ bản như:

Get-Process, Get-Service, Get-FileHash...

Các bạn có thể Google để tìm hiểu thêm về các lệnh của PowerShell nhé các bạn.

Dưới đây là giao diện demo của ứng dụng:

Hiển thị các Process đang chạy (Task Manager) sử dụng PowerShell:

power_shell_csharp_demo

Để thực hiện được bài viết này, các bạn cần cài đặt thư viện System.Management.Automation từ Nuget như hình ảnh bên dưới:

powser_shell_lib

Đầu tiên các bạn cần import thư viện vào:

using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Windows.Forms;

Source code chạy Script PowerShell và trả về kết quả:

private 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();
}

sự kiện Click vào button Run Script:

private void btn_run_Click(object sender, EventArgs e)
{
    try
    {
        txt_output.Clear();
        txt_output.Text = RunScript(txt_input.Text);
    }
    catch (Exception error)
    {
        txt_output.Text += String.Format("
Error in script : {0}
", error.Message);
    }
}

Thanks for watching!

 

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn chạy Script Windows Power Shell trong lập trình Winform
Đăng bởi: Thảo Meo - Lượt xem: 7721 11:28:42, 27/08/2019C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.