繁体   English   中英

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

[英]How to run Azure virtual machine from PowerShell script in C#

我想从 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# 运行 PowerShell 脚本

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

参考:

添加和调用命令

暂无
暂无

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

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