当前位置:网站首页>Powercli script performance optimization
Powercli script performance optimization
2022-07-19 11:05:00 【51CTO】
Or decided to write about this topic ,Powershell Not my strong point , Most of the content of this article also comes from other blogs , Think of it as a knowledge collection .
Probably 10 Go to do a project around the month , I see that the information left by my former colleagues contains a lot PowerCLI Script for , Some people go to batch configuration , There are batch information collection , So I took time to sort out a suit for myself , But there is always a problem that cannot be solved well :Powershell Scripts are executed sequentially , In the face of large quantities of data collection, the speed is very slow , It usually costs 1 It takes more than hours to collect information , So I spent some time trying to tune the performance , Trim the optimization experience .
0x00. About PowerCLI And Powershell
Powercli yes VMware A series of products Microsoft Powershell modular , Through these modules , It can be used very quickly Powershell Yes vCenter、NSX、SRM Wait for resources to perform batch operations , For example, batch modification ESXI Host configuration 、 List virtual machines, etc . foreign vSphere Administrators use PowerCLI A lot , The community has accumulated a lot of PowerCLI Script , As long as you can think of operations, you can find relevant resources .
0x01. Optimization principle
At present, I have used three optimization methods :
1、 Optimize the code , Improve the operation efficiency of single line and single code
2、 Execute commands asynchronously
3、 Multithreading
The following chapters explain each part one by one
0x02. Optimize the code
Check where the bottleneck is
Powershell There's an order called Measure-Command , With this command, you can view the running time of a piece of code , Its usage is as follows :
for example , test Get-Process Running time of :

Move the filter to the left
A general optimization method is as follows : If you want to collect a lot of data first , Data should be filtered as early as possible , To reduce the size of this part of data , Then conduct other secondary filtration . Or according to the original author , Move the filter to the left of the code .
for example :
Want to get-process obtain svchost Of this process CPU Information , It can be realized through the following two sets of code :
The performance comparison is as follows :

It can be seen that the former runs more than twice as fast as the latter , If you are performing a large number of tasks , This little gap adds up to a big gap .
PowerCLI Code performance optimization
The author of PowerCLI A similar test was carried out on the script, and it was found that with different writing methods , The speed of code execution varies greatly , Here's an example : Get the cluster information of the host :

Another example is right ESXi Statistics of the number of local disks :
although esxcli It seems that there are more steps , More code , But use esxcli It's much more efficient than Get-scsilun The efficiency of :

When encountering a lot of code , You need to test the speed difference caused by different writing methods repeatedly , Choose the best .
The efficiency of assignment is much higher than that of executing a query
In addition, the test found that , The operation speed of all assignments is lower than 1ms, So such operations do not affect performance . Specific to code optimization , We should try our best to reduce vCenter Interaction . For example, get the cluster where the host is located :
Direct assignment is much faster than executing a query . The execution speed of the three commands is as follows :

0x03. Asynchronous task
PowerCLI There are quite a few operations that can be used -RunAsync Parameters , After adding this parameter , This command only passes vCenter Create tasks , Does not monitor the performance of tasks .
When performing some batch tasks , For example, virtual machine startup and shutdown 、 Virtual machine creation can be very useful .
0x04. Using multithreading
Powershell There are many ways to create multithreaded tasks , Because of time, I only tested and used PSJob , In addition to that Runspace and RSJob , If you are interested, you can study it yourself .
PSJob Conditions of use
If you want to use PSJob Create multithreaded tasks , The preconditions are :
- Powershell 3.0 Above version
- The memory of the host and CPU Enough
- Ensure that the program can run in multiple threads
Be careful : Before multithreading , You need to ensure multithreaded runtime , There will be no conflict between multiple threads . For example, multiple processes writing files at the same time will conflict , But reading a file at the same time is no problem .
PSJobs Of cmdlet Built in Microsoft.PowerShell.Core in , You can use the following command to view this cmdlet Command below :

PSJobs share 8 States , The most commonly used ones are as follows :
- Completed :Job Already completed , Can get job Output information , perhaps job Can be safely removed .
- Running:Job Running , Can't stop ( Unless forced to stop ), Unable to get output information .
- Blocked:Job Running , But the system prompts you to enter information before continuing .
- Failed: perform Job An error occurred when .
start-job Start task
Use start-job You can create a new task , If you use measure-command Check the task execution time , You can see that it is far less than the actual execution time of the command .

get-job obtain job state
adopt get-job Commands can be viewed Job Operating condition .


In the above example , If the task is still running , be State Show Running, If the operation is completed ,State by Completed.
In addition, after running HasMoreData The value is False, It means this Job No output .
The following figure is a screenshot of other States , See Command Column .

receive-job Get task output
adopt receive-job Commands can be viewed Job Output information of ( Use write-output Output ), Note that once output Job There will be no more such information in , Therefore, it is suggested to wait Job Complete information collection after completion .

Parameter passing
Default start-job Production tasks cannot use globally defined variables , need ArgumentList Pass variables .
Operation after task execution
When doing some batch collection , We go through start-job To create a large number of Job, But this is just a task , We also need to read and process data after the task is completed , Here I use for Check periodically Job Has it been completed , Read data in batches only after waiting for completion , The specific operation is as follows :
Output optimization
As mentioned above, it can be found in job Internal use Write-Output Output information ,job For external use receive-job To receive information ,
During the actual test, I found Write-Output For a relatively large variable, the efficiency is very low ( For example, I try to output Get-vmhost Result , There was no response for dozens of minutes ), Low to doubt life , So the best way is to Job Complete the filtering within .
for example :
And
The following commands are only added when outputting select name,Version , The execution time is only 7 second , And the previous program hasn't responded for dozens of minutes .
PSJob be applied to PowerCLI
In the application of PowerCLI when , Discover each job Must be connected separately vCenter, Fortunately, this operation can write the password into the code , No interaction :
After being handled by the above means , Originally collected 100 It takes more than ten minutes for the information of each host , Now it is reduced to more than two minutes :

But the corresponding , The computer fan began to ring wildly ..

Reference material :
https://adamtheautomator.com/powershell-multithreading/#runspace-vs-psjobs
边栏推荐
猜你喜欢

LeetCode 2331. Calculate the value of Boolean binary tree (tree traversal)

ue4对动画蓝图的理解

一个报错, Uncaught TypeError: ModalFactory is not a constructor

ROS duplicate name

Win10 install Apache Jena 3.17

Svn learning

Win10的环境变量配置

Second classification learning is extended to multi classification learning

web安全入门-部署Snort开源IDS/IPS系统

Journal日志与oplog日志的区别
随机推荐
最大半连通子图(tarjan缩点+拓扑排序+dp最长链)
今日睡眠质量记录79分
Qt 两个重载QListWidget控件对象实现selectitem drag拖拽
How much money can you make by inventing flash memory? This is a Japanese dog blood story
【手写数字识别】基于Lenet网络实现手写数字识别附matlab代码
Vérification logique complexe personnalisée lors de l'ajout et de la modification - 2022 nouvel élément
input number 純數字輸入 限制長度 限制 最大值
Transplant Wu Enda's deep learning 01 machine learning and neural network second week neural network basic programming homework elective homework to pycharm
SVN学习
6G全域融合网络展望
[handwritten numeral recognition] handwritten numeral recognition based on lenet network with matlab code
关于hping打流测试工具
Tencent cloud server uses image to deploy WordPress personal website!
Google Earth engine - Hansen global forest change v1.8 (2000-2020) forest coverage and forest loss data set
基于“7·20郑州特大暴雨”对空天地一体化通信的思考
Summary of port mirroring methods with VDS or NSX under vSphere
Mysql 自增id、uuid与雪花id
MySQL query error
Explanation of tree chain dissection idea + acwing 2568 Tree chain dissection (DFS sequence + mountain climbing method + segment tree)
NVIDIA uses AI to design GPU: the latest H100 has been used, which reduces the chip area by 25% compared with traditional EDA