Monthly Archive

Categories

Modules

PAM 0.2

I’ve released the second module for the PowerShell Admin Modules tonight.  It is available from

http://psam.codeplex.com/releases/view/46364

This release includes two modules.

PAMShare (originally in PAM 0.1) contains the following functions:

  • Get-Share
  • Get-ShareAccessMask
  • Get-ShareSecurity
  • New-Share
  • Remove-Share
  • Set-Share

Get-Share can now accept a wildcard  eg get-share t*

New-Share now has the share name as first parameter and path as the second.

Both of these changes are the result of feed back on the issues page

The second module is PAMMath.  It contains functions for working with binary and hex numbers

  • ConvertTo-Binary
  • ConvertTo-Decimal
  • ConvertTo-Hex
  • Get-BinaryAND
  • Get-BinaryDifference
  • Get-BinaryOR
  • Get-BinarySum
  • Get-BinaryXOR
  • Get-HexDifference
  • Get-HexSum
  • Test-Binary
  • Test-Hex

A help file is supplied with each module.

Enjoy

PSCX 2.0 install

I mentioned last time that PSCX 2.0 was available. There is a very wide range of functionality available in the form of functions and cmdlets:

Cmdlets

Add-PathVariable                        Clear-MSMQueue                          ConvertFrom-Base64
ConvertTo-Base64                        ConvertTo-MacOs9LineEnding              ConvertTo-Metric
ConvertTo-UnixLineEnding                ConvertTo-WindowsLineEnding             Convert-Xml
Disconnect-TerminalSession              Expand-Archive                          Export-Bitmap
Format-Byte                             Format-Hex                              Format-Xml
Get-ADObject                            Get-AdoConnection                       Get-AdoDataProvider
Get-AlternateDataStream                 Get-Clipboard                           Get-DhcpServer
Get-DomainController                    Get-DriveInfo                           Get-EnvironmentBlock
Get-FileTail                            Get-FileVersionInfo                     Get-ForegroundWindow
Get-Hash                                Get-HttpResource                        Get-LoremIpsum
Get-MountPoint                          Get-MSMQueue                            Get-OpticalDriveInfo
Get-PathVariable                        Get-PEHeader                            Get-Privilege
Get-PSSnapinHelp                        Get-ReparsePoint                        Get-ShortPath
Get-TabExpansion                        Get-TerminalSession                     Get-TypeName
Get-Uptime                              Import-Bitmap                           Invoke-AdoCommand
Invoke-Apartment                        Join-String                             New-Hardlink
New-Junction                            New-MSMQueue                            New-Shortcut
New-Symlink                             Out-Clipboard                           Ping-Host
Pop-EnvironmentBlock                    Push-EnvironmentBlock                   Read-Archive
Receive-MSMQueue                        Remove-AlternateDataStream              Remove-MountPoint
Remove-ReparsePoint                     Resolve-Host                            Send-MSMQueue
Send-SmtpMail                           Set-BitmapSize                          Set-Clipboard
Set-FileTime                            Set-ForegroundWindow                    Set-PathVariable
Set-Privilege                           Set-VolumeLabel                         Skip-Object
Split-String                            Start-TabExpansion                      Stop-TerminalSession
Test-AlternateDataStream                Test-Assembly                           Test-MSMQueue
Test-Script                             Test-UserGroupMembership                Test-Xml
Unblock-File                            Write-BZip2                             Write-Clipboard
Write-GZip                              Write-Tar                               Write-Zip

 

functions

Add-DirectoryLength                     Add-ShortPath                           Dismount-VHD
Edit-File                               Edit-HostProfile                        Edit-Profile
Enable-OpenPowerShellHere               Get-Help                                Get-PropertyValue
Get-ScreenCss                           Get-ScreenHtml                          Get-ViewDefinition
help                                    Invoke-BatchFile                        Invoke-Elevated
Invoke-GC                               Invoke-Method                           Invoke-NullCoalescing
Invoke-Reflector                        Invoke-Ternary                          less
Mount-VHD                               New-HashObject                          Out-Speech
QuoteList                               QuoteString                             Resolve-ErrorRecord
Resolve-HResult                         Resolve-WindowsError                    Set-LocationEx
Set-ReadOnly                            Set-Writable                            Show-Tree
Stop-RemoteProcess

 

Download the zip file, unblock it, unzip and copy the pscx folder and all sub folders to a folder on your modules path. Couldn’t be easier. To get the functionality

Import-Module pscx

PowerShell Community Extensions 2.0

I’ve mentioned the Community Extensions many times in these posts. Version 2.0 is now available http://www.codeplex.com/wikipage?ProjectName=Pscx.

It installs as a PowerShell module – much easier and neater.

I’ve blogged about the beta a few times – if you didn’t try the beta go and get the RTM

Hex Subtraction

Again this takes the pattern from the binary function and adapts it to work with hex

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
## this will always subtract value2 from value1
function Get-HexDifference {
param(
    [string]$inputvalue1,
    [string]$inputvalue2
)
## check valid hex numbers
    Test-Hex $inputvalue1
    Test-Hex $inputvalue2

    $diff = (ConvertTo-Decimal -inputvalue $inputvalue1 -hex) `
     - (ConvertTo-Decimal -inputvalue $inputvalue2 -hex)

    if ($diff -lt 0){Throw "Hex subtraction produces negative number"}
    else {ConvertTo-Hex -inputvalue $diff}
}

 

As with the binary subtraction function we test to see if we’ve gone negative – if so reject the value.

 

That’s the end of the math module for now.  As soon as I’ve done the help files I’ll post it on codeplex.

Hex Addition

We’ve looked at the binary functions – now its time to look at the hex functions starting with addition.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
function Get-HexSum {
param(
    [string]$inputvalue1,
    [string]$inputvalue2
)
## check valid hex numbers
    Test-Hex $inputvalue1
    Test-Hex $inputvalue2

    $sum = (ConvertTo-Decimal -inputvalue $inputvalue1 -hex) `
    + (ConvertTo-Decimal -inputvalue $inputvalue2 -hex)

    ConvertTo-Hex -inputvalue $sum
}

This is a direct copy of the binary addition function – just changed to accept hex input instead.

Again we test the hex number is actually hex – convert to decimal, add, and convert back to hex

Establishing a pattern helps make things easier for producing related functions.

Binary Subtraction

Continuing our look at maths functions in binary (hex is to come) lets have a quick look at subtraction

 

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
function Get-BinaryDifference {
param(
    [string]$value1,
    [string]$value2
)
## check valid binary numbers
## move this to a validation test
    Test-Binary $value1
    Test-Binary $value2

    $diff = (ConvertTo-Decimal -inputvalue $value1 -binary) -`
     (ConvertTo-Decimal -inputvalue $value2 -binary)

    if ($diff -lt 0){Throw "Binary subtraction produces negative number"}
    else {ConvertTo-Binary -inputvalue $diff}
}

 

Always assume that value2 will be subtracted from value1 therefore value2 should be smaller.

The function is the same as the addition except we perform a subtraction 🙂

And we check to see if we have a negative result.  If so throw a wobbly and end the action.

These binary and hex functions will be the next module added to PSAM on codeplex

Binary Addition

We recently looked at converting numbers to binary and hex.  I then thought that I sometimes need to perform simple arithmetic in these bases so – binary addition.

We can use the functions we already have.  Convert a couple of numbers to binary

PS> $a = Convert-ToBinary -inputvalue 51
PS> $b = Convert-ToBinary -inputvalue 39
PS> $a
110011
PS> $b
100111

sum them by converting the binary back to decimal, performing the sum and converting back to binary.

PS> $c = Convert-ToBinary -inputvalue ((Convert-ToDecimal -inputvalue $a -binary) + (Convert-ToDecimal -inputvalue $b -binary))
PS> $c
1011010

A quick check on the result

PS> Convert-ToDecimal -inputvalue $c -binary
90

That works OK  but its a bit messy – too much typing. So I wrote Get-BinarySum

001
002
003
004
005
006
007
008
009
010
011
012
013
014
function Get-BinarySum {
param(
    [string]$value1,
    [string]$value2
)
## check valid binary numbers
## move this to a validation test
Test-Binary $value1
Test-Binary $value2

$sum = (Convert-ToDecimal -inputvalue $value1 -binary) + (Convert-ToDecimal -inputvalue $value2 -binary)

Convert-ToBinary -inputvalue $sum
}

 

Get the two binary numbers – test that they are binary.  Test-Binary is a helper function created from the code used in Convert-ToDecimal

The sum is performed by converting each binary to a decimal, summing them and converting the result back to a binary.

Bingo.  This forms the framework for other functions.

Number conversions

I often have to do conversions between decimal, hex and binary so I decided I wanted some functions to do this for me

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
#Requires -version 2.0
##
## Author Richard Siddaway
## Version 0.1 - Inital Release May 2009
###############################################

function Convert-ToHex{
[CmdletBinding()]
param (
    [Parameter(ValueFromPipeline=$true)]
    [int64]$inputvalue =0
)
    [convert]::ToString($inputvalue,16)
}

function Convert-ToBinary{
[CmdletBinding()]
param (
    [Parameter(ValueFromPipeline=$true)]
    [int64]$inputvalue =0
)
    [convert]::ToString($inputvalue,2)
}

function Convert-ToDecimal{
[CmdletBinding()]
param (
    [Parameter(ValueFromPipeline=$true)]
    [string]$inputvalue,

    [Parameter(ParameterSetName="Binary")]       
    [switch]$binary,
   
    [Parameter(ParameterSetName="Hex")]     
    [switch]$hex
)
    $chars = $inputvalue.Trim().ToCharArray()
    switch ($psCmdlet.ParameterSetName) {
        Binary { 
                    foreach ($char in $chars){
                        if (-not($char -match '0|1')){
                            Throw "$inputvalue is not a valid binary number"
                        }
                    }
                                                         
                    $ret = [convert]::ToInt64($inputvalue.Trim(),2)
                    break 
               }
        Hex    { 
                    foreach ($char in $chars){
                        if (-not($char -match '[0-9]' -or $char -match '[A-F]')){
                            Throw "$inputvalue is not a valid hex number"
                        }
                    }

                    $ret = [convert]::ToInt64($inputvalue.Trim(),16)
                    break
               }
    }
return $ret
}

 

Three simple functions to perform the conversions.

In the convert-todecimal I check that the input string is correct for binary or hex respectively before performing the conversion. It returns a int64 but that is easy to convert to int32 if required

[int]$i32 = Convert-ToDecimal -inputvalue "FFFFFF" -hex

Use the functions like this

Convert-ToBinary 255
Convert-ToHex 255

Convert-ToDecimal -inputvalue "ff" -hex

Convert-ToDecimal -inputvalue "11111111" –binary

or even

Convert-ToHex -inputvalue (Convert-ToDecimal -inputvalue "11111111" -binary)

though this is messy so I’m going to create direct hex <-> binary conversion routines

 

Error trapping stops false conversions

PS> Convert-ToDecimal -inputvalue " 111b1111 " -binary
111b1111  is not a valid binary number
At C:\Scripts\Modules\pammath\pammath.psm1:42 char:34
+                             Throw <<<<  "$inputvalue is not a valid binary number"
    + CategoryInfo          : OperationStopped: ( 111b1111  is not a valid binary number:String) [], RuntimeException
    + FullyQualifiedErrorId :  111b1111  is not a valid binary number

 

PS> Convert-ToDecimal -inputvalue "ffg" -hex
ffg is not a valid hex number
At C:\Scripts\Modules\pammath\pammath.psm1:52 char:34
+                             Throw <<<<  "$inputvalue is not a valid hex number"
    + CategoryInfo          : OperationStopped: (ffg is not a valid hex number:String) [], RuntimeException
    + FullyQualifiedErrorId : ffg is not a valid hex number

 

When I’ve finished the direct hex <-> binary conversions this will be the second module on PSAM.  I’ll add some functions to do simple arithmetic in hex and binary as well

PowerShell Admin Modules

I have created the first download for the PowerShell Admin Modules. This will be a set of of modules including code previously published on my blogs at:

http://msmvps.com/blogs/RichardSiddaway/Default.aspx

http://itknowledgeexchange.techtarget.com/powershell/

http://richardsiddaway.spaces.live.com/

 

The first release comprises a module for working with shares and can be found at:

http://psam.codeplex.com/

 

It has the following functions:

  • Get-Share
  • Get-ShareAccessMask
  • Get-ShareSecurity
  • New-Share
  • Remove-Share
  • Set-Share

There have been a series of posts on my IT Knowledge Exchange blog (see above) about the functions.  Select Shares from the

Browse This Blog’s Tags box

More to follow soon. Enjoy

Technorati Tags: PowerShell,Modules,Shares,PSAM

PowerShell UG Recording April 20

Thanks to everyone who came on to the Live Meeting tonight.  For anyone who missed it:

The slides and demo are available on my sky drive at

http://cid-43cfa46a74cf3e96.skydrive.live.com/browse.aspx/PowerShell%20User%20Group/April%202010

The recording of the meeting is available from

Richard Siddaway has invited you to view a Microsoft Office Live Meeting recording.
View Recording
Recording Details
    Subject: PowerShell Modules
    Recording URL: https://www.livemeeting.com/cc/usergroups/view
    Recording ID: B3FG29
    Attendee Key: Zft%D4B7H

This Office Live Meeting invitation is a personal invitation meant only for you. It should not be forwarded. If you received this email by mistake or require Live Meeting Assistance, please refer to the Live Meeting Assistance Center at http://r.office.microsoft.com/r/rlidLiveMeeting?p1=12&p2=en_US&p3=LMInfo&p4=support

 

Next meeting is 18 May when we look at PowerShell eventing

Technorati Tags: PowerShell,User Group