簡體   English   中英

如何通過 dot net / C# 在 Azure VM 上運行 Azure Powershell 腳本

[英]How to run Azure Powershell scripts on an Azure VMs via dot net / C#

我對 Azure 比較陌生,希望有人可以幫助我。 我有一個安裝了 Azure Powershell 的 azure VM。 我能夠運行以下腳本將一些文件從 Azure 存儲移動到 VM 上,沒有問題:

$path = "C:\Users\AdminUser\Desktop\test\"
$ConName = 'my-container'
$Ctx = New-AzStorageContext -ConnectionString <my connection string>
$List = Get-AzStorageBlob -Container $ConName -Context $Ctx
$List = $List.name
foreach ( $l in $list ){Get-AzStorageBlobContent -Blob $l -Container $conname -Context $ctx -Destination $path}

但是,當我嘗試使用 .NET azure SDK 復制上述內容時遇到了一個問題:

using Microsoft.Azure.Management.Compute.Fluent.Models;

var scriptLines = new List<string>();
var scriptParams = new List<RunCommandInputParameter>();

scriptLines.Add(@"$path = 'C:\Users\AdminUser\Desktop\test\'");
scriptLines.Add("$ConName = 'my-container'");
scriptLines.Add("$Ctx = New-AzStorageContext -ConnectionString <my connection string>");
scriptLines.Add("$List = Get-AzStorageBlob  -Container $ConName -Context $Ctx");
scriptLines.Add("$List = $List.name");
scriptLines.Add("foreach ( $l in $list ){Get-AzStorageBlobContent -Blob $l -Container $conname -Context $ctx -Destination $path}");

var result = vm.RunPowerShellScript(scriptLines, scriptParams);

總是拋出以下錯誤:

"New-AzStorageContext : The term 'New-AzStorageContext' is not recognized as the name of a cmdlet, function, script \nfile, or operable program...

誰能幫我這個? SDK 似乎無法檢測到 VM 上的 Azure Powershell 安裝,但我已經為所有用戶安裝了它。 我知道腳本語法很好,因為我可以在 VM 上的 Powershell 中運行它。 是否有另一種方法可以從 C# 中運行 Azure Powershell 腳本? 如果可能,我寧願不將腳本保存在 VM 上。 提前致謝!

編輯 - 作為一種解決方法,我安裝了 AZCopy 並且能夠使用“vanilla”powershell(不是 Azure 變體)讓 AZCopy 移動我需要的文件。

嘗試將字符串添加為文字,您的字符串數據中有 \\ chars。

scriptLines.Add(@"$path = 'C:\Users\AdminUser\Desktop\test\'");
scriptLines.Add(@"$ConName = 'my-container'");
scriptLines.Add(@"$Ctx = New-AzStorageContext -ConnectionString <my connection string>");
scriptLines.Add(@"$List = Get-AzStorageBlob  -Container $ConName -Context $Ctx");
scriptLines.Add(@"$List = $List.name");
scriptLines.Add(@"foreach ( $l in $list ){Get-AzStorageBlobContent -Blob $l -Container $conname -Context $ctx -Destination $path}");

字符串開頭的 @ 告訴 C# 不要將 \\ 解釋為特殊字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM