当需要通过代码的方式执行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]$arg1, [string]$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 Commandhttps://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

【Azure Developer】调用SDK的runPowerShellScript方法,在Azure VM中执行PowerShell脚本示例的更多相关文章

  1. 在WebBrowser中执行javascript脚本的几种方法整理(execScript/InvokeScript/NavigateScript) 附完整源码

    [实例简介] 涵盖了几种常用的 webBrowser执行javascript的方法,详见示例截图以及代码 [实例截图] [核心代码] execScript方式: 1 2 3 4 5 6 7 8 9 1 ...

  2. 【Azure Developer】VS Code运行Java 版Azure Storage SDK操作Blob (新建Container, 上传Blob文件,下载及清理)

    问题描述 是否可以用Java代码来管理Azure blob? 可以.在代码中加入azure-storage-blob依赖.即可使用以下类操作Azure Storage Blob. BlobServic ...

  3. 【Azure Developer - 密钥保管库 】使用 Python Azure SDK 实现从 Azure Key Vault Certificate 中下载证书(PEM文件)

    问题描述 在Azure Key Vault中,我们可以从Azure门户中下载证书PEM文件到本地. 可以通过OpenSSL把PFX文件转换到PEM文件.然后用TXT方式查看内容,操作步骤如下图: Op ...

  4. Linux中执行shell脚本的4种方法总结

    bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...

  5. Linux中执行shell脚本的4种方法

    bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...

  6. 每天一个linux命令(62):sh命令 /Linux中执行shell脚本的4种方法总结

    bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...

  7. Linux中执行shell脚本命令的4种方法总结

    bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...

  8. 自动化测试中执行JS脚本方法封装

    执行JS脚本方法封装: class JavaScript(Base): def execute_javascript(self, js): """执行 JavaScrip ...

  9. Linux 中执行Shell 脚本的方式(三种方法)

    Shell 脚本的执行方式通常有如下三种: (1)bash script-name 或者 sh script-name:(2)path/script-name或者./script-name:(3)so ...

随机推荐

  1. MySQL命名、设计及使用规范

    本文转载自MySQL命名.设计及使用规范 导语 最近在看MySQL相关的内容,整理如下规范,作为一名刚刚学习MySQL的菜鸟,整理的内容非常的基础,中间可能涉及到有错误的地方,欢迎批评指正,看到有错误 ...

  2. 【commons-pool2源码】_pre JMX

    目录 一.定义 二.demo 三.JMX在commons-pool2中的应用 一.定义 JMX(Java Management Extensions) 简单来说JMX技术提供了一套轻量的标准化的资源管 ...

  3. 别找了,这可能是全网最全的鸿蒙(OpenHarmony)刷机指南

    目录: 1. 配置编译环境 2. 编译HarmonyOS源代码 3. 烧录HarmonyOS 4.下载文中资源 5.作者文章合集 摘要:相信很多同学都玩过鸿蒙(HarmonyOS)了,不过估计大多数同 ...

  4. 主键策略+mybayisPlus自动增长

    主键策略: 1.自动增长 有一点小缺陷:例如当一张表里的数据过于庞大时我们会进行分表操作,若是用自动增长策略,那么除了第一张表外的每一张表都必须知道上一张的表的的最后ID值.这个操作便会造成效率的变低 ...

  5. sql注入和union all关联查询的学习总结

    1.后台从页面取值进行sql查询时最好不要直接拼,如下代码: String sql = "SELECT wo.* " + " from push_command pu & ...

  6. 基于docker部署skywalking实现全链路监控

    一.概述 简介 skywalking是一个开放源码的,用于收集.分析,聚合,可视化来自于不同服务和本地基础服务的数据的可观察的平台,skywalking提供了一个简单的方法来让你对你的分布式系统甚至是 ...

  7. localforage indexedDB如何使用索引

    简单介绍下localForage.localForage 是一个 JavaScript 库,通过简单类似 localStorage API 的异步存储来改进你的 Web 应用程序的离线体验.它能存储多 ...

  8. 如何进BAT,有了这个篇面试秘籍,成功率高达80%!!(附资料)

    多年前自己刚来北京找工作的时候,面了一个星期 面了七八家公司才拿到一个offer.而上次跳槽面了不到10家公司基本全过而且都给到了期望的薪资,本来自己在面试前没想到能够这么顺利,回想起来还是自己准备的 ...

  9. rabbitmq如何保证消息可靠性不丢失

    目录 生产者丢失消息 代码模拟 事务 confirm模式确实 数据退回监听 MQ事务相关软文推荐 MQ丢失信息 消费者丢失信息 之前我们简单介绍了rabbitmq的功能.他的作用就是方便我们的消息解耦 ...

  10. Java数据类型拓展

    public class Demo03 { public static void main(String[] args) { //整数拓展: 二进制0b 十进制 八进制0 十六进制0x int i = ...