Tuesday, 11 July 2017

Using PowerShell to grep

PowerShell is not Unix of course, but nevertheless, it does have a useful cmdlet to emulate the very useful Unix grep command. This is achieved by the Select-String (finds text in strings and files) cmdlet.

In order to learn more about PowerShell and grep, have a read of Grep, the PowerShell way. It's an excellent article on a comparison between the two. When you read the article, you'll see reference to sls. This is just an alias for Select-String which saves you having to type out the cmdlet name in full.



PS> Get-Alias sls

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           sls -> Select-String
 
I use Select-String myself from time to time but never seem to remember the best way of using it. This article serves as an aide-memoire.


See also


Grep, the PowerShell way
https://communary.net/2014/11/10/grep-the-powershell-way/

Select-String (finds text in strings and files)
https://msdn.microsoft.com/en-us/powershell/reference/5.0/microsoft.powershell.utility/select-string



Keywords: unix grep sls select-string search text file

Sunday, 15 January 2017

Loading a PowerShell assembly

From time to time I write a PowerShell program which makes use of the System.Windows.Forms Namespace. As the documentation reminds us “The System.Windows.Forms namespace contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system”.

In order to make use of this namespace, the relevant assembly needs to be loaded. Up until now I’ve been loading the assembly with the .NET Framework class:

[System.Reflection.Assembly]:: LoadWithPartialName ("System.Windows.Forms") | Out-Null
[System.Reflection.Assembly]:: LoadWithPartialName ("System.Drawing") | Out-Null

Use of the "Assembly" class is discouraged as this API is now obsolete so I now use the "Add-Type" cmdlet:

Add-Type -AssemblyName "System.Windows.Forms";
Add-Type -AssemblyName "System.Drawing";

Loading the assembly with the name alone doesn’t take into account any versions. So, if you wish to load an assembly with a particular version, a different syntax of the command will be required. For the scripts I’m writing, this hasn’t given me a problem although I guess I may have to think about this issue sometime in the future.




Keywords: load powershell assembly