且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何运行PowerCli并通过c#运行powershell脚本命令

更新时间:2023-10-21 08:49:16

这应该可以帮到你。



http://***.com/questions/11405384/how-to-pass-a-parameter-from-c-sharp-to-a-powershell-script-file [ ^ ]

Am using the below code to connect to powercli and run a powershell script in it and when i try to do so am getting an error at

pipeline.Invoke();



error message as : 'System.Management.Automation.PSSecurity' occured in System.Management.Automation.dll

Additional information: File 'C:\script\resource.ps1' is not recognised as the name of cmdlet, function, script, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again
, I have no idea how to solve it

Here is the code:

private void Powercli_Click(object sender, EventArgs e)
        {
            RunspaceConfiguration config = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(config);
            
            // open it  
            runspace.Open();
            
            try
            {
                RunspaceInvoke scriptinvoker = new RunspaceInvoke(runspace);
                // import PowerCLI ViCore snapin  
                PSSnapInException warning;
                config.AddPSSnapIn("VMware.VimAutomation.Core", out warning);
                if (warning != null)
                {
                    throw warning;
                }
                // create a pipeline and feed it the script text  
                Pipeline pipeline = runspace.CreatePipeline();
                // Create Command to Set Na Option  
               
                var connectVI = new Command("Connect-VIServer");
                connectVI.Parameters.Add("Server", "192.168.123.108");
                connectVI.Parameters.Add("Protocol", "https");
                connectVI.Parameters.Add("User", "root");
                connectVI.Parameters.Add("Password", "assign");
                Command mycommand = new Command("C:\\script\\resource.ps1");
                
                  // Add Command to Pipeline  
                     pipeline.Commands.Add(connectVI);
                    
                    pipeline.Commands.Add(mycommand);
                     //pipeline.Commands.Add(mycommand1);
                   //Execute by invoking  

                pipeline.Invoke();

                if (pipeline.HadErrors)
                {
                    MessageBox.Show(pipeline.Error.ToString(), "Error occurred");
                }
            }
            finally
            {
                runspace.Close();
            }

        }

This should help you.

http://***.com/questions/11405384/how-to-pass-a-parameter-from-c-sharp-to-a-powershell-script-file[^]