Planet
When your PowerShell cmdlet doesn’t return anything, use -PassThru
The other day I was mounting an ISO in Windows 8 via the Mount-DiskImage command. Since I was mounting the disk image in a script, I needed to know the drive letter it was mounted to so the script could access the files contained within. However, Mount-DiskImage was not returning anything. I didn’t want to go through the hack of listing drives before and after I mounted the disk image, or explicitly assigning the drive letter. Both would leave me open to race conditions if another drive was mounted by another process while my script ran. I was at a loss for what to do.
Then, I remembered the -PassThru parameter, which I am quite fond of using with Add-Type. See certain cmdlets, like Mount-DiskImage, and Add-Type don’t return pipeline output by default. For Add-Type, this makes sense. You rarely want to see a list of the types you just added, unless your exploring the classes in a DLL from the command like. However, for Mount-DiskImage, defaulting to no output was a questionable decision IMHO.
Now in the case of Mount-DiskImage, -PassThru doesn’t return the drive letter. However, it does return an object that you can pipe to Get-Volume which does return an object with a DriveLetter property. To figure that out, I had to ask on stackoverflow.
tl;dr: If your PowerShell cmdlet doesn’t return any output, try -PassThru. If you need the drive letter of a disk image mounted with Mount-DiskImage, pipe the output through Get-Volume.
For a more in depth treatise of -PassThru, check out this script guy article by Ed Wilson(blog|twitter).
Getting the Drive Letter of a disk image mounted with WinCdEmu
In my last post, I talked about mounting disk images in Windows 8. Both Windows 8 and 2012 include native support for mounting ISO images as drives. However, in prior versions of Windows you needed a third party tool to do this. Since I have a preference for open source, my tool of choice before Windows 8 was WinCdEmu. Today, I decided to see if it was possible to determine the drive letter of an ISO mounted by WinCdEMu with PowerShell.
A quick search of the internet revealed that WinCdEmu contained a 32 bit command line tool called batchmnt.exe, and a 64 bit counterpart called batchmnt64.exe. These tools were meant for command line automation. While I knew there would be no .NET libraries in WinCdEmu, I did have hope there would be a COM object I could use with New-Object. Unfortunately, all the COM objects were for Windows Explorer integration and popped up GUIs, so they were inappropriate for automation.
Next I needed to figure out how to use batchmnt. For this I used batchmnt64 /?.
C:\Users\Justin>"C:\Program Files (x86)\WinCDEmu\batchmnt64.exe" /? BATCHMNT.EXE - WinCDEmu batch mounter. Usage: batchmnt <image file> [<drive letter>] [/wait] - mount image file batchmnt /unmount <image file> - unmount image file batchmnt /unmount <drive letter>: - unmount image file batchmnt /check <image file> - return drive letter as ERORLEVEL batchmnt /unmountall - unmount all images batchmnt /list - list mounted C:\Users\Justin>Mounting and unmounting are trivial. The /list switch produces some output that I could parse into a PSObject if I so desired. However, what I really found interesting was batchmnt /check. The process returned the drive letter as ERORLEVEL. That means the ExitCode of the batchmnt process. If you ever programmed in a C like language, you know your main function can return an integer. Traditionally 0 means success and a number means failure. However, in this case 0 means the image is not mounted, and a non zero number is the ASCII code of the drive letter. To get that code in PowerShell is simple:
$proc = Start-Process -Wait ` "C:\Program Files (x86)\WinCDEmu\batchmnt64.exe" ` -ArgumentList '/check', '"C:\Users\Justin\SQL Server Media\2008R2\en_sql_server_2008_r2_developer_x86_x64_ia64_dvd_522665.iso"' ` -PassThru; [char] $proc.ExitCodeThe Start-Process cmdlet normally returns immediately without output. The -PassThru switch makes it return information about the process it created, and -Wait make the cmdlet wait for the process to exit, so that information includes the exit code. Finally to turn that ASCII code to the drive letter we cast with [char].
Setting the Visual Studio TFS diff and merge tools with PowerShell
I recently wrote this script to let me quickly change the diff and merge tools TFS uses from PowerShell. I plan to make it a module and add it to the StudioShell Contrib package by Jim Christopher (blog|twitter). For now, I share it as a gist and place it on this blog.
The script supports Visual Studio 2008-2012 and the following diff tools:
- The built-in tools
- WinMerge
- KDiff3
- SemanticMerge
- BeyondCompare Standard
- BeyondCompare Pro
New Video! – The Yellow Box – “Chasing the Squid”
The Yellow Box performs “Chasing the Squid” at Matchless, Brooklyn, NY on October 24, 2012. Charlie Labs: keyboards & vocals, Chris Merlo: bass, Rich Moscatelli: drums. (c) Labs/Merlo/Moscatelli. Filmed by Don Becker.
Dear Congress...
Dear Congres,
Stop.
Seriously, just FUCKING STOP.
I read this one today and just couldn't believe it guys:
A bipartisan group of senators will introduce legislation to stop the FAA from closing any control towers to meet its sequester cut requirements. "The Protect Our Skies Act, which is co-sponsored by a bipartisan group of 18 Senators, would prohibit the Department of Transportation (DOT) from closing any air traffic control towers, including those that are operated by the FAA," says a news release issued by Sen. Jim Inhofe (R-Okla), one of the bill's sponsors.
(Via AvWeb) So, basically in your infinite stupidity you all went ahead and created a law that imposes budget cuts so draconian that they say it's inconcievable that it woud ever be allowed to go into effect, then when you pull the trigger on this massive bazooka pointed at the nation's head and realize essential services are getting cut as a result your answer (rather than doing something sane like passing a reasonable budget) is to start legislating agencies into an impossible situation: Cut your budget, but don't cut any of the services you provide. Frankly I'm not a huge fan of the tower closings (a bunch of towers at fields I would like to visit would be going away under the FAA's plan, and I think it would turn the airspace over Connecticut into a marvelous knot), but I'd rather the FAA make those cuts rather than wiping out more center and approach controller positions, eliminating maintenance inspectors, or countless other options with potentially more devastating safety implications than closing 150 towers. So my dear esteemed congresscritters, I would like to know two things:- Exactly what economics program did you all flunk out of?
- Exactly when did you all become experts on the national airpsace system?
I hate to be the bearer of bad news, but the FAA is a service agency, and those services are (a) essential, and (b) provided by people. If you want them to cut their budget they're going to have to cut the least essential of those services, and that - I'm sorry to say - pretty much means "Towers". The other option is to make deeper cuts to approach control and centers, which at least in my little corner of the airspace system are already working above capacity. You also seem to think you know better than the FAA how to run the nation's airspace. First you stomp your feet like petulant children and DEMAND that the FAA integrate unmanned aerial vehicles (drones) into the airspace, now you pitch a hissy and try to micromanage the way they deal with this budget crisis you idiots created. Frankly - you're full of it, and messing with things you don't understand, so PLEASE just fucking STOP - you're making it worse! Just sit on your hands and resist the urge to try to legislate anything until your term is up and we can replace you with something more useful (like perhaps a stuffed wombat. No love, Me.
Political Correctness, Sensitivity, and Censorship in the Information Age
So anyone who knows me knows that I hate censorship in any form. I'm the guy that wears the "I Read Banned Books" shirt, and considers it to be a required reading list (yeah I'm still working my way through it myself).
So you can imagine I was just a little bit miffed when I found out that @violetblue's talk at BSides SF was apparently cancelled because it offended someone's delicate sensibilities (particularly since they can't have possibly known the content of said talk as it HADN'T BEEN GIVEN YET). I was even a little miffed at @BSidesSF for basically caving to PC-Pressure (unjustly as it turns out, so I'm glad I didn't lay into them), but I just quietly commented on the WTFery of such censorship and moved on...
...until tonight when I read @violetblue's blog post on what went down.
I fully expect this blog entry will piss some people off. Frankly I don't care. Try not to get any wharrgarbl on me if you feel the need to respond.
Continue reading "Political Correctness, Sensitivity, and Censorship in the Information Age"
Codeigniter Updates to 2.1.2
Nested If’s the root of all evil
Ok so the title is an over exaggeration but I need a simple way to express how much I HATE when I see code with dozens of closing brackets because the developer was trying to fix the Unexpected $end error. Simple control structures not only help to keep code readable, it will also help in performance because you can escape code blocks with ease. To illustrate, below is an example of a function I have seen in my adventures in programming:
- function isAuthorized($resource)
- {
- $allowed = false;
- if ($_SESSION['loggedin'] == 1) {
- $user = $_SESSION['username'];
- if (!empty($user)) {
- $result = mysql_query('SELECT * FROM user_roles WHERE user = "' . $user . "'");
- if ($result) {
- while ($resArray = mysql_fetch_array($result)) {
- if ($resource == $resArray['role']) {
- $allowed = true;
- }
- }
- } else {
- throw new Exception('No valid results');
- }
- } else {
- throw new Exception('User name is invalid');
- }
- }
- return $allowed;
- }
Lets just ignore the security hole and performance issues with the MySql query, just look at the structure starting with the while loop. What if that user had 100 roles assigned and the role we wanted is the 1st record? We set $allowed to true on the 1st iteration then spend 99 iterations doing nothing. We can either break the loop or just add the $allowed to the condition. I suggest adding the $allowed to the loop which will clearly state that we are looking for $allowed.
- while (($resArray = mysql_fetch_array($result)) && !$allowed) {
- if ($resource == $resArray['role']) {
- $allowed = true;
- }
- }
Ok a little better we now have a chance of breaking the loop if we find the resource early. We can still optimize this function but returning true or false based off our conditionals:
- function isAuthorized($resource)
- {
- if (!$_SESSION['loggedin'] == 1) {
- return false;
- }
- $user = $_SESSION['username'];
- if (empty($user)) {
- throw new Exception('User name is invalid');
- }
- $result = mysql_query('SELECT * FROM user_roles WHERE user = "' . $user . "'");
- if (!$result) {
- throw new Exception('No valid results');
- }
- while ($resArray = mysql_fetch_array($result)) {
- if ($resource == $resArray['role']) {
- return true;
- }
- }
- return false;
- }
We gain a many advantages here. First PHP will not have to allocate memory for the $allowed and $user variables since they will not get called if the user is clearly not logged in. We also gain greater op-code usage by not having the parse read in else statements. The big advantage to this is how easy it is to read and make a change. Lets say we wanted to add a check for if the users session expired, by following the 1st example we would have to add a whole new block as follows:
- function isAuthorized($resource)
- {
- $allowed = false;
- if ($_SESSION['loggedin'] == 1) {
- if (date_add($_SESSION['loggedin'], '+30 min') < new DateTime("now")) {
- $user = $_SESSION['username'];
- if (!empty($user)) {
- $result = mysql_query('SELECT * FROM user_roles WHERE user = "' . $user . "'");
- if ($result) {
- while ($resArray = mysql_fetch_array($result)) {
- if ($resource == $resArray['role']) {
- $allowed = true;
- }
- }
- } else {
- throw new Exception('No valid results');
- }
- } else {
- throw new Exception('User name is invalid');
- }
- } else {
- throw new Exception('Session has expired');
- }
- }
- return $allowed;
- }
With our cleaned up structure we just add the following lines like so:
- function isAuthorized($resource)
- {
- if (!$_SESSION['loggedin'] == 1) {
- return false;
- }
- $user = $_SESSION['username'];
- if (empty($user)) {
- throw new Exception('User name is invalid');
- }
- if (date_add($_SESSION['loggedin'], '+30 min') < new DateTime("now")) {
- throw new Exception('Session has expired');
- }
- $result = mysql_query('SELECT * FROM user_roles WHERE user = "' . $user . "'");
- if (!$result) {
- throw new Exception('No valid results');
- }
- while ($resArray = mysql_fetch_array($result)) {
- if ($resource == $resArray['role']) {
- return true;
- }
- }
- return false;
- }
As we can see keeping the code structured helps us understand what a function is supposed to be doing, improves our opcode performance, and helps keep making changes to a function that much easier
New Look
Well as you can see, MANCHUCK has a new look. I switched over to Word Press because really, it takes a long time to build your own blog from scratch (which is what I was hoping to do with the old site). It took about a day to install and configure the new look. Hope you all enjoy
Shout out to Themetation for creating this theme. Thanks for helping save me some time with messing around with CSS