Posts

Showing posts from 2016

PowerShell One-Liner: Get Public IP Quickly and Reliably

Image
Recently, three is a need to obtain the public IP information from the instance(s). While there are many ways, especially using the browser. I'd like to have a reliable and programmatic way. Here we have PowerShell and AWS. Following one-liner processes the result from  Amazon's checkip site  and then convert it into a beautiful System.Net.IPAddress object ready for use. :)

Weekend project: automate end-of-day with PowerShell, Pebble, and Wemo.

Image
Since I started to work from my home office several months ago, I've been enjoying making my work space (a.k.a man cave) the way I want. This weekend, I got a pebble 2 watch and a wemo switch  and explored the fun. ( Before pebble says goodbye.... ) Started by connecting the power bar to the the wemo switch, I could press a button in the app on my phone to turn on everything (monitors, speaker, computer...etc) even on a schedule if I liked. Well, that's okay. But at the end of 2016, I wanted to press less buttons and be able to... just make it happen. Talking into the watch and then turn on/ off my entire stack sounds like a modern and super cool idea! So the journey began. Aside from the hardware, few moving parts were needed: Something orchestrates the sequence of events based on triggers. Something on the pebble that understands my voice command and send it over to the orchestrating tool. Something on my computer that accepts the events and shut itself down. To allow

Retrieving AWS EC2 instance screenshot with PowerShell

Image
Few months ago, Amazon announced the ability to capture and show the console screen of an EC2 instance. It really helps troubleshooting in certain situations. While it is available through the GUI console, one has to explore further with the PowerShell way. ;-) Reading up on the AWS documentation, the AWS PowerShell cmdlet, Get-EC2ConsoleScreenshot , allows us to retrieve the image data. Let's give it a try in the PowerShell console. The result doesn't really look like an image, does it? Worry not, the data is actually a jpeg file encoded in BASE64 format. We just have to convert it back to bytes with the [convert]::FromBase64String() before saving the file. Now, opening up the saved screenshot. Oh well... this doesn't look perfect but good to know. I've put these together in a PowerShell function: Save-EC2consoleScreenshot.  And now that's a pragmatic way to retrieve the EC2 instance screenshot! Feel free to have a look of it on GitHub: Link . Ho

Updating the rdg connection file of the Remote Desktop Connection Manager program.

Image
Since the new job starts few months ago, I've been very busy stepping out my comfort zone and learning new topics: AWS, Puppet and Linux. :) Pretty exciting journey but I miss PowerShell a lot... Anyway, I'd like to share this small PowerShell script with you. You can find the project here:  UpdateRDG on GitHub . It updates the Remote Desktop Connection Manager  connection file which sometimes is handy for switching between environments. (Yes yes, we all know RDP is not a server management tool... but slowly we'll pay off the technical debt.) The file itself is an XML document so not too hard to work with PowerShell. Here is an example of the rdg file created using the GUI for demo purpose. The <server>....</server> block defines the server node information. So our goal is adding the server blocks based on whatever input there is. The input can be Hyper-V, VMware, Azure, AWS or even Excel spreadsheet. Here I query Hyper-V for the vm information and yo

PowerShell way to parse Windows Update log: Get-PSWindowsUpdateLog

Image
Windows Update, not a fun thing to work with when you need find details in the WindowsUpdate.log. The log has a ton of great information but really hard for with human eyes. Again with PowerShell, there is an opportunity to transform the text based log file into PowerShell Custom Ojects. Which will make exporting, filtering, and reporting much easier. Here is the function I build to fetch and parse WindowsUpdate.log. This function works for local or remote computers given that you have permission to the remote system. Check out the screenshots below, they look similar but you can do lots more with the parsed object. Like, pipe them to Out-GridView. :-) Before: After: The function is here: * *

Get-TaskList, a PowerShell wrapper for tasklist command

Image
Today I was helping my desktop support folks troubleshooting workstation performance issues remotely. It appeared that the target Windows computers had no PowerShell enabled. As the result Get-Process couldn't connect. We then fall back to the good old command: tasklist . The text based output, however, was less easy to process. Maybe I'm just spoiled by PowerShell's object based pipeline but look look look how 'pretty' it is. I then spent some Friday afternoon time writing this PowerShell cmdlet: Get-Tasklist . It wraps around the built-in tasklist command and then parses the text-based output to object-based. Next time, troubleshooting with non-PS going to be much easier. With the Out-GridView , you get an elegant way to work with legacy systems remotely. Hope this might help you at some point. Here is the code:

Converting markdown files to PDFs

Image
While it is awesome reading the PowerShell DSC documentations in nicely markdown, formatted webpage, I am still emotionally attached to the printed paper in the digital age. (Rubbing my sore eyes) So task is to find a way converting those markdown formatted docs in to PDFs and then print them. I found a couple resources available for this task: GitPrint.com PanDoc Here is my recommendation: Use GitPrint.com whenever you can for smaller batches of conversion. It's easy to use with a javascript based bookmark for page redirection. (The Chrome plug-in is no longer available) As for PanDoc, I installed it along with the MikTex, LaTex's implementation on Windows, for PDF converstion. First, the installers together are over 200 MB download and install. Second, about 70% of the files were converted fine (no colour syntax like GitPrint though) but the rest came out with formatting issues. It could still be valuable when converting a large batches though. You *may* save some ti

PowerShell: Loop through a collection, N objects at a time

Recently I want to loop through a collection of objects and do something with each object. Well, that's a common task in PowerShell. The problem using a loop is it does one object at a time and flow control is limit in this fashion. So it can launch the work to all objects very fast using jobs or slow when iterating though each single one and wait. I want something in the middle. So I spent some time and wrote something that can be used to provide the flow control while enabling multiple running executions. It can be useful in the scenario of upgrading the vmware tools in the vm guests where Invoke-Command doesn't suit the purpose fully. The goal is to go through a collection of objects and:     - Perform some work to the collection in smaller batches of  N     - The batch work should be sent to background for "parallel" execution     - Have a way to check the status of each object in the batch work     - If completed work(s) is found, pull next object(s) fr

PowerShell codes in PowerCLI's Invoke-VMScript

Image
PowerCLI has a nice Invoke-VMScript cmdlet that runs powershell (by default) in a guest via vmware tools. It is very handy in certain cases. For example, servers in isolated or inaccessible  network. Also using it during the server provisioning process sometimes can be helpful. You can use it to invoke a single cmdlet. Just pass what you want to run in the guest to the -ScriptText syntax (enclosed in " or '). Invoke-VMScript will redirect the output from guest to your PowerShell session. Invoke-VMScript -VM 'guestVM' -ScriptText "Get-Process" -GuestCredential $guestcred What if you have a couple cmdlets to run? Separating them with semi-colon works fine. Invoke-VMScript -VM 'guestVM' -ScriptText "Get-Process ; Get-Service" -GuestCredential $guestcred Things start to get interesting/ tricky when you have special charters ($, ", '). For example, say you want to output some text on the screen or trying to do some stu

Get a list of printer queues from Active Directory

Image
I was helping colleague earlier this week to clean up the printer queues in the Active Directory. Well, the challenges comes to get a meaningful list of printer queues. Sure you can use the GUI to search in ADUC but that's doesn't give you much details to work with. If you have Windows 8 or Server 2012 and above, then the Get-Printer PowerShell comlet is the best bet. But, what about if I don't have them in production? Try this one liner that fetchs all the print queues from your active directory and save them in to the $printer variable. Get-ADObject -LDAPFilter '(ObjectClass=PrintQueue)' -Properties * -OV printer The AD object is very rich with properties that can be filtered and reported on. It will help your filtering much easier.

Script: Auto-install OMI and PowerShell DSC on CentOS7 Linux

While following the lab instruction for the DSC on Linux, I found the procedure outdated and not fully applicable to the latest build of PowerShell DSC for Linux. (I used CentOS7 in the lab) With the helpful resources on the internet, I was able to piece together a script that works with the current version. (OMI 1.0.8-4 and PowerShell DSC for Linux 1.1.1) The bash script assumes you have the  omi-1.0.8.4.packages.tar.gz downloaded and saved to the same location as the script. It also worth noting following changes: OMI now availalbe as rpm and deb packages.  Linux Development Tool does not seem to be required   OMI daemon is now named: omid wget doesn't work with OMI's website. Manual download is required. If you happen to know how to make wget work with OMI's site, please kindly share it. It's going to make the process much smoother. :-) Reference: https://collaboration.opengroup.org/omi/documents.php?action=view&gdid=34607 https://github.

A case with psEdit

Image
While using the very cool  PowerShell Gallery MVA module  provided by Jeffery Snover to learn about the DSC, I was interested in how the magic was done and took a further look into the module. One command used in there was psEdit  for opening up the script files in the PowerShell ISE. The command could be documented better and Mike F Robbins has a great blog post about its usage. If you run the command without any parameter and press enter without providing anything at the prompt, ISE will open what ever file is in the current directory. Have a look of the screenshot below. Interesting. I then tried to see what psEdit really is with following command: With the command, we can see what the psEdit function is doing: The function wants a mandatory input and then it will iterate through the files in that location and open them in the ISE. The problem comes when you don't pass anything via the variable and not specifying while prompted, the $filenames variable is the

A few random things about Win10, .Net 3.5 and PowerShell

Image
One day in the past week, my colleague and I were trying to get .Net Framework 3.5 installed on Windows 10 test machines. It was required for several applications. (Exactly what we wanted to find out from the test.) Interesting enough, the .Net 3.5 is now a "Feature on Demand v2" item in windows 10. That means the "feature" is by default not part of the image but would be loaded via Windows Update (not WSUS). My colleague suggested using the dism command to complete the install and it worked fine. I thought to myself, how is that going to be done the PowerShell way? So the exploration began. I started  Get-WindowsFeature that I used often on servers. But on Windows 10 I got the red stuffs. Turns out the Get-WindowsFeature cmdlet is part of the ServerManager module which is not included in the Windows 10. (Doh!) Thanks to the intellisense pointed out there's another cmdlet that may or may not help: Get-WindowsOptionalFeature . With further checki

PowerShell tip: Using the -OutVariable

Image
It is very often that I want to run a cmdlet to do something. For example, Get-Process to check the current running process. Cool, I have a list of the running process. So how about saving it to a variable so we can capture and maybe use it later? Sure then we can do the: $p = Get-Process. This is fine when the cmdlet takes a short time to complete and PowerShell does not show you anything until you put the variable back in. In our case $p or $p | Out-Default Say you write an advanced function that scans the remote file system. The process could take a couple cups of coffee before before returning some results. Or you just want to see the results as it moves. Easy! Just add the common parameter: -OutVariable VariableName  (no $ in front of the variable name). PowerShell will display and store the output object at the same time. Meaning you can see the progress on the fly and use the result later. For example: Get-Process -OutVariable p It's a simple trick that wil

Get-ChildItem -Include and -exclude with multiple file extensions

Image
On day I was writing a PowerShell script to streamline my photography workflow. I would like to copy the photo files including the RAWs from memory card to the hard drive, and put them into the the folders named by the date of shooting. I decided to filter early in the Get-ChildItem so it only checks the photo related files* and skip others. The Get-ChildItem has the -Include syntax suit the purpose well. However, there was a tiny rock in the way: getting the multiple file extensions work with the -include parameter. In the shell, following worked fine: But when the '*.jpg, *.cr2' was saved in to a variable, $list, for the script, Get-ChildItem returned nothing. Saving them into an array worked for the script. See the list below. Well, the full help of Get-ChildItem did tell me that it wants String[] for the -include parameter. But what interested me was why? I then ran the tracing in each scenarios. Please have a look of each screenshot below. In scenari

Getting the help descriptions in Group Policy settings with PowerShell

Image
As a windows administrator, I deal with group policy frequently. From time to time, I forget what a specific setting mean. I'm glad that Microsoft is including the help/ description with the group policy templates so I can view details by opening up the setting in GPMC. See the highlighted section in the screenshot: That's a good and easy when checking only few settings and only me, myself and I are involved. Chances are, I have to review and discuss the group policy settings with others on my team. (Or the security people. You know they love these 'controls'...) In the meeting, the scrolling and clicking within GPMC seems to easily nullify the caffeine in everyone's brain within five minutes. Sometimes I wish there is a simple group policy report that shows the configured settings AND their descriptions so I can email it to people before the meeting! Well, I did try once to copy-paste the content from Microsoft's Group Policy Reference . But I just felt

Windows Version Number

Here is a list of Windows version number that can be used in WMI query/ filtering within Group Policy. Or they can be used together with Get-WmiObject/ Get-CimInstance cmdlet when needed. For example, you can perform a quick scan for a list of computer whether from AD or other sources. Operating system Version number Windows 10 10.0* Windows Server 2016 Technical Preview 10.0* Windows 8.1 6.3* Windows Server 2012 R2 6.3* Windows 8 6.2 Windows Server 2012 6.2 Windows 7 6.1 Windows Server 2008 R2 6.1 Windows Server 2008 6 Windows Vista 6 Windows Server 2003 R2 5.2 Windows Server 2003 5.2 Windows XP 64-Bit Edition 5.2 Windows XP 5.1 Windows 2000 5 Source: MSDN – Operating System Version

Learning PowerShell as a Windows Admin

Image
Today I would like to share the PowerShell learning resources that have been tremendously helpful to me as an IT Pro/ Windows Admin. Hope you will find some of these useful to you as well. This post will be updated as I continue learning. Before jumping into the resources, allow me to share some thoughts with you. I started using the PowerShell v3 as a replacement for good old faithful command line and the gui. Honestly, the change wasn't that smooth during the first few weeks. I had to refer to the Get-Help command and Google a lot even for a recursive directory copy. You might ask now "That sounds... a lot of work. Does it really worth the time learning?" True, things already work (and work fine) in the cmd and gui world. You know how to finish a task in somewhat reasonable time. However, how often do you want to share an exciting solution with your team and ended not doing it because you just have no appetite to capture all the 17 screenshots, highlight the 'NE

ValidateCount and pipeline

Image
One day I used the ValidateCount() in a PowerShell script for simple throttling. (List 1.) When testing, I found the script didn't throw the expected red stuffs and actually accepted more piped objects than specified in the ValidateCount(). See figure below. It took all six arguments when ValidateCount(0,5) set to accept maximum 5. Moments after, I realized that the pipe passes one object at a time so the validation would always return true. The $_ , that's one object and one object only. Or have a look of the debug result showen. Figure below shows the ValidateCount() works as expected when using the parameter.The kind of validation will have to also happen within the script/ advanced function when values are expected from the pipeline. List 1.

PowerShell ISE: A couple useful keys

Image
When I started learning PowerShell a couple years ago, I was annoyed a bit about the ISE. Mainly because I had to frequently move my hand back and forth between the keyboard and the trackball. Why? Because I was trying to validate every PowerShell command along the script and the cursor had to be move between the script pane and the console. And one day these magic key combinations showed up gloriously! (Well, I probably wasn't looking careful enough...) : Ctrl + I : move cursor to the Script Pane Ctrl + D: move cursor to the Console These look simple but they do help with my scripting that I'm less interrupted. Try them now in PowerShell ISE if you haven't already. It'll definitely help enhancing your scripting experience. Do you have any tips like this you can share? Please feel free to post a comment.

A PowerShell Pomodoro clock.

Image
Pomodoro is a time management technique I use for protecting my eyes. While  Tomighty  is a great Pomodoro tool, it doesn't work very nicely in multi-monitor set-up. Since I always have PowerShell open, it makes sense to have it do the timing for me. Things I want it to do: Have a progress bar for the Pomodoro clock (default: 25min) Have another progress bar for the break  (default: 5min) A pop-up window (and grab the focus) at the end of each period. Have option for audio feedback I had the flow kinda ready but didn't really know how how to handle the pop-up the way I wanted: a pop-up that grabs the focus. Thanks to Sonam Rastogi mentioning in the recent  Blog post  about using the VisualBasic MessageBox and the 'ShowModal' value. Here is the script module, PoshPomodoro , and you can run the Start-Pomorodo once imported. A couple screenshot here: Screenshot 1. Progress bar Screenshot 2. Pop-up And below is the script for your easy reference. What

Using PowerShell to scan for Cryptowall encrypted files

During the post clean-up in a Cryptowall incident, a challenge is to identify the files encrypted so those can have top priority. Having someone to open every single file and see which one breaks? It can be done but you don’t really want go that direction. With a good backup system in place already prior the Cryptowall incident, PowerShell is the perfect tool to do the heavy lifting to point out those affected files so you can focus the restoration effort at the right spots. The short script below is used in a previous incident to help a customer. In the case, the encrypted files had same file header, +O)T.  To speed up the scan,  Get-Content  is used with  -TotalCount 1  to retrieve only the beginning of the files. PowerShell is the perfect tool to do this. Please note that the pattern could be different among different variants of Cryptowall or CryptoLocker. But you can gather the pattern once you unwillingly have the encrypted files. $path = "C:\" #Path to scan