【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

相关文章
|
7月前
|
数据安全/隐私保护
【Azure Function App】PowerShell Function 执行 Get-AzAccessToken 的返回值类型问题:System.String 与 System.Security.SecureString
将PowerShell Function部署到Azure Function App后,Get-AzAccessToken返回值类型在不同环境中有差异。正常为SecureString类型,但部分情况下为System.String类型,导致后续处理出错。解决方法是在profile.ps1中设置环境变量$env:AZUREPS_OUTPUT_PLAINTEXT_AZACCESSTOKEN=false,以禁用明文输出。
196 0
|
JSON 数据格式
【Azure Fabric Service】演示使用PowerShell命令部署SF应用程序(.NET)
本文详细介绍了在中国区微软云Azure上使用Service Fabrics服务时,通过PowerShell命令发布.NET应用的全过程。由于Visual Studio 2022无法直接发布应用,需借助PowerShell脚本完成部署。文章分三步讲解:首先在Visual Studio 2022中打包应用部署包,其次连接SF集群并上传部署包,最后注册应用类型、创建实例并启动服务。过程中涉及关键参数如服务器证书指纹和服务端证书指纹的获取,并附带图文说明,便于操作。参考官方文档,帮助用户成功部署并运行服务。
374 73
|
JavaScript Shell C#
多种脚本批量下载 Docker 镜像:Shell、PowerShell、Node.js 和 C#
本项目提供多种脚本(Shell、PowerShell、Node.js 和 C#)用于批量下载 Docker 镜像。配置文件 `docker-images.txt` 列出需要下载的镜像及其标签。各脚本首先检查 Docker 是否安装,接着读取配置文件并逐行处理,跳过空行和注释行,提取镜像名称和标签,调用 `docker pull` 命令下载镜像,并输出下载结果。使用时需创建配置文件并运行相应脚本。C# 版本需安装 .NET 8 runtime。
1003 3
|
API 开发工具 Python
【Azure Developer】编写Python SDK代码实现从China Azure中VM Disk中创建磁盘快照Snapshot
本文介绍如何使用Python SDK为中国区微软云(China Azure)中的虚拟机磁盘创建快照。通过Azure Python SDK的Snapshot Class,指定`location`和`creation_data`参数,使用`Copy`选项从现有磁盘创建快照。代码示例展示了如何配置Default Azure Credential,并设置特定于中国区Azure的`base_url`和`credential_scopes`。参考资料包括官方文档和相关API说明。
237 1
【Azure App Service】PowerShell脚本批量添加IP地址到Web App允许访问IP列表中
Web App取消公网访问后,只允许特定IP能访问Web App。需要写一下段PowerShell脚本,批量添加IP到Web App的允许访问IP列表里!
283 2
|
Kubernetes API 开发工具
【Azure Developer】通过SDK(for python)获取Azure服务生命周期信息
需要通过Python SDK获取Azure服务的一些通知信息,如:K8S版本需要更新到指定的版本,Azure服务的维护通知,服务处于不健康状态时的通知,及相关的操作建议等内容。
261 18
|
JavaScript 前端开发 开发工具
【Azure Developer】使用JavaScript通过SDK进行monitor-query的client认证报错问题
AADSTS90002: Tenant 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' not found. Check to make sure you have the correct tenant ID and are signing into the correct cloud. Check with your subscription administrator, this may happen if there are no active subscriptions for the tenant.
171 1
|
API 开发工具 网络架构
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
152 0
【Azure Developer】使用Python SDK去Azure Container Instance服务的Execute命令的疑问解释
|
监控 关系型数据库 MySQL
PowerShell 脚本编写 :自动化Windows 开发工作流程
PowerShell 脚本编写 :自动化Windows 开发工作流程
695 0
|
数据安全/隐私保护
【Azure Entra ID】使用PowerShell脚本导出Entra ID中指定应用下的所有用户信息
在Azure Entra ID中,需要导出一个Application 下的用户信息, 包含User的创建时间。
299 0