Posts

Showing posts with the label powershell

Powershell One Liners

Instead of making a post every time I stumble upon a cool powershell one liner, I'll combine them all in this post. If you have a better one liner for my tasks, please comment. Kill a process by name (In this case Jenkins).  Get-Process | ? {$_.Name -like 'JenKins' }  | Stop-Process Delete all Duplication Downloads (I usually run it first without the del paramaters)  dir  -r  | ? {$_.Name -like '(1)' }  | del Powershell 3, Where/ForEach hack  - allowing you to specify properties sans an anonymous expression.  dir  -r  | ?  Name -like '(1)'  Restart Explorer (often auto-hide of taskbar gets stuck, restarting explorer fixes it.) Get-Process | where name -eq explorer  |kill ; explorer Find Who's hogging memory  Get-Process | sort "VM" -Des | Select-Object -first 10 Set current time  forward 4 hours  set-date ((get-date) + [TimeSpan]::FromHours(4.0)) Get my son's age in weeks  ((g...

Powershell in Real Life: Fixing an MP3 Album I downloaded

Powershell has some quirks, but all in all is awesome. Here's an example: Today I downloaded an album from the internet... PS C:\Users\idvor_000\Downloads\music> dir Directory: C:\Users\idvor_000\Downloads\music Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 1/20/2013 11:47 AM 8648447 01-Loreena_McKennitt-The_Book_Of_Secrets-Prologue.mp3 -a--- 1/20/2013 11:48 AM 12194913 02-Loreena_McKennitt-The_Book_Of_Secrets-The_Mummers_Dance.mp3 -a--- 1/20/2013 11:47 AM 12026448 03-Loreena_McKennitt-The_Book_Of_Secrets-Skellig.mp3 -a--- 1/20/2013 11:49 AM 20341141 05-Loreena_McKennitt-The_Book_Of_Secrets-The_Highwayman.mp3 -a--- 1/20/2013 11:49 AM 10037007 06-Loreena_McKennitt-The_Book_Of_Secrets-La_Serenissima (1).mp3 -a--- 1/20/2013 11:47 AM 10037007 06-Loreena_McKennitt-The_Book_Of_Secrets-La_Serenissima.mp3 -a--- 1/20/2013 11:51 AM 16985204 07-L...

Powershell script to enable windows to capture localhost traffic in wireshark

If you want to understand why the following scripts work read this post . Otherwise just paste the following into an elevated powershell window: Setup windows networking to allow localhost capturing in wireshark: # Find the network configuration that has the default gateway. $defaultAdapter = Get-WMIObject Win32_NetworkAdapterConfiguration | ? {$_.DefaultIPGateway} if (@($defaultAdapter).Length -ne 1) {throw "You don't have 1 default gateway, your network configuration is not supported" } # Route local IP address via the default gateway route add $defaultAdapter.IPAddress[0] $defaultAdapter.DefaultIPGateway Write-Host "Start capturing on localhost by connecting to $($defaultAdapter.IPAddress[0])" Return windows networking to normal configuration: # Find the network configuration that has the default gateway. $defaultAdapter = Get-WMIObject Win32_NetworkAdapterConfiguration | ? {$_.DefaultIPGateway} if (@($defaultAdapter).Length -ne 1) {throw "Y...

Batch to Powershell: dir /s

I often go looking for a file in batch, aka c:\Program Files (x86)>dir /s fsi* Volume in drive C has no label. Volume Serial Number is 8EDE-D64E Directory of c:\Program Files (x86)\Microsoft F#\v4.0 03/19/2010 02:02 PM 230,216 Fsi.exe 09/30/2009 08:08 PM 158 Fsi.exe.config 2 File(s) 230,374 bytes Unfortunately this doesn't 'just work' in powershell. A quick search on the internet shows in powershell 'dir /s' becomes 'dir -r', but the following doesn't work either: PS C:\Program Files (x86)> dir -r fsi* PS C:\Program Files (x86)> What's going on? Let's check the help: PS C:\Program Files (x86)> help dir NAME Get-ChildItem SYNOPSIS Gets the items and child items in one or more specified locations. SYNTAX Get-ChildItem [[-Path] ] [[-Filter] ] [-Exclude ] [-For ce] [-Include ] [-Name] [-Recurse] [-UseTransaction] [ ] Get-ChildItem...

The joy's of batch - Delayed Expansion

  If you can, skip batch and move strait to powershell. If you don't believe me, maybe this blog post will change your mind. In batch %ErrorLevel% is how you know if the last command succeeded: C:\>echo %ERRORLEVEL% 0 It turns out if you set a variable that doesn't exist, this sets error code to 1. So C:\>set DONKEYRIDING Environment variable DONKEYRIDING not defined C:\>echo %ERRORLEVEL% 1 Makes sense, batch isn't that bad you think. Now here's a pop quiz - What will you get when you run this batch file? C:\>type foo.bat if NOT "BATCH"=="OBVIOUS" ( echo %ERRORLEVEL% set DONKEYRIDING echo %ERRORLEVEL% ) I"ll run it for you: C:\>foo.bat C:\>if NOT "BATCH" == "OBVIOUS" ( echo 0 set DONKEYRIDING echo 0 ) 0 Environment variable DONKEYRIDING not defined 0 C:\> Not what you thunk huh? Maybe error level wasn't set - lets check C:\>echo %ERRORLEVEL% 1 What the...

Better Certificate Management in Powershell via CertificateHelper

If you’ve read my previous post here , you know powershell can do some basic certificate management via the certificate provider. However, the certificate provider has some limitations. The certificate provider can’t create,delete,copy or import/export certificates. This annoyed me so I’m creating a powershell module called CertificateHelper that will provide these missing features. So far the module implements: New-Certificate Remove-Certificate  CertHelper can be found on codeplex . You install it like this: (You must have hg installed) PS C:\>cd $home\Documents\WindowsPowerShell\Modules PS C:\Users\igord\Documents\WindowsPowerShell\Modules> hg clone https://hg01.codeplex.com/certificatehelper destination directory: certificatehelper requesting all changes adding changesets adding manifests adding file changes added 5 changesets with 8 changes to 4 files updating to branch default 4 files updated, 0 files merged, 0 files removed, 0 files unresol...

How do you thumbprint a certificate?

You often use thumbprints to find certificates, but what is the thumbprint?  The thumbprint is the hash of the certificate. In the case of the CLR’s X509Certificate2 class, the thumbprint is the SHA1 hash of the certificate. If you want to compute the thumbprint of a certificate yourself it’s pretty simple: function get-CertThumbprint ($cert) { $sha = new-object System.Security.Cryptography.SHA1CNG $hashOfRawBytesOfCertificate = $sha.ComputeHash($cert.RawData) ( $hashOfRawBytesOfCertificate| % {"{0:X}" -f $_} ) -join "" } PS cert:\LocaLMachine\My> dir Directory: Microsoft.PowerShell.Security\Certificate::LocaLMachine\My Thumbprint Subject ---------- ------- 3BCA8A25A071300BD177E4C73135E54FA830039A CN=STS 08766D8B3DCDE5D633ED06AB1CB4DF4CCAECA533 CN=localhost PS cert:\LocalMachine\My> $cert = get-item 08766D8B3DCDE5D633ED06AB1CB4DF4CCAECA533 PS cert:\LocalMachine\My> $cert...

Powershell is dynamically scoped, and that will confuse you.

Lets start with an example, as the concept of dynamic scoping is a big string for most programmers. Python Program x = 5 def printX(): print x def setAndprintX(): x=7 printX() printX() setAndPrintX() printX() Output From Python 5 5 5 Powershell Program $x = 5 function printX() { echo $x } function setAndprintX() { $x=7 printX } printX setAndprintX printX Output From Powershell 5 7 5 What is this dynamic scoping? Most programs use static, also called lexical, scoping because it's easy to understand. You figure out what is in scope by looking at the source code. In the python example, the only value of x in scope is the global value of x. By contrast, powershell uses dynamic scoping, in this model, you lookup up variables at runtime based on a scope stack. Each time you call a function you create a new scope, and copy all values from the parent scope into it. In the powershell example, when printX is called fr...

Using wireshark to trace localhost traffic on windows.

(If you don’t care why this works and just need a recipe, switch to this post ) Capturing network packets on localhost doesn't work on windows. The reason is windows doesn't send loopback traffic far enough down the networking stack for wireshark to see it. To make sniffing work on localhost you can route your ip traffic to your default gateway. I'll walk you through this, and along the way you'll see: netcat - telnet on steroids (nc.exe) tshark - command line network sniffer from the wireshark package. powershell jobs - background jobs from the shell! Step 1 - launch the server as a background job (Woohoo powershell) PS C:\Users\igord> $server = start-job { \bin_drop\nc -L -p 8082 } Step 2 - Make client connection: PS C:\Users\igord> \bin_drop\nc.exe 127.0.0.1 8082 Hello You can see me Step 3: See if we can see anything in tshark on port 8082. C:\Program Files (x86)\Wireshark>tshark -i 4 -R "tcp.port == 8082" Capturing on M...

The Performance of Everyday Things

I've spent much time fixing code optimizations that added no business value (with often matching performance value). Please do not try to make your code faster unless you need to. The way I handle performance issues on my projects: Define acceptable performance. Write my code as simply as possible. Measure performance: against definition, if performance > acceptable - goto DONE. /*Performance not acceptable*/ Profile; Fix as simply as possible; goto Measure. DONE To be explicit: I'm comfortable using slower patterns if they are clear and simple. As soon as I've hit my acceptable performance bar - I'm done. With that out of the way, let me discuss a performance riddle I hit this week. I was wandering through some powershell code that processed slews of objects (over 200K of 'em): $interestingObjects = @() foreach ($object in $inputObjects) { if ($object.IsInteresting) { $interestingObjects += $objects ...