Krutek
Krutek

Reputation: 1

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

I want to run my virtual machine from C# script, if i try to do this from PowerShell(5.1.18362.752 version) it works, i put first command

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

and then second command

$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"

but if i try to do this in C# .Net Core ,Visual Studio it's doesn't work

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();

I check what is inside text and text1 and script is read correct. Can somebody explain me what is wrong with my code or why it doesn't work? and what i can do to run this PowerShell script from C# ?

Thanks

Upvotes: 0

Views: 582

Answers (1)

Tony Ju
Tony Ju

Reputation: 15609

You can run PowerShell script from C# like this

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

Reference:

Adding and invoking commands

Upvotes: 1

Related Questions