【发布时间】: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