简体   繁体   中英

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

I'm relatively new to Azure and hope someone can help me. I have an azure VM on which I have installed Azure Powershell. I am able to run the following script to move some files from Azure storage onto the VM with no issues:

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

However, I run into an issue when I try replicate the above using the .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);

The following error is always thrown:

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

Can anyone help me with this? It seems the SDK is unable to detect the Azure Powershell installation on the VM, though I have installed it for all users. I know the script syntax is fine as I can run it from within Powershell on the VM. Is there another way to run Azure Powershell scripts from within C#? I would rather not have the script saved on the VM if possible. Thanks in advance!

EDIT - as a workaround I installed AZCopy and was able to use 'vanilla' powershell (not the Azure variant) to get AZCopy to move the files around that I needed.

Try adding the strings as literals, you have \\ chars in your string data.

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}");

The @ at the start of the string tells C# to not interpret \\ as special character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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