0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

When I changed the code to the one you recommended and changed the script extension from txt to ps1 then nothing changed, the machine still won't boot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.