Commit e7acec95 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading
+72 −0
Changes for Add-ExtendedFileProperties.ps1: 72 added lines, 0 removed lines.
Original line number Diff line number Diff line
##############################################################################
##
## Add-ExtendedFileProperties.ps1
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
## Add the extended file properties normally shown in Exlorer's 
## "File Properties" tab.
##
## ie:
##
##  PS >Get-ChildItem | Add-ExtendedFileProperties.ps1 | 
##          Format-Table Name,"Bit Rate"
##
##############################################################################

begin
{
    ## Create the Shell.Application COM object that provides this
    ## functionality
    $shellObject = New-Object -Com Shell.Application

    ## Store the property names and identifiers for all of the shell
    ## properties
    $itemProperties = @{
        1 = "Size"; 2 = "Type"; 3 = "Date Modified";
        4 = "Date Created"; 5 = "Date Accessed";
        7 = "Status"; 8 = "Owner";
        9 = "Author"; 10 = "Title"; 11 = "Subject";
        12 = "Category"; 13 = "Pages"; 14 = "Comments";
        15 = "Copyright"; 16 = "Artist"; 17 = "Album Title";
        19 = "Track Number"; 20 = "Genre"; 21 = "Duration";
        22 = "Bit Rate"; 23 = "Protected"; 24 = "Camera Model";
        25 = "Date Picture Taken"; 26 = "Dimensions";
        30 = "Company"; 31 = "Description"; 32 = "File Version";
        33 = "Product Name"; 34 = "Product Version" }
}

process
{
    ## Get the file from the input pipeline. If it is just a filename
    ## (rather than a real file,) piping it to the Get-Item cmdlet will
    ## get the file it represents.
    $fileItem = $_ | Get-Item

    ## Don't process directories
    if($fileItem.PsIsContainer)
    {
        $fileItem
        return
    }

    ## Extract the file name and directory name
    $directoryName = $fileItem.DirectoryName
    $filename = $fileItem.Name

    ## Create the folder object and shell item from the COM object
    $folderObject = $shellObject.NameSpace($directoryName)
    $item = $folderObject.ParseName($filename)

    ## Now, go through each property and add its information as a
    ## property to the file we are about to return
    foreach($itemProperty in $itemProperties.Keys)
    {
        $fileItem | Add-Member NoteProperty $itemProperties[$itemProperty] `
            $folderObject.GetDetailsOf($item, $itemProperty)
    }

    ## Finally, return the file with the extra shell information
    $fileItem
}
 No newline at end of file

Compare-Property.ps1

0 → 100644
+19 −0
Changes for Compare-Property.ps1: 19 added lines, 0 removed lines.
Original line number Diff line number Diff line
##############################################################################
##
## Compare-Property.ps1
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
## Compare the property you provide against the input supplied to the script.
## This provides the functionality of simple Where-Object comparisons without
## the syntax required for that cmdlet.
##
## Example:
##    Get-Process | Compare-Property Handles gt 1000
##    dir | Compare-Property PsIsContainer
##############################################################################
param($property, $operator = "eq", $matchText = "$true")

Begin { $expression = "`$_.$property -$operator `"$matchText`"" }
Process { if(Invoke-Expression $expression) { $_ } }
 No newline at end of file

Connect-WebService.ps1

0 → 100644
+152 −0
Changes for Connect-WebService.ps1: 152 added lines, 0 removed lines.
Original line number Diff line number Diff line
##############################################################################
##
## Connect-WebService.ps1
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
## Connect to a given web service, and create a type that allows you to
## interact with that web service.
##
## Example:
##
##     $wsdl = "http://terraserver.microsoft.com/TerraService2.asmx?WSDL"
##     $terraServer = Connect-WebService $wsdl
##     $place = New-Object Place
##     $place.City = "Redmond"
##     $place.State = "WA"
##     $place.Country = "USA"
##     $facts = $terraserver.GetPlaceFacts($place)
##     $facts.Center
##############################################################################
param(
    [string] $wsdlLocation = $(throw "Please specify a WSDL location"),
    [string] $namespace,
    [Switch] $requiresAuthentication)

## Create the web service cache, if it doesn't already exist
if(-not (Test-Path Variable:\Lee.Holmes.WebServiceCache))
{
    ${GLOBAL:Lee.Holmes.WebServiceCache} = @{}
}

## Check if there was an instance from a previous connection to
## this web service. If so, return that instead.
$oldInstance = ${GLOBAL:Lee.Holmes.WebServiceCache}[$wsdlLocation]
if($oldInstance)
{
    $oldInstance
    return
}

## Load the required Web Services DLL
[void] [Reflection.Assembly]::LoadWithPartialName("System.Web.Services")

## Download the WSDL for the service, and create a service description from
## it.
$wc = New-Object System.Net.WebClient

if($requiresAuthentication)
{
    $wc.UseDefaultCredentials = $true
}

$wsdlStream = $wc.OpenRead($wsdlLocation)

## Ensure that we were able to fetch the WSDL
if(-not (Test-Path Variable:\wsdlStream))
{
    return
}

$serviceDescription =
    [Web.Services.Description.ServiceDescription]::Read($wsdlStream)
$wsdlStream.Close()

## Ensure that we were able to read the WSDL into a service description
if(-not (Test-Path Variable:\serviceDescription))
{
    return
}

## Import the web service into a CodeDom
$serviceNamespace = New-Object System.CodeDom.CodeNamespace
if($namespace)
{
    $serviceNamespace.Name = $namespace
}

$codeCompileUnit = New-Object System.CodeDom.CodeCompileUnit
$serviceDescriptionImporter = 
    New-Object Web.Services.Description.ServiceDescriptionImporter
$serviceDescriptionImporter.AddServiceDescription(
    $serviceDescription, $null, $null)
[void] $codeCompileUnit.Namespaces.Add($serviceNamespace)
[void] $serviceDescriptionImporter.Import(
    $serviceNamespace, $codeCompileUnit)

## Generate the code from that CodeDom into a string
$generatedCode = New-Object Text.StringBuilder
$stringWriter = New-Object IO.StringWriter $generatedCode
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider 
$provider.GenerateCodeFromCompileUnit($codeCompileUnit, $stringWriter, $null)

## Compile the source code.
$references = @("System.dll", "System.Web.Services.dll", "System.Xml.dll")
$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters 
$compilerParameters.ReferencedAssemblies.AddRange($references)
$compilerParameters.GenerateInMemory = $true

$compilerResults = 
    $provider.CompileAssemblyFromSource($compilerParameters, $generatedCode)

## Write any errors if generated.         
if($compilerResults.Errors.Count -gt 0) 
{ 
    $errorLines = "" 
    foreach($error in $compilerResults.Errors) 
    { 
        $errorLines += "`n`t" + $error.Line + ":`t" + $error.ErrorText 
    } 

    Write-Error $errorLines
    return 
}
## There were no errors.  Create the webservice object and return it.
else 
{
    ## Get the assembly that we just compiled 
    $assembly = $compilerResults.CompiledAssembly

    ## Find the type that had the WebServiceBindingAttribute. 
    ## There may be other "helper types" in this file, but they will 
    ## not have this attribute
    $type = $assembly.GetTypes() |
        Where-Object { $_.GetCustomAttributes(
            [System.Web.Services.WebServiceBindingAttribute], $false) }

    if(-not $type)
    {
        Write-Error "Could not generate web service proxy."
        return
    }

    ## Create an instance of the type, store it in the cache,
    ## and return it to the user.
    $instance = $assembly.CreateInstance($type)

    ## Many services that support authentication also require it on the
    ## resulting objects
    if($requiresAuthentication)
    {
        if(@($instance.PsObject.Properties | 
            where { $_.Name -eq "UseDefaultCredentials" }).Count -eq 1)
        {
            $instance.UseDefaultCredentials = $true
        }
    }
    
    ${GLOBAL:Lee.Holmes.WebServiceCache}[$wsdlLocation] = $instance

    $instance
}
 No newline at end of file

Convert-TextObject.ps1

0 → 100644
+205 −0
Changes for Convert-TextObject.ps1: 205 added lines, 0 removed lines.
Original line number Diff line number Diff line
##############################################################################
##
## Convert-TextObject.ps1 -- Convert a simple string into a custom PowerShell
## object.
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##        Parameters:
##
##        [string] Delimiter
##            If specified, gives the .NET Regular Expression with which to
##            split the string. The script generates properties for the 
##            resulting object out of the elements resulting from this split.
##            If not specified, defaults to splitting on the maximum amount
##            of whitespace: "\s+", as long as ParseExpression is not 
##            specified either.
##
##        [string] ParseExpression
##            If specified, gives the .NET Regular Expression with which to 
##            parse the string. The script generates properties for the 
##            resulting object out of the groups captured by this regular
##            expression.
##
##        ** NOTE ** Delimiter and ParseExpression are mutually exclusive.
##
##        [string[]] PropertyName
##            If specified, the script will pair the names from this object
##            definition with the elements from the parsed string.  If not
##            specified (or the generated object contains more properties
##            than you specify,) the script uses property names in the
##            pattern of Property1,Property2,...,PropertyN
##
##        [type[]] PropertyType
##            If specified, the script will pair the types from this list with
##            the properties from the parsed string.  If not specified (or the
##            generated object contains more properties than you specify,) the
##            script sets the properties to be of type [string]
##
##
##        Example usage:
##            "Hello World" | Convert-TextObject
##            Generates an Object with "Property1=Hello" and "Property2=World"
##
##            "Hello World" | Convert-TextObject -Delimiter "ll"
##            Generates an Object with "Property1=He" and "Property2=o World"
##
##            "Hello World" | Convert-TextObject -ParseExpression "He(ll.*o)r(ld)"
##            Generates an Object with "Property1=llo Wo" and "Property2=ld"
##
##            "Hello World" | Convert-TextObject -PropertyName FirstWord,SecondWord
##            Generates an Object with "FirstWord=Hello" and "SecondWord=World
##
##            "123 456" | Convert-TextObject -PropertyType $([string],[int])
##            Generates an Object with "Property1=123" and "Property2=456"
##            The second property is an integer, as opposed to a string
##
##############################################################################
param(
    [string] $delimiter, 
    [string] $parseExpression, 
    [string[]] $propertyName, 
    [type[]] $propertyType
    )

function Main(
    $inputObjects, $parseExpression, $propertyType, 
    $propertyName, $delimiter)
{
    $delimiterSpecified = [bool] $delimiter
    $parseExpressionSpecified = [bool] $parseExpression

    ## If they've specified both ParseExpression and Delimiter, show usage
    if($delimiterSpecified -and $parseExpressionSpecified)
    {
        Usage
        return
    }

    ## If they enter no parameters, assume a default delimiter of whitespace
    if(-not $($delimiterSpecified -or $parseExpressionSpecified))
    {
        $delimiter = "\s+"
        $delimiterSpecified = $true
    }

    ## Cycle through the $inputObjects, and parse it into objects
    foreach($inputObject in $inputObjects)
    {
        if(-not $inputObject) { $inputObject = "" }
        foreach($inputLine in $inputObject.ToString())
        {
            ParseTextObject $inputLine $delimiter $parseExpression `
                $propertyType $propertyName
        }
    }
}

function Usage
{
    "Usage: "
    " Convert-TextObject"
    " Convert-TextObject -ParseExpression parseExpression " +
        "[-PropertyName propertyName] [-PropertyType propertyType]"
    " Convert-TextObject -Delimiter delimiter " + 
        "[-PropertyName propertyName] [-PropertyType propertyType]"
    return
}

## Function definition -- ParseTextObject.
## Perform the heavy-lifting -- parse a string into its components.
## for each component, add it as a note to the Object that we return
function ParseTextObject
{
    param(
        $textInput, $delimiter, $parseExpression,
        $propertyTypes, $propertyNames)

    $parseExpressionSpecified = -not $delimiter

    $returnObject = New-Object PSObject

    $matches = $null
    $matchCount = 0
    if($parseExpressionSpecified)
    {
        ## Populates the matches variable by default
        [void] ($textInput -match $parseExpression)
        $matchCount = $matches.Count
    }
    else
    {
        $matches = [Regex]::Split($textInput, $delimiter)
        $matchCount = $matches.Length
    }

    $counter = 0
    if($parseExpressionSpecified) { $counter++ }
    for(; $counter -lt $matchCount; $counter++)
    {
        $propertyName = "None"
        $propertyType = [string]

        ## Parse by Expression
        if($parseExpressionSpecified)
        {
            $propertyName = "Property$counter"

            ## Get the property name
            if($counter -le $propertyNames.Length)
            {
                if($propertyName[$counter - 1])
                {
                    $propertyName = $propertyNames[$counter - 1] 
                }
            }

            ## Get the property value
            if($counter -le $propertyTypes.Length)
            {
                if($types[$counter - 1])
                {
                    $propertyType = $propertyTypes[$counter - 1] 
                }
            }
        }
        ## Parse by delimiter
        else
        {
            $propertyName = "Property$($counter + 1)"

            ## Get the property name
            if($counter -lt $propertyNames.Length) 
            {
                if($propertyNames[$counter])
                {
                    $propertyName = $propertyNames[$counter] 
                }
            }

            ## Get the property value
            if($counter -lt $propertyTypes.Length)
            {
                if($propertyTypes[$counter])
                {
                    $propertyType = $propertyTypes[$counter] 
                }
            }
        }

        Add-Note $returnObject $propertyName `
            ($matches[$counter] -as $propertyType)
    }

    $returnObject
}

## Add a note to an object
function Add-Note ($object, $name, $value) 
{
     $object | Add-Member NoteProperty $name $value
}


Main $input $parseExpression $propertyType $propertyName $delimiter
 No newline at end of file
+17 −0
Changes for ConvertFrom-FahrenheitWithFunction.ps1: 17 added lines, 0 removed lines.
Original line number Diff line number Diff line
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)

param([double] $fahrenheit)

## Convert Fahrenheit to Celcius
function ConvertFahrenheitToCelcius([double] $fahrenheit)
{
    $celcius = $fahrenheit - 32
    $celcius = $celcius / 1.8
    $celcius
}

$celcius = ConvertFahrenheitToCelcius $fahrenheit

## Output the answer
"$fahrenheit degrees Fahrenheit is $celcius degrees Celcius."
 No newline at end of file
Loading