Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

9/1/11

Powershell Asynchronous Download String

WebClient DownloadStringAsync
Powershell Register-ObjectEvent
PSEventArgs Properties
# - get webclient
$webClient = new-object net.webclient

# - register event handler for DownloadStringCompleted event
#   action script block is event handler code, show string DownloadStringCompletedEventArgs.Result
register-objectEvent $webClient downloadStringCompleted e1 {write-host $args[1].result}  #positional input params

# - begin asynchronous download string
#   event handlers will execute when download is complete
$webClient.downloadStringAsync("http://www.expressionsoftware.com")

# - list event subscriptions
get-eventSubscriber  #output #SubscriptionId  : 1
                             #SourceObject    : System.Net.WebClient
                             #EventName       : downloadStringCompleted
                             #SourceIdentifier: e1
                             #Action          : System.Management.Automation.PSEventJob
                             #SupportEvent    : False
                             #ForwardEvent    : False
                             #HandlerDelegate :

# - list jobs
get-job | fl  #output  #Id           : 1
                       #Name         : e1
                       #Command      : write-host $args[1].result
                       #State        : Running
                       #JobStateInfo : Running
                       #HasMoreData  : True
                       #Finished     : System.Threading.ManualResetEvent
                       #InstanceId   : 010f31f4-e8d2-4742-a782-79057faefebf
                       #Module       : __DynamicModule_a48149c1-5a56-4172-bc68-473ec7c83119
                       #StatusMessage:   #Location
                       #ChildJobs    : {}  #Output, Error, Progress, Verbose, Debug, Warning

# - register another handler, multiple event handlers supported, named input params
register-objectEvent -inputObject $webClient `
                     -eventName downloadStringCompleted `
                     -sourceIdentifier e2 `
                     -action {write-host ("async event at {0}`nevent handler source identifier: {1}`n{2}" -f ($event.timeGenerated.tostring("HH:mm:ss")), $event.sourceIdentifier, $args[1].result)}

# - unregister events
unregister-event -subscriptionId 1
unregister-event -sourceIdentifier e2
get-eventsubscriber -force | unregister-event -force  #unregister all events

# - synchronous download string
$webClient.downloadString("http://www.expressionsoftware.com")

Powershell asynchronous download file with WebClient DownloadFileAsync

1/17/11

Powershell Appcmd IIS 7 Command Line Tool

Appcmd Objects
APPapplications
APPPOOLapplication pools
BACKUPserver configuration backups
CONFIGgeneral configuration sections
MODULEserver modules
REQUESTHTTP requests
SITEvirtual sites
TRACEworking with failed request trace logs
VDIRvirtual directories
WPworker processes

$appcmd = "c:\windows\system32\inetsrv\appcmd.exe"
&$appcmd /?  #help

#list all sites
&$appcmd list site
&$appcmd list site /xml        #use xml to get attribute names
&$appcmd list site /text:name  #use text to get attribute values

&$appcmd list site /text:name | sort  #ps sort

#list all app pools
&$appcmd list apppool

#list app pool names
&$appcmd list apppool /text:name

#list app pool .net framework version
&$appcmd list apppool /text:managedRuntimeVersion

#list all w3wp.exe worker processes, use to debug match process id to iis website
&$appcmd list wp

#list started sites, running
&$appcmd list site /state:started

#list stopped app pools
&$appcmd list apppool /state:stopped

#list all virtual directory/physical paths
&$appcmd list vdir

#list site bindings ipaddress
(&$appcmd list site prod /text:bindings).split(",")

#list response headers
&$appcmd list config prod /section:httpProtocol

#add response headers
&$appcmd set config prod /section:httpProtocol /+"customHeaders.[name='foo', value='bar']"

#delete response headers
&$appcmd set config prod /section:httpProtocol /-"customHeaders.[name='foo']"
&$appcmd set config prod /section:httpProtocol /-"customHeaders.[name='x-powered-by']"

#output site configuration text
&$appcmd list site prod /text:*

#list website virtual directory/physical path
&$appcmd list vdir prod/

#stop website
&$appcmd stop apppool prod; &$appcmd stop site prod

#start website
&$appcmd start apppool prod; &$appcmd start site prod

#stop all running sites
&$appcmd list site /state:started /xml | &$appcmd stop site /in  

#stop all running app pools
&$appcmd list apppool /state:started /xml | &$appcmd stop apppool /in

#list mime types
&$appcmd list config prod /section:system.webServer/staticContent

v11.09

12/5/10

SQL Server Command Line Utility - SqlCmd

http://msdn.microsoft.com/en-us/library/ms162773.aspx
path: c:\program files\microsoft sql server\100\tools\binn\sqlcmd.exe

powershell examples
- execute command-line query, connect using SQL Server Authentication
  &sqlcmd -S SERVER -d DB -U LOGIN -P 'PASSWORD' -q 'select getdate()'

- execute command-line query, connect using SQL Server Authentication, password prompt
  &sqlcmd -S SERVER -d DB -U LOGIN -q 'select getdate()'

- execute command-line query, connect using Windows Authentication
  &sqlcmd -S SERVER -d DB -E -q 'select getdate()'
    
- execute sql script file
  &sqlcmd -S SERVER -d DB -E -i x:\sql\script1.sql

- execute all sql script files in a folder
  gci x:\sql\ *.* | %{ &sqlcmd -S SERVER -d DB -E -i $_.fullname }
  
- exit or quit

- command-line options
  [-? show syntax summary]
  [-a packetsize]
  [-A dedicated admin connection]
  [-b On error batch abort]
  [-c cmdend]
  [-C Trust Server Certificate]
  [-d use database name]
  [-e echo input]
  [-E trusted connection]
  [-f <codepage> | i:<codepage>[,o:<codepage>]]
  [-h headers]
  [-H hostname]
  [-i inputfile]
  [-I Enable Quoted Identifiers]
  [-k[1|2] remove[replace] control characters]
  [-l login timeout]
  [-L[c] list servers[clean output]]
  [-m errorlevel]
  [-N Encrypt Connection]
  [-o outputfile]
  [-p[1] print statistics[colon format]]
  [-P password]
  [-q "cmdline query"]
  [-Q "cmdline query" and exit]
  [-r[0|1] msgs to stderr]
  [-R use client regional setting]
  [-s colseparator]
  [-S server]
  [-t query timeout]
  [-u unicode output]
  [-U login id]
  [-v var = "value"...]
  [-V severitylevel]
  [-w screen width]
  [-W remove trailing spaces]
  [-x disable variable substitution]
  [-X[1] disable commands, startup script, enviroment variables [and exit]]
  [-y variable length type display width]
  [-Y fixed length type display width]
  [-z new password]
  [-Z new password and exit]

11/15/10

PInvoke SetWindowText PowerShell Script

P/Invoke examples for the SetWindowText Windows API Function.
These examples set the window text/title for Notepad.exe.
#get notepad window handle
$notepad = get-process notepad
$notepad.mainWindowHandle //100000, intptr structure

$pinvoke::setWindowText($notepad.mainWindowHandle, "a")

#auto-convert int to intptr
$pinvoke::setWindowText(100000, "b")

#create intptr
#out-null to suppress bool result
$pinvoke::setWindowText((new-object intPtr(100000)), "c") | out-null

$pinvoke::setWindowTextCustomWrapper(100000)

Implementation #1 simply exposes the SetWindowText method, the member definition uses C# syntax.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition @'

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool SetWindowText(IntPtr hwnd, String lpString);

'@

Implementation #2, same as #1 but written on one line.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition '[DllImport("user32.dll", CharSet = CharSet.Auto)]public static extern bool SetWindowText(IntPtr hwnd, String lpString);'

Implementation #3, SetWindowText is private, add custom wrapper method.
$pinvoke = add-type -name pinvoke -passThru -memberDefinition @'

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool SetWindowText(IntPtr hwnd, String lpString);

public static void SetWindowTextCustomWrapper(IntPtr handle)
{
string customText = string.Format("handle: {0}", handle);
SetWindowText(handle, customText);
}

'@


11/3/10

Setting Windows Path Environment Variable with PowerShell

#get all environment vars
gi env:
(gi env:) | sort name

#get path value
gi env:path
(gi env:path).value
(gi env:path).value.split(';')
(gi env:path).value.split(';') | sort

#set path value (note the "$" prefix)
$env:path = 'c:\windows;c:\windows\system32;'

5/11/10

Checkout One File from SVN

A Slik SVN/PowerShell workaround for the SVN missing feature - checking out just a few select files instead of the entire folder.
$svnFolder = 'https://dev.co.com/svn/project1'
$workingFolder = 'c:\temp\svn'
$file = 'foo.cs'

#checkout just the folder, checkout depth "only this item"
&svn checkout $svnFolder $workingFolder --depth=empty

#method 1: cd to working folder, update using file name
cd $workingFolder
&svn update $file

#method 2: update using file full path name
$file = join-path $workingFolder $file
&svn update $file

5/8/10

PowerShell Registry Script

Four variations for reading registry keys.
HKLM and HKCU are PowerShell drives for HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER registry hives.

Windows startup entries.
getRegistryV1 hklm:\software\microsoft\windows\currentversion\run
getRegistryV1 hkcu:\software\microsoft\windows\currentversion\run
function getRegistryV1($key)
{
  $key = get-item $key
  $values = get-itemProperty $key.psPath  #gp alias for get-itemProperty
  $values
}

function getRegistryV2($key)
{
  $key = get-item $key
  $values = get-itemProperty $key.psPath
  foreach ($value in $key.property)
  {
    "$value = $($values.$value)"  #subexpression $()
  }
}

function getRegistryV3($key)
{
  $key = get-item $key
  $maxKeyNameLen = ($key.property | %{$_.length} | measure -max).maximum
  $values = get-itemProperty $key.psPath
  foreach ($value in $key.property)
  {
    "{0,-$maxKeyNameLen} = {1}" -f $value, $values.$value  #format left-aligned width
  }
}

function getRegistryV4($key)
{
  $key = get-item $key
  $maxKeyNameLen = ($key.property | %{$_.length} | measure -max).maximum
  $values = get-itemProperty $key.psPath
  $key.property | %{"{0,-$maxKeyNameLen} = {1}" -f $_, $values.$_}  #format left-aligned width
}

5/2/10

Testing String Format in PowerShell

'{0:x2}' -f 10
[string]::format('{0:x2}', 10)
0a

4/19/10

PowerShell List Dates Script

listDates '01-01' 7                       #01-01-2010
listDates '01-01' 7 'M-d'                 #1-1
listDates '01-01' 14 'ddd MM-dd'          #Fri 01-01
listDates '01-01-2011' 30                 #01-01-2011
listDates '01-01' 60 'MMM dd yyyy - ddd'  #Jan 01 2010 - Fri
function listDates($startDate, $daysCount, $format='MM-dd-yyyy')
{
  $startDate = [datetime]$startDate
  0..($daysCount-1) |
    %{
        $startDate.addDays($_).toString($format)  #console - show date
     }
}

4/8/10

PowerShell File Concatenation Script

Concatenates text files into a single file for printing, text-zip-attachments, etc.
File index is included at the top of the output file.
function concatFiles($outFile)
{
  begin
  {
    $date = get-date
    [string[]] $filelist = @()  #empty string array
    $filebreak = '-'*32
  }
  process
  {
    #for process-block vars, append data using +=
    $_.fullname  #or "$_", console - show file name
    $filelist += $_.fullname
    $filedata += "$filebreak`nfile: $_`n"
    $filedata += gc $_.fullname | out-string  #use out-string to restore linebreaks
  }
  end
  {
    $filecount = $filelist.length
    "{0} files" -f $filecount  #console - show file count
    $fileheader = "{0}`n" -f $date.toString('MM-dd-yy HH:mm:ss')
    $fileheader += "concat output file: {0}`n{1} files" -f $outFile, $filecount
    $fileheader            >> $outFile
    $filelist              >> $outFile
    $filedata + $filebreak >> $outFile
  }
}


Concatenate all text files
gci c:\docs\* -inc *.txt -rec | concatFiles c:\temp\out.txt

#powershell console output
C:\docs\file1.txt
C:\docs\file7.txt
2 files

#file output
03-01-11 14:09:22
concat output file: c:\temp\out.txt
2 files
C:\docs\file1.txt
C:\docs\file7.txt
--------------------------------
file: C:\docs\file1.txt
file 1
...
--------------------------------
file: C:\docs\file7.txt
file 7
...
--------------------------------


Concatenate files modified on Jan 1 2011 or later
$files = "*.htm","*.css","*.js"
gci c:\docs\* -inc $files -rec -force -ea silentlycontinue |
  ?{$_.lastwritetime -gt [datetime]'01-01-2011'} | concatFiles c:\temp\out.txt

3/31/10

Insert String Every N Characters

This PowerShell v2 script inserts a string every N characters. The interval is specified using the regex repetition operator, {min,max}.
$a = 'abcdefghijklmnopqrstuvwxyz'
([regex]::matches($a, '.{1,3}') | %{$_.value}) -join ' '
([regex]::matches($a, '.{1,8}') | %{$_.value}) -join '..'
([regex]::matches($a, '.{1}') | %{$_.value}) -join '-'

#output
abc def ghi jkl mno pqr stu vwx yz
abcdefgh..ijklmnop..qrstuvwx..yz
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z

3/22/10

PowerShell Download File Script

This script downloads files asynchronously. It uses the .NET WebClient DownloadFileAsync method.
Note that the download file path must exist.
downloadFile 'http://www.foo.com/foo.iso' 'c:\temp\foo.iso'

function downloadFile($uri, $filename)
{
  $webClient = new-object net.webclient
  $webClient.downloadFileAsync($uri, $filename)
}

2/6/10

PowerShell Asynchronous Background Jobs

PowerShell Background Jobs - MSDN.
Requires PowerShell v2.

Job Cmdlets
start-job
get-job
receive-job
stop-job
start-job {
  #...
}

#with parameters
start-job {param($p1, $p2)
  $p1
  $p2
} -argumentList 'foo', 123

#output
foo
123

#execute N times
start-job {
  1..3 |
    %{
        (get-date).toString('HH:mm:ss')
        sleep 1
     }
}

#output
20:32:51
20:32:52
20:32:53

#execute N times with script block begin-process-end clause
start-job {
  begin
  {
    'begin script...'
  }
  process
  {
    1..3 | %{(get-date).toString('HH:mm:ss'); sleep 1;}
  }
  end
  {
    'end script...'
  }
}

#output
begin script...
20:35:42
20:35:43
20:35:44
end script...

#infinite loop, stop job during sleep interval
start-job {param($sleep)
  while ($true)
  {
    #...

    $now = get-date
    'sleep {0}, {1} - {2}' -f $sleep, $now.toString('HH:mm:ss'), $now.addSeconds($sleep).toString('HH:mm:ss')
    sleep $sleep
  }
} -argumentList 60

#output
sleep 60, 20:41:06 - 20:42:06
sleep 60, 20:42:06 - 20:43:06

2/5/10

Generic Array to String Function

ArrayToString returns an array as a formatted string. This generic function works with arrays of all types.
//C#
using System.Text;

namespace ExpressionSoftware.System
{
    public static class Array
    {
        public static string ArrayToString<T>(T[] array, string format)
        {
            return ArrayToString(array, format, 16);
        }

        public static string ArrayToString<T>(T[] array, string format, int stringBuilderItemCapacity)
        {
            var sb = new StringBuilder(array.Length * stringBuilderItemCapacity);
            foreach (T item in array)
            {
                sb.AppendFormat(format, item);
            }
            return sb.ToString();
        }
    }
}

//F# v1.9.7.8
namespace ExpressionSoftware.System
open System.Text

type Array =
  
  //stringBuilderItemCapacity is an optional int parameter
  static member ArrayToString(array:'a[], format:string, ?stringBuilderItemCapacity:int) =
    
    let stringBuilderItemCapacity =
      match stringBuilderItemCapacity with
        | Some(stringBuilderItemCapacity) -> stringBuilderItemCapacity
        | None -> 16

    let sb = new StringBuilder(array.Length * stringBuilderItemCapacity)
    array |> Array.iter(fun b -> sb.AppendFormat(format, b) |> ignore)
    sb.ToString()

#PowerShell
function arrayToString($array, $format)
{
  $array | %{$result += ($format -f $_)}
  $result
}

Examples
//C#
byte[] bytes = { 0, 1, 255 };
int[] ints = { int.MinValue, -1, 0, 256, int.MaxValue };
float[] floats = { -9.99f, 0f, 3.14159f };
char[] chars = { 'a', 'b', 'c', '1', '2', '3' };
string[] strings = { "xyz", "789" };

Debug.WriteLine(Array.ArrayToString(bytes, "{0}", 3));
Debug.WriteLine(Array.ArrayToString(bytes, "{0} "));
Debug.WriteLine(Array.ArrayToString(ints, "{0} "));
Debug.WriteLine(Array.ArrayToString(floats, "{0} "));
Debug.WriteLine(Array.ArrayToString(chars, "{0}", 1));
Debug.WriteLine(Array.ArrayToString(chars, "{0},", 2));
Debug.WriteLine(Array.ArrayToString(strings, "{0} ", 4));

//F#
let bytes = [|0uy; 1uy; 255uy|]
let ints = [|Int32.MinValue; -1; 0; 256; Int32.MaxValue|]
let floats = [|-9.99f; 0.0f; 3.14159f|]
let chars = [|'a'; 'b'; 'c'; '1'; '2'; '3'|]
let strings = [|"xyz"; "789"|]

Array.ArrayToString(bytes, "{0}", 3) |> (fun s -> printfn "%s" s)
Array.ArrayToString(bytes, "{0} ") |> (fun s -> printfn "%s" s)
Array.ArrayToString(ints, "{0} ") |> (fun s -> printfn "%s" s)
Array.ArrayToString(floats, "{0} ") |> (fun s -> printfn "%s" s)
Array.ArrayToString(chars, "{0}", 1) |> (fun s -> printfn "%s" s)
Array.ArrayToString(chars, "{0},", 2) |> (fun s -> printfn "%s" s)
Array.ArrayToString(strings, "{0} ", 4) |> (fun s -> printfn "%s" s)

#PowerShell
[byte[]]$bytes = 0, 1, 255
[int[]] $ints = [int32]::MinValue, -1, 0, 256, [int32]::MaxValue
[single[]] $floats = -9.99, 0, 3.14159
[char[]] $chars = 'a', 'b', 'c', '1', '2', '3'
[string[]] $strings = 'xyz', '789'

arrayToString $bytes '{0}'
arrayToString $bytes '{0} '
arrayToString $ints '{0} '
arrayToString $floats '{0} '
arrayToString $chars '{0}'
arrayToString $chars '{0},'
arrayToString $strings '{0} '

Output
01255
0 1 255 
-2147483648 -1 0 256 2147483647 
-9.99 0 3.14159 
abc123
a,b,c,1,2,3,
xyz 789 


11/29/09

PowerShell Load Assembly Function

LoadAssembly loads an assembly into the PowerShell session.

Note that unloading an assembly from PowerShell requires closing the PowerShell window, so close the window before trying to rebuild or delete a loaded assembly.
function loadAssembly($file)
{
  [system.reflection.assembly]::loadfile($file) | out-null
}

Example
loadAssembly c:\lib\file.dll

11/22/09

PowerShell SharpZipLib Script

These PowerShell scripts can be used to zip and unzip files.

Zip operates on file lists such as output from the Get-ChildItem cmdlet. You can set the zip file root folder by specifying the leading folder path to remove. The Where-Object cmdlet can be used for advanced filtering. This function does not zip empty folders. See the SharpZipLib wiki for examples of zipping empty folders. Also, this function does not work with files that are locked, such as log files that are being written.

The free SharpZipLib .NET Zip assembly is used for zip functionality. You'll need to download the assembly and load it into PowerShell to run the scripts. Note that after you download or copy the assembly locally, you may have to trust the assembly. To do this, right-click the assembly and trust (unblock) it. Other related info can be found the SharpZipLib wiki.

These PowerShell scripts were tested using SharpZipLib version 0.85.5.
Strong name: ICSharpCode.SharpZipLib, Version=0.85.5.452, Culture=neutral, PublicKeyToken=1b03e6acf1164f73
function zip($zipFile, $leadingFolderPathToRemove)
{
  begin
  {
    $zip = [icSharpCode.sharpZipLib.zip.zipFile]::create($zipFile)
    $zip.beginUpdate()
  
    #add trailing backslash if necessary
    $leadingFolderPathToRemove = (join-path $leadingFolderPathToRemove '\')
  }
  process
  {
    #remove leading folder path from file name
    $file = $_.fullName.remove(0, $leadingFolderPathToRemove.length)
    $zip.add($_.fullName, $file)
  }
  end
  {
    $zip.commitUpdate()
    '{0} files zipped' -f $zip.count
    $zip.close()
  }
}

function unzip($zipFile, $unzipToFolder)
{
  $zip = new-object icSharpCode.sharpZipLib.zip.fastZip
  $zip.extractZip($zipFile, $unzipToFolder, $null)
}

Examples
loadAssembly c:\lib\sharpZipLib\ICSharpCode.SharpZipLib.dll

#zip all files from folder c:\code\web\ into c:\temp\web.zip
gci c:\code\web\* -include *.* -recurse -force | zip c:\temp\web.zip c:\code\web\

#only files modified 11-22-2009 or later
gci c:\code\web\* -include *.* -recurse -force |
where {$_.lastWriteTime -ge [dateTime]"11-22-2009 00:00"} |
zip c:\temp\web.zip c:\code\web\

#exclude files: *.csproj*, *.pdb, *.refresh, *.sln, *.suo
#exclude folders: debug, obj, release, properties
$excludeRegex = '(\.(csproj(.*)|pdb|refresh|sln|suo)$)|(\\(debug|obj|release|properties)(\\|$))'
gci c:\code\web\* -include *.* -recurse -force |
where {$_.fullName -notMatch $excludeRegex} |
zip c:\temp\web.zip c:\code\web\

#unzip c:\temp\web.zip into folder c:\temp\unzip\web\
unzip c:\temp\web.zip c:\temp\unzip\web

11/15/09

PowerShell Find Files Script

FindFiles returns a list of files that contain the search text. The search can be plain text or a regular expression.

This function is similar to using the Select-String cmdlet with the -list switch parameter. The difference is that FindFiles supports searching across line breaks. See the examples that use the "dot matches line breaks" regex pattern (?s).
function findFiles($text)
{
begin
{
$count = 0
}
process
{
$data = [system.io.file]::readAllText($_.fullname)
if ($data -match $text) #if matches at least once...
{
$_.fullname
$count += 1
}
}
end
{
"$count files found"
}
}

Examples
#find files containing "abc"
gci c:\* -include *.txt | findFiles 'abc'

#find files containing "abc" or "xyz"
gci c:\* -include *.txt | findFiles 'abc|xyz'

#find files containing "abc", including across line breaks
gci c:\* -include *.txt | findFiles '(?s)a.*bc|ab.*c'

#find files containing "<abc>" tags, including across line breaks, and empty tags
gci c:\* -include *.txt | findfiles '(?s)<abc>.*</abc>|<abc/>'

8/19/09

Hash Functions

GetHash returns the hash value of a byte array.
GetHashStr returns the hash value of a string.

These functions can use any of the hash classes from the System.Security.Cryptography namespace, e.g. MD5, SHA1, SHA256, SHA512.
//C#
using System;
using System.Security.Cryptography;
using System.Text;

namespace ExpressionSoftware.Security.Crypt
{
    public static class Hash
    {
        public static byte[] GetHash(byte[] bs, Type hashType)
        {
            return HashAlgorithm.Create(hashType.Name).ComputeHash(bs);
        }
        
        public static byte[] GetHashStr(string input, Type hashType)
        {
            byte[] bs = Encoding.UTF8.GetBytes(input);
            return GetHash(bs, hashType);
        }
    }
}

//F# v1.9.7.8
namespace ExpressionSoftware.Security.Crypt
open System
open System.Security.Cryptography
open System.Text

module Hash =
  let GetHash(bs:byte[], hashType:Type) =
    HashAlgorithm.Create(hashType.Name).ComputeHash bs

  let GetHashStr(input:string, hashType:Type) =
    Encoding.UTF8.GetBytes input
    |> (fun bs -> GetHash(bs, hashType))

#PowerShell
function getHash($bs, $hashType)
{
  $hashType::create().computeHash($bs)
}

function getHashStr($inputStr, $hashType)
{
  getHash ([system.text.encoding]::utf8.getBytes($inputStr)) $hashType
}

Examples
//C#
byte[] bs = Encoding.UTF8.GetBytes("foo");
byte[] hash = Hash.GetHash(bs, typeof(SHA1));
Debug.WriteLine(Byte.BytesToString(hash, "{0} "));
11 238 199 181 234 63 15 219 201 93 13 212 127 60 91 194 117 218 138 51  //output

//F#
let hash = Hash.GetHashStr("foo", typeof<SHA1>)
Byte.BytesToString(hash, "{0:x} ")
|> (fun s -> printfn "%s" s)
b ee c7 b5 ea 3f f db c9 5d d d4 7f 3c 5b c2 75 da 8a 33  //output

#PowerShell
$hashType = [system.security.cryptography.SHA1]
$hash = getHashStr 'foo' $hashType
bytesToString $hash '{0:X}'
BEEC7B5EA3FFDBC95DDD47F3C5BC275DA8A33  #output

8/18/09

Bytes to String Function

BytesToString returns a byte array as a formatted string.

02-05-10 This function has been replaced with a generic version - Generic Array to String Function.
//C#
using System.Text;

namespace ExpressionSoftware.System
{
    public static class Byte
    {
        public static string BytesToString(byte[] bs, string format)
        {
            var sb = new StringBuilder(bs.Length * 4);
            foreach (byte b in bs)
            {
                sb.AppendFormat(format, b);
            }
            return sb.ToString();
        }
    }
}

//F# v1.9.7.8
namespace ExpressionSoftware.System
open System.Text

module Byte =
  let BytesToString(bs:byte[], format:string) =
    let sb = new StringBuilder(bs.Length * 4)
    bs |> Array.iter(fun b -> sb.AppendFormat(format, b) |> ignore)
    sb.ToString()

#PowerShell
function bytesToString($bs, $format)
{
  $bs | %{$result += ($format -f $_)}
  $result
}

Examples
//C#
byte[] bs = { 102, 111, 111 };
Debug.WriteLine(Byte.BytesToString(bs, "{0}"));  //default format
102111111  //output

//F#
let bs = [|102uy; 111uy; 111uy|]
Byte.BytesToString(bs, "{0:d4}-")  //4 digit width format
|> (fun s -> printfn "%s" s)
0102-0111-0111-  //output

#PowerShell
[byte[]]$bs = 102,111,111
bytesToString $bs '{0:x} ' #hex format
66 6f 6f  #output

8/14/09

Listing Users From the Windows Event Log

GetEventLogUsers returns a list of users from the Windows EventLogs, e.g. Application, Security, System. This function returns the entire dataset, unsorted. See examples for sorting and returning distinct lists.

Note: This function works on Windows XP, but not Window Server 2008.
//C#
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace ExpressionSoftware.EventLogs
{
    public static class EventLogQuery
    {
        public static IEnumerable GetEventLogUsers(string logName)
        {
            EventLog log = new EventLog(logName);
            var users = from e in log.Entries.Cast()
                        select e.UserName;
            return users;
        }
    }
}

//F# v1.9.7.8
namespace ExpressionSoftware.EventLogs
open System.Diagnostics

module EventLogQuery =
  let GetEventLogUsers logName =
    let log = new EventLog(logName)
    log.Entries
    |> Seq.cast
    |> Seq.map (fun x -> x.UserName)

#PowerShell
function getEventLogUsers($logName)
{
  $log = new-object system.diagnostics.eventLog($logName)
  $log.entries | %{$_.username}
}

Examples
//C#
var users = EventLogQuery.GetEventLogUsers("security");
users = users.Distinct().OrderBy(u => u);
foreach (string user in users)
{
    Debug.WriteLine(user);
}

//F#
let users = EventLogQuery.GetEventLogUsers "security" |> Seq.distinct |> Seq.sort
for user in users do
  printfn "%s" user

#PowerShell
getEventLogUsers 'security' | sort-object | get-unique

Output
DEV\john
NT AUTHORITY\ANONYMOUS LOGON
NT AUTHORITY\LOCAL SERVICE
NT AUTHORITY\NETWORK SERVICE
NT AUTHORITY\SYSTEM