当前位置:网站首页>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 weekly replay] 302 weekly 20220717
- Connected graph (union search set)
- Transplant Wu Enda's deep learning 01 machine learning and neural network second week neural network basic programming homework elective homework to pycharm
- 6G smart endogenous: technical challenges, architecture and key features
- 过拟合与欠拟合
- Model comparison of material inventory management between sap ECC and s4hana material
- After summarizing the surface based knowledge of the database
- SSM uses POI to export data to excel
- Pytoch and weight decay (L2 norm)
- Satellite network capacity improvement method based on network coding
猜你喜欢
随机推荐
(一)了解MySQL
ENVI_ Idl: use the inverse distance weight method to select the nearest n points for interpolation (bottom implementation) and output them to GeoTIFF format (the effect is equivalent to the inverse di
【手写数字识别】基于Lenet网络实现手写数字识别附matlab代码
Four methods of traversing key value in map
空天地海一体化网络体系架构与网络切片技术
8.固定收益投资
Connected graph (union search set)
SVN学习
vulnhub inclusiveness: 1
input number 純數字輸入 限制長度 限制 最大值
人大、微软等提出InclusiveFL:异构设备上的包容性联邦学习
(1) Learn about MySQL
2022/7/14
Custom complex logic verification during adding and modifying -2022 new project
ThreadLocal变量使用及原理
Svn learning
虚拟化排错概论
2022/7/15
PowerCLI 脚本性能优化
[in vivado middle note ILA IP core]

![[leetcode weekly replay] 302 weekly 20220717](/img/38/446db9b4755f8b30f9887faede7e95.png)






