【问题标题】:How to run Azure virtual machine from PowerShell script in C#如何在 C# 中从 PowerShell 脚本运行 Azure 虚拟机
【发布时间】:2020-09-16 10:14:28
【问题描述】:

我想从 C# 脚本运行我的虚拟机,如果我尝试从 PowerShell(5.1.18362.752 版本)执行此操作,它可以工作, 我放了第一个命令

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

然后是第二个命令

$PowerState = ((Get-AzureRmVM -Name Janusz -ResourceGroupName Inzynierska -Status).Statuses[1]).code If ( $PowerState -contains "PowerState/running") { Write-Host "PowerState1: running" } ElseIf ( $PowerState -contains "PowerState/deallocated") { Start-AzureRmVM -Name Janusz -ResourceGroupName Inzynierska $PowerState = ((Get-AzureRmVM -Name Janusz -ResourceGroupName Inzynierska -Status).Statuses[1]).code } Write-Host "PowerState2: $PowerState"

但如果我尝试在 C# .Net Core 中执行此操作,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();

我检查了 text 和 text1 里面的内容,并且脚本读取正确。 有人可以解释一下我的代码有什么问题或为什么它不起作用吗?以及如何从 C# 运行这个 PowerShell 脚本?

谢谢

【问题讨论】:

    标签: c# azure powershell .net-core virtual-machine


    【解决方案1】:

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

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

    参考:

    Adding and invoking commands

    【讨论】:

    • 当我将代码更改为您推荐的代码并将脚本扩展名从 txt 更改为 ps1 之后没有任何变化,机器仍然无法启动
    猜你喜欢
    • 2021-03-08
    • 2017-01-07
    • 1970-01-01
    • 2020-09-09
    • 2015-09-04
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2018-05-11
    相关资源
    最近更新 更多