What does PowerShell have anything to do with Python? Good question, I personally need to work in the Windows environment and most of my colleague do too. I can automate via PyWin32, but I can't pass that script on to my colleague unless they have PyWin32. The fact that PowerShell is pre-installed on Windows is a great way to write a simple Python script to generate PS file, then pass it on to colleague and users.
For example, referencing the example in chapter 10 of the book, here is a quick Python script to create a spreadsheet, populate the first column with interface name, and second column with incremental IP addresses:
*** Begin of Script ***
import subprocess, os
# Create the PowerShell file for Excel
f = open("createExcel.ps1", "w")
f.write('$xl = New-Object -ComObject Excel.Application\n')
f.write('$xl.Visible = $true\n')
f.write('$workbook = $xl.Workbooks.Add()\n')
f.write('$sheet1 = $workbook.Worksheets.Item(1)\n')
f.write('$sheet1.Cells.Item(1,1) = "Interface"\n')
f.write('$sheet1.Cells.Item(1,2) = "IP"\n')
# Write 10 interfaces
j = 1
k = 1
for i in range(2,12):
f.write('$sheet1.Cells.Item('+ str(i) +',1) = "Interface1/'+ str(j)+'"\n')
f.write('$sheet1.Cells.Item('+ str(i) +',2) = "10.0.0.'+ str(k)+'/31"\n')
j += 1
k += 2
# Invoke Script
startPS = subprocess.Popen([r'C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe',
'-ExecutionPolicy', 'Unrestricted', './createExcel.ps1'], cwd=os.getcwd())
result = startPS.wait()
*** End of Script ***
This will produce the following spreadsheet on your screen:
Here is the review itself as appear on Amazon:
This should be a must have for people who wants to automate in the Windows environment, IMHO. In less than 200 pages (minus appendix), the books is full of useful concepts, examples, and things you can use right away. This book is also modern in terms of the focus on RESTFul objects, JSon object types, while covering the basics of PoewrShell. The fact that PowerShell is pre-installed on modern Windows machines makes learning this language a worthwhile investment. Let's face it, doesnt matter how much you like Mac/Linux/___, a lot of your users run on Windows.
I particurly enjoyed the chapter on writing Domain Specific Language with GraphViz (Chapter 9) since I am a big fan of GraphViz and have been writing Python scripts to work with GraphViz, now I have a new tool in the bag to pass it on to folks who do not want to install Python just to work with GraphViz.
Chapter 10 alone is worth the purchase price of the book, if you need to work with Excel and only have a few hours to read the book, I would recommend skipping from Chapter 3 the Dime Tour directly to Chapter 10. It will teach you valuable lessons on working with Exel, creating workbooks, worksheets and populating information in the worksheet.
This book changed my perspective on PowerShell and automation on Windows. Now I like my workmachine just a little more.