相关疑难解决方法(0)

从C#调用powershell cmdlet

我正在尝试学习如何从C#调用PS cmdlet,并且遇到了PowerShell类.它适用于基本用途,但现在我想执行此PS命令:

Get-ChildItem | where {$_.Length -gt 1000000}
Run Code Online (Sandbox Code Playgroud)

我尝试通过powershell类来构建它,但我似乎无法做到这一点.到目前为止这是我的代码:

PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-ChildItem");
ps.AddCommand("where-object");
ps.AddParameter("Length");
ps.AddParameter("-gt");
ps.AddParameter("10000");


// Call the PowerShell.Invoke() method to run the 
// commands of the pipeline.
foreach (PSObject result in ps.Invoke())
{
    Console.WriteLine(
        "{0,-24}{1}",
        result.Members["Length"].Value,
        result.Members["Name"].Value);
} // End foreach.
Run Code Online (Sandbox Code Playgroud)

我跑这个时总是遇到异常.是否可以像这样运行Where-Object cmdlet?

c# powershell

21
推荐指数
1
解决办法
2万
查看次数

从c#获取Powershell错误

问题

我从c#调用powershell命令但是,PowerShell命令对象似乎只有属性bool HasErrors不能帮助我知道我收到了什么错误.

这就是我构建powershell命令的方法

图书馆

public static class PowerSheller
{
    public static Runspace MakeRunspace()
    {
        InitialSessionState session = InitialSessionState.CreateDefault();
        Runspace runspace = RunspaceFactory.CreateRunspace(session);
        runspace.Open();

        return runspace;
    }

    public static PowerShell MakePowershell(Runspace runspace)
    {
        PowerShell command = PowerShell.Create();
        command.Runspace = runspace;

        return command;
    }
}
Run Code Online (Sandbox Code Playgroud)

调用Move-Vm cmdlet

using (Runspace runspace = PowerSheller.MakeRunspace())
{
    using (PowerShell command = PowerSheller.MakePowershell(runspace))
    {
        command.AddCommand("Move-VM");
        command.AddParameter("Name", arguments.VMName);
        command.AddParameter("ComputerName", arguments.HostName);
        command.AddParameter("DestinationHost", arguments.DestinationHostName);

        if (arguments.MigrateStorage)
        {
            command.AddParameter("IncludeStorage");
            command.AddParameter("DestinationStoragePath", arguments.DestinationStoragePath);
        }

        try
        { …
Run Code Online (Sandbox Code Playgroud)

c# error-handling powershell

6
推荐指数
1
解决办法
8224
查看次数

标签 统计

c# ×2

powershell ×2

error-handling ×1