Tag Archive for powershell

Changing Powershell console background colours

In my current gig the guys in charge of the build scripts had a “brilliant” idea (<- please see the sarcasm in the last sentence): change the colour of the Powershell console depending of the build status (red is bad, green is good).

The problem is that the new screen colours of your beloved console remain like that after the build, and I don’t like it. Well…

((Get-Host).UI.RawUI).BackgroundColor = “Black”

And text foreground:

((Get-Host).UI.RawUI).ForegroundColor = “Gray”

Sweet, no more red console in my days Smile

Conditional command execution in Powershell

Something very usual in Bash (and also in the old Cmd) is the conditional execution of commands, I mean, in the same line we execute a command after the other but only if the execution of the previous command success (or fail!). In Bash or Cmd is something like this:

command1 && command2

That line of code will execute command2 only if command1 succeed. Another common option is:

command1 || command2

It will execute command2 even if command1 fails. Well, looks like there is no elegant way to do the same in Powershell (as version 2, maybe in Version 3!) but we can do the same in Powershell using –and and –or

(command1) –and (command2)

(command1) –or (command2)

See you next time…

Getting a list of committers with Mercurial and Powershell

A few days ago I need to create a list of committers for a Mercurial repository from the command line (don’t ask me why). Thanks God Powershell is always near to help us in so trivial tasks like that.

First, we can get a list of committers from a Mercurial repository using just the mercurial log command with a simple template:

hg log --template ‘{author}n’

Now is when powershell magic appears, let’s just order that list using our friend Sort-Object commandlet:

hg log --template ‘{author}n’ | sort-object

Yeah, now we have a sorted list of authors in a repository! now is time to eliminate duplicates to get the list of unique commiters, for this task we have our friend Get-Unique Powershell Commandlet:

hg log –template ‘{author}n’ | sort-object | unique

Easy Smile

Eliminando directorios de Subversion (.svn) desde la línea de comandos

Subversion es un excelente sistema de control de versiones centralizado (VCS) de código abierto ampliamente utilizado alrededor del mundo no sólo por los desarrolladores sino también por diversas personas que lo usan para mantener un control de cambios en sus documentos varios.

Es común para un usuario de Subversion utilizar el famoso cliente TortoiseSVN para manejar sus directorios de trabajo actuales conectados a un repositorio de Subversion. Como algunos se habran percatado, Subversion crea directorios “ocultos” .svn donde contiene la metadata necesara para trabajar de forma desconectada al repositorio, a veces estos directorios pueden llegar a ser un poco “irritantes” y necesitamos deshacernos de ellos. Recientemente un amigo me llamó con el siguiente problema:

Tengo un problema, el repositorio original no existe, por lo tanto no puedo hacer el “export” de TortoiseSVN de mi repositorio para deshacerme de los directorios .svn, necesito enviarle el código fuente a un cliente pero no quiero enviarle los .svn, ¿cómo hago para deshacerme de ellos? la estructura de directorios es muy compleja por lo que navegar uno a uno y quitarlos es un poco tedioso.

Es ahí cuando sale a la luz nuestro viejo amigo la línea de comando, no es nada que un simple script de Cmd o PowerShell en Windows no pueda resolver. Comencemos con el viejo y ya casi obsoleto Cmd:

for /r %%f in (.svn) do rd /s /q "%%f"

En PowerShell es un poco más complejo, pero igual se puede lograr :)

get-childitem -Include .svn -Recurse -force | Remove-Item -Force –Recurse

Obviamente, cualquiera de los dos comandos deben correrse en el directorio que queremos limpiar.

Saludos!

UPDATE: mi amigo jfroma me sugiere el uso de SVN Export para lograr lo mismo, bueno, recordemos que SVN Export es una operación conectada de Subversion, eso indica que debemos tener conexión al repositorio para efectuarla. Como expongo en mi caso, mi amigo no tiene acceso al repositorio original (para ser exacto según me contó fue borrado), he ahí porqué no podemos usar Export y debemos recurrir a otras “técnicas” tibetanas para lograrlo.

Libro gratuito de PowerShell

Powershell es el super versátil y útil sucesor del infame Cmd en Windows. Este esta disponible para Windows XP, Windows 2003 Server, Windows Vista (como un download) e incluído en Windows 2008 Server. De hecho, Windows 7, Windows 2008 Server R2 y Windows Vista SP2 vendrán con PowerShell V2 el cuál incluye significantes cambios y mejoras en cuanto al poder disponible en la línea de comando.

Para aquellos que quieren comenzar a usar Powershell y explotarlo al máximo, Keith Hill (Powershell MVP) ha convertido su columna “Effective Powershell” en un libro gratuito descargable. Pueden bajarlo de aquí.

Saludos!