C# 如何在C中从PowerShell脚本运行Azure虚拟机#

C# 如何在C中从PowerShell脚本运行Azure虚拟机#,c#,azure,powershell,.net-core,virtual-machine,C#,Azure,Powershell,.net Core,Virtual Machine,我想从C#脚本运行我的虚拟机,如果我尝试从PowerShell(5.1.18362.752版本)运行它, 我把命令放在第一位 Import-AzureRmContext-Path“C:\Program Files(x86)\WindowsPowerShell\azureprofile.json” 然后是第二个命令 $PowerState=((Get AzureRmVM-Name Janusz-ResourceGroupName Inzynierska-Status)。状态[1])。代码 If($

我想从C#脚本运行我的虚拟机,如果我尝试从PowerShell(5.1.18362.752版本)运行它, 我把命令放在第一位

Import-AzureRmContext-Path“C:\Program Files(x86)\WindowsPowerShell\azureprofile.json”

然后是第二个命令

$PowerState=((Get AzureRmVM-Name Janusz-ResourceGroupName Inzynierska-Status)。状态[1])。代码
If($PowerState-包含“PowerState/running”)
{
写入主机“PowerState1:正在运行”
}
ElseIf($PowerState-包含“PowerState/deallocated”)
{
在zynierska中启动AzureRmVM-Name Janusz-ResourceGroupName
$PowerState=((Get-AzureRmVM-Name Janusz-ResourceGroupName Inzynierska-Status)。状态[1])。代码
}
写入主机“PowerState2:$PowerState”

但如果我尝试在C#.Net内核中执行此操作,Visual Studio将无法正常工作

static void  Main(string[] args)
        {
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {

                string text = System.IO.File.ReadAllText(@"C:\Users\Krute\Desktop\Inżynierka\PowerShellScriptRunning\FirstScript.txt");
                PowerShellInstance.AddScript(text);

                IAsyncResult result = PowerShellInstance.BeginInvoke();
                while (result.IsCompleted == false)
                {
                    Console.WriteLine("Pierwsze Zapytanie");
                    Thread.Sleep(1000);

                }
            }
            using (PowerShell PowerShellInstance1 = PowerShell.Create())
            {

                string text1 = System.IO.File.ReadAllText(@"C:\Users\Krute\Desktop\Inżynierka\PowerShellScriptRunning\SecondScript.txt");
                PowerShellInstance1.AddScript(text1);

                IAsyncResult result = PowerShellInstance1.BeginInvoke();

                while (result.IsCompleted == false)
                {
                    Console.WriteLine("Drugie Zapytanie");
                    Thread.Sleep(1000);

                }

                Console.WriteLine("Finished!");
            }
            Console.Read();
我检查文本和文本1中的内容,并且脚本读取正确。 有人能解释一下我的代码有什么问题或者为什么它不工作吗?我能做些什么从C#运行这个PowerShell脚本呢


谢谢

您可以像这样从C#运行PowerShell脚本

PowerShell ps = PowerShell.Create();
ps.AddScript(@"D:\PSScripts\MyScript.ps1", true).Invoke();
参考:


当我将代码更改为您推荐的代码,并将脚本扩展名从txt更改为ps1时,没有任何更改,机器仍然无法启动