繁体   English   中英

在C#中使用PowerShell运行命令时访问被拒绝

[英]Access Denied When Running Command Using PowerShell in C#

我正在尝试编写一个程序,以在单击按钮时使用Msinfo32实用程序导出系统信息。 我正在使用Powershell类在C#中执行此操作。 现在,问题在于已编译的应用程序已设置为可以使用管理员特权运行。 但是,当该实用程序开始保存到桌面时,仍然出现“访问被拒绝”错误。 以下是源代码:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management.Automation;
using System.IO;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;

namespace Diagnostic_Tool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 10;
            Runspace Run = RunspaceFactory.CreateRunspace();
            Run.Open();
            progressBar1.Value = 30;
            Pipeline pipeline = Run.CreatePipeline();
            progressBar1.Value = 50;
            Command Msinfo32 = new Command("Msinfo32.exe");
            string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            Msinfo32.Parameters.Add("/nfo");
            Msinfo32.Parameters.Add(path);
            progressBar1.Value = 70;
            pipeline.Commands.Add(Msinfo32);
            pipeline.Invoke();
            pipeline.Stop();
            Run.Close();
            progressBar1.Value = 100;
            MessageBox.Show("The Task Has Completed Successfully");


    }


}
}

谁能告诉我发生了什么事吗?

您被拒绝访问是因为您要告诉msinfo将数据直接写到Desktop目录本身而不是文件中。

您的“ path”变量包含桌面目录的名称。 您需要将文件名附加到此参数。 例如:

OLD: MSinfo32.Parameters.add(path)

NEW: MSinfo32.Parameters.add(path + "\\foo.txt")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM