【Azure Developer】调用SDK的runPowerShellScript方法,在Azure VM中执行PowerShell脚本示例

简介: 【Azure Developer】调用SDK的runPowerShellScript方法,在Azure VM中执行PowerShell脚本示例

当需要通过代码的方式执行PowerShell脚本时,可以参考以下的示例。

 

 

 

Azure SDK中提供了两个方法来执行PowerShell脚本 (SDK Source Code: https://github.com/Azure/azure-libraries-for-java/blob/master/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImpl.java#L400)

  • public RunCommandResult runPowerShellScript(String groupName, String name, List<String> scriptLines, List<RunCommandInputParameter> scriptParameters)
  • public Observable<RunCommandResult> runPowerShellScriptAsync(List<String> scriptLines, List<RunCommandInputParameter> scriptParameters)

在使用的时候,需要注意的是参数scriptLines 和 scriptParameters。 下面部分为关键代码,以Java SDK的同步方法runPowerShellScript为例

Azure azure = null;
        azure = Azure.authenticate(credentials).withSubscription("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
        
        // 获取虚拟机对象
        VirtualMachine testvm = azure.virtualMachines().getById(
                "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vm resource group /providers/Microsoft.Compute/virtualMachines/vm name");
        //testvm.start();
        
        // 准备PowerShell脚本
        List<String> scriptLines = new ArrayList<String>();
        scriptLines.add(" param([string]$arg1, [string]$arg2 )");
        scriptLines.add(" Write-Host This is a sample script with parameters $arg1 and $arg2");
        scriptLines.add(" Get-Host | Select-Object Version");
        //设置参数arg1 和 arg2
        List<RunCommandInputParameter> scriptParameters = new ArrayList<RunCommandInputParameter>();
        RunCommandInputParameter arg1 = new RunCommandInputParameter(){};
        arg1.withName("arg1");
        arg1.withValue("test1");
        RunCommandInputParameter arg2 = new RunCommandInputParameter(){};
        arg2.withName("arg2");
        arg2.withValue("test2");
        scriptParameters.add(arg1);
        scriptParameters.add(arg2);
        //执行 PowerShell
        RunCommandResult rcresult = testvm.runPowerShellScript("vm-rg", "lbpstest01", scriptLines, scriptParameters);
        System.out.println(rcresult.value().get(0).message());
        System.out.println(rcresult.value().get(1).message());

注意:

  1. 在获取 azure对象时,需要通过AAD认证。并且当前使用的认证有权限操作所选择的虚拟机(VM)。获取认证信息部分参考博文 “使用Java代码启动Azure VM(虚拟机)
  2. 如PowerShell脚本中需要传入参数,则必须在脚本中进行声明,如:param([string]���1,[������]arg2 ),然后通过scriptParameters对象传入。
  3. PowerShell执行成功的结果包含在RunCommandResult对象的Value 1中,如果所输入的PowerShell脚本有语法等操作,则在Value 2中输出详细的异常消息.

在执行PowerShell脚本时,如发现脚本有错误。在RunCommandResult中会返回PowerShell提示的错误信息:

错误的PowerShell脚本
RunCommandResult中的提示消息

示例完整代码:

package org.example;
import java.util.ArrayList;
import java.util.List;
import com.microsoft.azure.AzureEnvironment;
import com.microsoft.azure.credentials.ApplicationTokenCredentials;
import com.microsoft.azure.credentials.AzureTokenCredentials;
import com.microsoft.azure.management.Azure;
import com.microsoft.azure.management.compute.*;
/**
 * s Hello world!
 *
*/
public class App {
    public static void main(String[] args)
    {
        //使用AAD Application 方式获取 认证
        AzureTokenCredentials credentials = new ApplicationTokenCredentials("application id",
                "tenant id "securt key",
                AzureEnvironment.AZURE_CHINA);
        Azure azure = null;
        azure = Azure.authenticate(credentials).withSubscription("subscription id");
        
        // 获取虚拟机对象
        VirtualMachine testvm = azure.virtualMachines().getById("resource id");
        //testvm.start();
        
        // 准备PowerShell脚本
        List<String> scriptLines = new ArrayList<String>();
        scriptLines.add(" param([string]$arg1, [string]$arg2)");
        scriptLines.add(" Write-Host This is a sample script with parameters $arg1 and $arg2");
        scriptLines.add(" Get-Host | Select-Object Version");
        //设置参数arg1 和 arg2
        List<RunCommandInputParameter> scriptParameters = new ArrayList<RunCommandInputParameter>();
        RunCommandInputParameter arg1 = new RunCommandInputParameter(){};
        arg1.withName("arg1");
        arg1.withValue("test1");
        RunCommandInputParameter arg2 = new RunCommandInputParameter(){};
        arg2.withName("arg2");
        arg2.withValue("test2");
        scriptParameters.add(arg1);
        scriptParameters.add(arg2);
        //执行 PowerShell
        RunCommandResult rcresult = testvm.runPowerShellScript("vm-rg", "lbpstest01", scriptLines, scriptParameters);
        System.out.println(rcresult.value().get(0).message());
        System.out.println(rcresult.value().get(1).message());
        System.out.println("Hello World!");
    }
}

 

在POM.XML中引用的SDK Version:

   <dependency>

     <groupId>com.microsoft.azure</groupId>

     <artifactId>azure</artifactId>

     <version>1.37.1</version>

   </dependency>

执行结果的正确输出:

 

 

参考资料

使用Java代码启动Azure VM(虚拟机): https://www.cnblogs.com/lulight/p/14295089.html

Run PowerShell scripts in your Windows VM by using Run Command: https://docs.microsoft.com/en-us/azure/virtual-machines/windows/run-command#azure-cli

azure-libraries-for-java VirtualMachineImpl.java : https://github.com/Azure/azure-libraries-for-java/blob/master/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImpl.java#L400

相关文章
|
20天前
|
JavaScript 前端开发 API
【Azure Developer】use @azure/arm-monitor sdk 遇见 ManagedIdentityCredential authentication failed.(status code 500)
【Azure Developer】use @azure/arm-monitor sdk 遇见 ManagedIdentityCredential authentication failed.(status code 500)
|
20天前
|
存储 Java API
【Azure 存储服务】Java Storage SDK 调用 uploadWithResponse 代码示例(询问ChatGTP得代码原型后人力验证)
【Azure 存储服务】Java Storage SDK 调用 uploadWithResponse 代码示例(询问ChatGTP得代码原型后人力验证)
|
20天前
|
存储 API 开发工具
【Azure Storage Blob】如何通过.NET Azure Storage Blobs SDK获取到Blob的MD5值呢?
【Azure Storage Blob】如何通过.NET Azure Storage Blobs SDK获取到Blob的MD5值呢?
|
20天前
|
Java 开发工具
【Azure Developer】示例: 在中国区调用MSGraph SDK通过User principal name获取到User信息,如Object ID
【Azure Developer】示例: 在中国区调用MSGraph SDK通过User principal name获取到User信息,如Object ID
|
20天前
|
API 开发工具 网络架构
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
|
20天前
|
开发工具 iOS开发 容器
【Azure Blob】关闭Blob 匿名访问,iOS Objective-C SDK连接Storage Account报错
【Azure Blob】关闭Blob 匿名访问,iOS Objective-C SDK连接Storage Account报错
|
20天前
|
消息中间件 开发工具
【Azure Service Bus】Service Bus SDK 抛出 ERROR c.a.c.a.i.ActiveClientTokenManager - Error is transient. Rescheduling authorization task at interval 1079000 ms.
【Azure Service Bus】Service Bus SDK 抛出 ERROR c.a.c.a.i.ActiveClientTokenManager - Error is transient. Rescheduling authorization task at interval 1079000 ms.
|
20天前
|
开发工具
【Azure Event Hub】解决Event Hub SDK出现无法识别 com.azure.core.client.traits.TokenCredentialTrait 错误
【Azure Event Hub】解决Event Hub SDK出现无法识别 com.azure.core.client.traits.TokenCredentialTrait 错误
|
10月前
|
Shell Linux 开发工具
windows中cmd和PowerShell批处理命令
之前在 Git 批量删除本地分支,有用到 Linux 或 MacOS 下的批处理命令,这个命令中的 grep、xargs 本身是 Shell script,在 windows 中的 cmd 和 PowerShell 中是不能用的
77 0
|
JavaScript Windows
[Vue]解决 Windows PowerShell 不识别 vue 命令的问题
[Vue]解决 Windows PowerShell 不识别 vue 命令的问题