【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());
注意:
- 在获取 azure对象时,需要通过AAD认证。并且当前使用的认证有权限操作所选择的虚拟机(VM)。获取认证信息部分参考博文 “使用Java代码启动Azure VM(虚拟机)”
- 如PowerShell脚本中需要传入参数,则必须在脚本中进行声明,如:param([string]$arg1, [string]$arg2 ),然后通过scriptParameters对象传入。
- 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
【Azure Developer】调用SDK的runPowerShellScript方法,在Azure VM中执行PowerShell脚本示例的更多相关文章
- 在WebBrowser中执行javascript脚本的几种方法整理(execScript/InvokeScript/NavigateScript) 附完整源码
[实例简介] 涵盖了几种常用的 webBrowser执行javascript的方法,详见示例截图以及代码 [实例截图] [核心代码] execScript方式: 1 2 3 4 5 6 7 8 9 1 ...
- 【Azure Developer】VS Code运行Java 版Azure Storage SDK操作Blob (新建Container, 上传Blob文件,下载及清理)
问题描述 是否可以用Java代码来管理Azure blob? 可以.在代码中加入azure-storage-blob依赖.即可使用以下类操作Azure Storage Blob. BlobServic ...
- 【Azure Developer - 密钥保管库 】使用 Python Azure SDK 实现从 Azure Key Vault Certificate 中下载证书(PEM文件)
问题描述 在Azure Key Vault中,我们可以从Azure门户中下载证书PEM文件到本地. 可以通过OpenSSL把PFX文件转换到PEM文件.然后用TXT方式查看内容,操作步骤如下图: Op ...
- Linux中执行shell脚本的4种方法总结
bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...
- Linux中执行shell脚本的4种方法
bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...
- 每天一个linux命令(62):sh命令 /Linux中执行shell脚本的4种方法总结
bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...
- Linux中执行shell脚本命令的4种方法总结
bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...
- 自动化测试中执行JS脚本方法封装
执行JS脚本方法封装: class JavaScript(Base): def execute_javascript(self, js): """执行 JavaScrip ...
- Linux 中执行Shell 脚本的方式(三种方法)
Shell 脚本的执行方式通常有如下三种: (1)bash script-name 或者 sh script-name:(2)path/script-name或者./script-name:(3)so ...
随机推荐
- es初步搭建
1.es tar包传至linux上 并解压 tar -zxvf elasticsearch-7.4.0-linux-x86_64.tar.gz 2.新建用户 useradd xxxname passw ...
- webpack + vuecli多页面打包基于(vue-template-admin)修改
转: webpack + vuecli多页面打包基于(vue-template-admin)修改 遇见的问题TypeError: Cannot read property 'tap' of undef ...
- HDOJ-2087(KMP算法)
剪花布条 HDOJ-2087 本题和hdoj-1686相似,唯一不同的是这里的子串一定要是单独的.所以在确定有多少个子串时不能用前面的方法.而是在循环时,只要找到一个子串,i就不是++,而是+=子串的 ...
- hiho一下 第195周 奖券兑换[C solution][Accepted]
时间限制:20000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi在游乐园中获得了M张奖券,这些奖券可以用来兑换奖品. 可供兑换的奖品一共有N件.第i件奖品需要Wi张奖券才能兑换到, ...
- C#扩展方法的一分钟小例子
扩展方法是静态方法,是类的一部分,但没有在类的源代码中,就像一个补丁 首先创建一个静态类,然后创建一个静态方法,重点是静态方法的参数 public static class xExtension { ...
- Spring MVC获取请求参数的其中两张方式
1 @RequestParam 从请求地址获取参数 例如 username=xxxx 2 @PathVariable 从请求路径获取参数 例如 /req/{123}
- Codeforces Round #574 (Div. 2) D1. Submarine in the Rybinsk Sea (easy edition) 【计算贡献】
一.题目 D1. Submarine in the Rybinsk Sea (easy edition) 二.分析 简单版本的话,因为给定的a的长度都是定的,那么我们就无需去考虑其他的,只用计算ai的 ...
- 13、Script file 'E:\Anaconda Distribution\Anaconda\Scripts\pip-script.py' is not present.
pip-script.py文件缺失问题 问题: Script file 'E:\Anaconda Distribution\Anaconda\Scripts\pip-script.py' is not ...
- 此博客使用的CSS样式详解!
此博客使用的CSS样式详解! 页面使用的博客园模板为:LuxInteriorLight,可以在博客皮肤里找到. 页首屏蔽广告代码 <script>console.log("顶部标 ...
- 基于react hooks,zarm组件库配置开发h5表单页面
最近使用React Hooks结合zarm组件库,基于js对象配置方式开发了大量的h5表单页面.大家都知道h5表单功能无非就是表单数据的收集,验证,提交,回显编辑,通常排列方式也是自上向下一行一列的方 ...

