Tuesday, 30 December 2008

Get-StockQuote.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Gets stock quotes using a web servoice 
  4. .DESCRIPTION 
  5.     This function uses the New-WebServiceProxy cmdlet to 
  6.     create a web service proxy. Then it calls that proxy 
  7.     to get stock information.  
  8. .NOTES 
  9.     File Name  : get-stockquote.ps1 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell V2 CTP3 
  12. .LINK 
  13.    Original post:   
  14.    http://PoshCode.org/embed/752 
  15.    Updated script posted: 
  16.    http://www.pshscripts.blogspot.com 
  17. .INPUTTYPE 
  18.    String(s) representing stock tickers to find 
  19. .RETURNVALUE 
  20.    XML Element, holding stock details 
  21. .EXAMPLE 
  22.     Run from PowerShell Prompt: 
  23.     Get-StockQuote "MSFT" 
  24.     Output - left as an exercise for the reader 
  25. .EXAMPLE 
  26.     Run from Pipeline 
  27.     "IBM","INTC" | Get-StockQuote 
  28.     Output - left as an exercise for the reader 
  29. .PARAMETER TICKER 
  30.     A string, or array of strings representing stock tickers 
  31.     The function gets stock details for each stock ticker provided 
  32. #> 
  33.  
  34. function Get-StockQuote { 
  35. param
  36. [Parameter(Position=0, Mandatory=$FALSE, ValueFromPipeline=$TRUE)]  
  37. [String] $TICKER="MSFT"
  38. process { 
  39.    $ticker 
  40.    $s = new-webserviceproxy -uri http://www.webservicex.net/stockquote.asmx 
  41.    foreach ($symbol in $ticker) { 
  42.       $result = [xml]$s.GetQuote($symbol
  43.       $result.StockQuotes.Stock 
  44.     } # end foreach 
  45. } #end process block 
  46. } # end function 
  47.  
  48.  
  49. "Example 1:" 
  50. "==========" 
  51. Get-StockQuote MSFT 
  52. "" 
  53. "Example 2:" 
  54. "==========" 
  55. "IBM","INTC" | Get-StockQuote 

Monday, 29 December 2008

Validate-EmailAddress.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Validates an email address using a web service 
  4. .DESCRIPTION 
  5.     This script uses the New-WebServiceProxy cmdlet to 
  6.     create a web service proxy. Then it calls that proxy 
  7.     to Validate an email address.  
  8. .NOTES 
  9.     File Name  : validate-emailaddress.ps1 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell V2 CTP3 
  12. .LINK 
  13.    Script posted to: 
  14.    http://www.pshscripts.blogspot.com 
  15. .INPUTTYPE 
  16.    String(s) representing email address to validate 
  17. .RETURNVALUE 
  18.    [Boolean] - whether email address was valid 
  19. .EXAMPLE 
  20.     Run from PowerShell Prompt: 
  21.     PS C:\foo> .\Validate-EmailAddress "tfl@psp.co.uk” 
  22.     True 
  23. .EXAMPLE 
  24.     Run from Pipeline: 
  25.     PS C:\foo> "tfl@psp.co.uk", "foo@foo.bar" | .\Validate-EmailAddress 
  26.     True 
  27.     False 
  28. .PARAMETER addr 
  29.     A string, or array of strings representing email addresses to check 
  30. #> 
  31.  
  32. param( 
  33. [Parameter(Position=0, Mandatory=$FALSE, ValueFromPipeline=$TRUE)]  
  34. [String] $Addr = "doctordns@gmail.com" ) 
  35. process { 
  36.    $s = new-webserviceproxy -uri http://www.webservicex.net/validateEmail.asmx 
  37.    foreach ($a in $addr) { 
  38.       $result = $s.IsValidEmail($a
  39.       $result 
  40.     } # end foreach 
  41. } #end process block 

Sunday, 28 December 2008

Get-AutoHelp.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     A summary of what this script does 
  4.     In this case, this script documents the auto-help text
  5.     in PowerShell CTP 3 
  6.     Appears in all basic, -detailed, -full, -examples 
  7. .DESCRIPTION 
  8.     A more in depth description of the script 
  9.     Should give script developer more things to talk about 
  10.     Hopefully this can help the community too 
  11.     Becomes: "DETAILED DESCRIPTION" 
  12.     Appears in basic, -full and -detailed 
  13. .NOTES 
  14.     Additional Notes, eg 
  15.     File Name  : get-autohelp.ps1 
  16.     Author     : Thomas Lee - tfl@psp.co.uk 
  17.     Requires   : PowerShell V2 CTP3 
  18.     Appears in -full  
  19. .LINK 
  20.     A hyper link, eg 
  21.     http://www.pshscripts.blogspot.com/2008/12/get-autohelpps1.html 
  22.     Becomes: "RELATED LINKS"  
  23.     Appears in basic and -Full 
  24. .EXAMPLE 
  25.     The first example - just text documentation 
  26.     You should provide a way of calling the script, plus
  27.     any expected output, eg:
  28.          C:\foo> .\get-autohelp.ps1 42
  29.          The meaning of life is 42
  30.     Appears in -detailed and -full 
  31. .EXAMPLE 
  32.     The second example - more text documentation 
  33.     This would be an example calling the script differently. You
  34.     have lots and lots, and lots of examples if this is useful. 
  35.     Appears in -detailed and -full 
  36. .INPUTTYPE 
  37.    Documentary text, eg: 
  38.    Input type  [Universal.SolarSystem.Planetary.CommonSense] 
  39.    Appears in -full 
  40. .RETURNVALUE 
  41.    Documentary Text, e,g: 
  42.    Output type  [Universal.SolarSystem.Planetary.Wisdom] 
  43.    Appears in -full 
  44. .COMPONENT 
  45.    Not sure how to specify or use 
  46.    Does not appear in basic, -full, or -detailed 
  47.    Should appear in -component 
  48. .ROLE  
  49.    Not sure How to specify or use 
  50.    Does not appear in basic, -full, or -detailed 
  51.    Should appear with -role 
  52. .FUNCTIONALITY 
  53.    Not sure How to specify or use 
  54.    Does not appear in basic, -full, or -detailed 
  55.    Should appear with -functionality 
  56. .PARAMETER foo 
  57.    The .Parameter area in the script is used to derive the
  58.    of the PARAMETERS in Get-Help output which documents the
  59.    parameters in the param block. The section takes a
  60.    value (in this case foo,  the name of the first actual
  61.    parameter), and only appears if there is parameter of
  62.    that name in the param block. Having a section for a
  63.    parameter that does not exist generate no extra output
  64.    of this section   
  65.    Appears in -detailed, -full (with more info than in -det)
  66.    Appears in -Parameter (need to specify the parameter name) 
  67. .PARAMETER bar 
  68.    Example of a parameter definition for a parameter that does not exist. 
  69.    Does not appear at all. 
  70. #> 
  71.  
  72. # Note above section does not contain entries for NAME, SYNTAX
  73. # and REMARKS sections of in get-help output 
  74. # 
  75. # These sections appear as follows: 
  76. # NAME    - generated from the name passed to get-help.  
  77. # SYNTAX  - generated from param block details. 
  78. # REMARKS - generated based on script name (e.g. what's shown in NAME)
  79. #           inserted into some static text. 
  80. # 
  81. # Not sure how to generate/document -component, -role, -functionality 
  82. # Not sure how to generate/use  -category 
  83.  
  84. param
  85. [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]  
  86. [int64] $foo=42 
  87.  
  88.  "The meaning of life is $foo!" 

Saturday, 27 December 2008

Get-Win32Share.ps1

<#
.SYNOPSIS
Demonstrates WMI and Win32_Share
.DESCRIPTION
This script looks at objects returned from Get-WMIObject, and
    [WMICLASS] and demonstrates the use of a static method (create)
    and a dynamic or object method (delete). 
.NOTES
File Name: get-win32share.ps1
Author : Thomas Lee - tfl@psp.co.uk
.LINK
http://www.pshscripts.blogspot.com
.EXAMPLE
Left as an exercise for the reader
#>

# Display shares at start
$start = get-wmiobject win32_share | where {$_.name -match "Foo"}
if ($start) {
"{0} foo shares at start, as follows:" -f $start.count;
$start}
else {"No foo shares"}

# Create a foo22 share
"";"Adding Foo22 share"
$class = [WMICLASS]'win32_share'
$ret = $class.create("c:\foo", "foo22", 0,$null,"Test Share Creation with WMI")
if ($ret.returnvalue -eq 0){
"Foo22 Share created OK"}
else {
"Share not created, error code: {0}" -f $ret.returnvalue
}

# Display results
"";"Foo shares now:"
get-wmiobject win32_share | where {$_.name -match "foo"}
""

# Delete the foo22 share
$del = Get-WmiObject win32_share | where {$_.name -eq "foo22"}
$ret = $del.delete()
if ($ret.returnvalue -eq 0){
"share deleted OK"}
else {
"Share not deleted, error code: {0}" -f $ret.returnvalue
}

# Display final results
"";"Foo at the end:"
$finish = get-wmiobject win32_share | where {$_.name -match "foo"}
if ($finish) {
"{0} foo shares at the end, as folllows:" -f $start.count;
$start}
else {"No foo shares at the end:"}
""

Friday, 26 December 2008

Get-Formatstring2.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Demonstrates string formatting using Powershell 
  4. .DESCRIPTION 
  5.     This script formats 2 numbers in a variety of ways, also 
  6.     formats an enum. 
  7.     An adaptation of the C# sample in the MSDN Library. However, 
  8.     this script uses a built-in enum, and displays two. 
  9. .NOTES 
  10.     Author   : Thomas Lee - tfl@psp.co.uk 
  11. .INPUTTYPE 
  12.    This script has no effective parameters. 
  13. .RETURNVALUE 
  14.    This script produces output as shown in the example 
  15. .LINK 
  16.     http://msdn.microsoft.com/en-us/library/fht0f5be.aspx 
  17.     http://www.pshscripts.blogspot.com  
  18. .EXAMPLE 
  19. PS C:\foo> . 'Get-StringFormat2.ps1' 
  20. (C) Currency: . . . . . . . . ($123.00) 
  21. (D) Decimal:. . . . . . . . . -123 
  22. (E) Scientific: . . . . . . . -1.234500E+002 
  23. (F) Fixed point:. . . . . . . -123.45 
  24. (G) General:. . . . . . . . . -123 
  25. (default):. .     . . . . . . -123 
  26. (N) Number: . . . . . . . . . -123.00 
  27. (P) Percent:. . . . . . . . . -12,345.00 % 
  28. (R) Round-trip: . . . . . . . -123.45 
  29. (X) Hexadecimal:. . . . . . . FFFFFF85 
  30.  
  31. Date Format 
  32. (d) Short date: . . . . . . . 12/25/2008 
  33. (D) Long date:. . . . . . . . Thursday, December 25, 2008 
  34. (t) Short time: . . . . . . . 2:12 PM 
  35. (T) Long time:. . . . . . . . 2:12:55 PM 
  36. (f) Full date/short time: . . Thursday, December 25, 2008 2:12 PM 
  37. (F) Full date/long time:. . . Thursday, December 25, 2008 2:12:55 PM 
  38. (g) General date/short time:. 12/25/2008 2:12 PM 
  39. (G) General date/long time: . 12/25/2008 2:12:55 PM 
  40.     (default):. . . . . . . . 12/25/2008 2:12:55 PM 
  41. (M) Month:. . . . . . . . . . December 25 
  42. (R) RFC1123:. . . . . . . . . Thu, 25 Dec 2008 14:12:55 GMT 
  43. (s) Sortable: . . . . . . . . 2008-12-25T14:12:55 
  44. (u) Universal sortable: . . . 2008-12-25 14:12:55Z 
  45. (U) Universal full date/time: Thursday, December 25, 2008 2:12:55 PM 
  46. (Y) Year: . . . . . . . . . . December, 2008 
  47.  
  48. Standard Enumeration Format Specifiers 
  49. (G) General:. . . . . . . . . Green 
  50.     (default):. . . . . . . . Green 
  51. (F) Flags:. . . . . . . . . . Green 
  52. (D) Decimal number: . . . . . 79 
  53. (X) Hexadecimal:. . . . . . . 0000004F 
  54. Standard Enumeration Format Specifiers (again) 
  55. (G) General:. . . . . . . . . Gainsboro 
  56.     (default):. . . . . . . . Gainsboro 
  57. (F) Flags:. . . . . . . . . . Gainsboro 
  58. (D) Decimal number: . . . . . 74 
  59. (X) Hexadecimal:. . . . . . . 0000004A 
  60. .EXAMPLE 
  61. PS C:\Users\tfl> Get-Help .\Get-StringFormat2.ps1' 
  62. Left as an exercise for the reader. 
  63. #> 
  64. ## 
  65. # Start of script 
  66. # #
  67. #Format a negative integer or floating-point number in various ways. 
  68. "Standard Numeric Format Specifiers" 
  69. "(C) Currency: . . . . . . . . {0:C}" -f -123, -123.45 
  70. "(D) Decimal:. . . . . . . . . {0:D}" -f -123, -123.45 
  71. "(E) Scientific: . . . . . . . {1:E}" -f -123, -123.45 
  72. "(F) Fixed point:. . . . . . . {1:F}" -f -123, -123.45 
  73. "(G) General:. . . . . . . . . {0:G}" -f -123, -123.45 
  74. "(default):. .     . . . . . . {0}  " -f -123, -123.45 
  75. "(N) Number: . . . . . . . . . {0:N}" -f -123, -123.45 
  76. "(P) Percent:. . . . . . . . . {1:P}" -f -123, -123.45 
  77. "(R) Round-trip: . . . . . . . {1:R}" -f -123, -123.45 
  78. "(X) Hexadecimal:. . . . . . . {0:X}" -f -123, -123.45 
  79. ""     
  80. # Format the current date in various ways. 
  81. $today = Get-Date 
  82. "Date Format" 
  83. "(d) Short date: . . . . . . . {0:d}" -f $today 
  84. "(D) Long date:. . . . . . . . {0:D}" -f $today 
  85. "(t) Short time: . . . . . . . {0:t}" -f $today 
  86. "(T) Long time:. . . . . . . . {0:T}" -f $today 
  87. "(f) Full date/short time: . . {0:f}" -f $today 
  88. "(F) Full date/long time:. . . {0:F}" -f $today 
  89. "(g) General date/short time:. {0:g}" -f $today 
  90. "(G) General date/long time: . {0:G}" -f $today 
  91. "    (default):. . . . . . . . {0} "  -f $today 
  92. "(M) Month:. . . . . . . . . . {0:M}" -f $today 
  93. "(R) RFC1123:. . . . . . . . . {0:R}" -f $today 
  94. "(s) Sortable: . . . . . . . . {0:s}" -f $today 
  95. "(u) Universal sortable: . . . {0:u}" -f $today 
  96. "(U) Universal full date/time: {0:U}" -f $today 
  97. "(Y) Year: . . . . . . . . . . {0:Y}" -f $today 
  98. "" 
  99. # Format a Color enumeration value in various ways. 
  100. "Standard Enumeration Format Specifiers" 
  101. "(G) General:. . . . . . . . . {0:G}" -f  [system.Drawing.KnownColor]::Green 
  102. "    (default):. . . . . . . . {0}"   -f  [system.Drawing.KnownColor]::Green 
  103. "(F) Flags:. . . . . . . . . . {0:F} " -f [system.Drawing.KnownColor]::Green 
  104. "(D) Decimal number: . . . . . {0:D} " -f [system.Drawing.KnownColor]::Green 
  105. "(X) Hexadecimal:. . . . . . . {0:X}" -f  [system.Drawing.KnownColor]::Green 
  106. "Standard Enumeration Format Specifiers (again)" 
  107. "(G) General:. . . . . . . . . {0:G}" -f  [system.Drawing.KnownColor]::Gainsboro 
  108. "    (default):. . . . . . . . {0}"   -f  [system.Drawing.KnownColor]::Gainsboro 
  109. "(F) Flags:. . . . . . . . . . {0:F} " -f [system.Drawing.KnownColor]::Gainsboro 
  110. "(D) Decimal number: . . . . . {0:D} " -f [system.Drawing.KnownColor]::Gainsboro 
  111. "(X) Hexadecimal:. . . . . . . {0:X}" -f  [system.Drawing.KnownColor]::Gainsboro
  112. # End of Script

Thursday, 25 December 2008

Get-Format1.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Demonstrates simple string formatting using Powershell 
  4. .DESCRIPTION 
  5.     This script formats 5 numbers in Decimal, Hex and Currency and is 
  6.     an adaptation of the C# sample in the MSDN Library 
  7. .NOTES 
  8.     Author   : Thomas Lee - tfl@psp.co.uk 
  9. .INPUTTYPE 
  10.    This script has no effective parameters. 
  11. .RETURNVALUE 
  12.    This script produces a short table of output, as shown in the Example. 
  13. .LINK 
  14.     http:////msdn.microsoft.com/en-us/library/fht0f5be.aspx 
  15.     http://www.pshscripts.blogspot.com 
  16. .EXAMPLE 
  17.    PS C:\foo> .\Get-StringFormat1.ps1  
  18.    Decimal         Hex        Currency 
  19.     -32768:       8000   ($32,768.00) 
  20.        -27:   FFFFFFE5       ($27.00) 
  21.          0:          0          $0.00 
  22.       1042:        412      $1,042.00 
  23.      32767:       7FFF     $32,767.00 
  24. #> 
  25.  
  26. # Create an array of values to display 
  27. $values = [Int16]::MinValue, -27, 0, 1042, [Int16]::maxValue 
  28.  
  29. # Print header line then values 
  30.  "{0,10}  {1,10}  {2,14}" -f "Decimal", "Hex", "Currency" 
  31. foreach ($value in $values) { 
  32.     "{0,10:G}: {0,10:X} {0,14:C}" -f $value 

Wednesday, 24 December 2008

Get-EvenNumber.ps1

  1. # Requires –Version:2.0 
  2. # Get-EvenNumber.ps1 
  3. # Gets an even number 
  4. # Demonstrates Version 2 functionality 
  5. # Updates Andget-=y Schneider's example at 
  6. # http://get-powershell.com/2008/12/23/industrial-strength-functions-in-powershell-v2-ctp-3/ 
  7.  
  8. function Get-EvenNumber { 
  9. #.Synopsis 
  10. #    Detects and reports on even numbers using the Modulo operator (%) 
  11. #.Description 
  12. #    Takes a pipeline of values and tells you the numbers that are are even  
  13. #    integers. PowerShell detects non-integers.  At the end, this function 
  14. #    tells you how many numbers were processed and how many were even. Non-Inteers 
  15. #    are not reported. 
  16. #.Parameter number 
  17. #    One or more integers - values can come from the pipeline as well    
  18. #.Example 
  19. #    1..10 | Get-EvenNumber 
  20. #.Example 
  21. #    1,2,3,4,"foo" | get-EvenNumber
  22. #    (Generates an error) 
  23.  
  24. param
  25. [Parameter(Position=0,  
  26. Mandatory=$true,  
  27. ValueFromPipeline=$true,  
  28. HelpMessage="Please type a integer")] 
  29. [Alias("integer")] [int32] 
  30.  $number 
  31. # Begin block - just type out a greeting and initialise 
  32. begin {"Beginning of Pipeline";  
  33.        $i=$j=0 
  34.  
  35. process { 
  36.  $i++  
  37.  if (($number % 2) -eq 0) {"$number is even"; $j++} 
  38.  
  39. end { 
  40. "End of Pipeline";  
  41. "{0} integers processed" -f $i;  
  42. "{0} were even" -f $j 

This script produces the following output:

PS C:\foo> 1..10 | Get-EvenNumber
Beginning of Pipeline
2 is even
4 is even
6 is even
8 is even
10 is even
End of Pipeline
10 integers processed
5 were even

PS C:\foo> -22,200000,2 | Get-EvenNumber
Beginning of Pipeline
-22 is even
200000 is even
2 is even
End of Pipeline
3 integers processed
3 were even


PS C:\foo> "foo" | Get-EvenNumber
Begining of Pipeline
Get-EvenNumber : Cannot process argument transformation on parameter 'number'. Cannot convert value "foo" to type "System.Int32". Error:
"Input string was not in a correct format."
At line:1 char:23
+ "foo" | Get-EvenNumber <<<<
    + CategoryInfo          : InvalidData: (foo:String) [Get-EvenNumber], ParameterBindin...mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-EvenNumber

End of Pipeline
0 integers processed
0 were even

PS C:\foo> 123456789012 | Get-EvenNumber
Begining of Pipeline
Get-EvenNumber : Cannot process argument transformation on parameter 'number'. Cannot convert value "123456789012" to type "System.Int32"
. Error: "Value was either too large or too small for an Int32."
At line:1 char:30
+ 123456789012 | Get-EvenNumber <<<<
    + CategoryInfo          : InvalidData: (123456789012:Int64) [Get-EvenNumber], ParameterBindin...mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-EvenNumber

End of Pipeline
0 integers processed
0 were even

PS C:\foo> Get-Help Get-EvenNumber -Full

NAME
    Get-EvenNumber

SYNOPSIS
    Detects and reports on even numbers using the Modulo operator (%)

SYNTAX
    Get-EvenNumber [-number] [<Int32>] [-Verbose] [-Debug] [-ErrorAction [<ActionPreference>]] [-WarningAction [<ActionPreference>]] [-Er
    rorVariable [<String>]] [-WarningVariable [<String>]] [-OutVariable [<String>]] [-OutBuffer [<Int32>]] [<CommonParameters>]

DETAILED DESCRIPTION
    Takes a pipeline of values and tells you the numbers that are are even
    integers. PowerShell detects non-integers.  At the end, this function
    tells you how many numbers were processed and how many were even. Non-Inteers
    are not reported.

PARAMETERS
    -number
        One or more integers - values can come from the pipeline as well

        Required?                    true
        Position?                    0
        Default value
        Accept pipeline input?       true (ByValue)
        Accept wildcard characters?

    <CommonParameters>
        This cmdlet supports the common parameters: -Verbose, -Debug,
        -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
        -OutBuffer and -OutVariable. For more information, type,
        "get-help about_commonparameters".

INPUT TYPE

RETURN TYPE

    -------------------------- EXAMPLE 1 --------------------------

    1..10 | Get-EvenNumber

    -------------------------- EXAMPLE 2 --------------------------

    1,2,3,4,"foo" | get-EvenNumber
    (Generates an error)

Tuesday, 23 December 2008

Get-FileCount.ps1

  1. # Get-FileCount.ps1 
  2. # Uses shell.application to get a count of files in a folder 
  3. # Thomas Lee - tfl@psp.co.uk 
  4.  
  5. # First get shell object 
  6. $Shell = new-object -com Shell.Application 
  7.  
  8. # Now get folder details and item counts for a folder 
  9. $foldername = "D:\Foo" 
  10. $folder = $shell.namespace($foldername
  11. if (!$folder) { 
  12. "Folder: {0} does not exist" -f $foldername 
  13. return 
  14.  
  15. # Now output the count of folders 
  16. if ($folder) {  
  17.  $folderitems = $folder.items()  
  18.  $count = $folderitems.count  
  19.  
  20.  $folderps1items = $folderitems | where {$_.type -eq "PS1 File"
  21.  $countps1items=$folderps1items.count 
  22.   
  23.  "Folder `"{0}`" contains {1} files"     -f $foldername, $count 
  24.  "Folder `"{0}`" contains {1} PS1 files" -f $foldername, $countps1items 

This script produces the following output:

PSH [D:\foo]: .\shell.application\Get-FileCount.PS1'
Folder "D:\Foo" contains 38 files
Folder "D:\Foo" contains 22 PS1 files

Monday, 22 December 2008

Get-ParsedString.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Formats a number using .NET - an MSDN Sample recoded in PowerShell 
  4. .DESCRIPTION 
  5.     This script createa a number and formats it in Hex. Then a negative number 
  6.     is created and formatted several ways. Uses int32.parse method to do the  
  7.     parsing. 
  8. .NOTES 
  9.     File Name  : Get-ParsedString 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell V2 CTP3 
  12. .LINK 
  13.     Posted to: 
  14.     http://pshscripts.blogspot.com/2008/12/get-parsedstringps1.html 
  15.     Script also posted to MSDN at: 
  16.     http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles(VS.85).aspx 
  17. .EXAMPLE 
  18.     PS c:\foo> .\Get-ParsedString.ps1 
  19.     A in hex = 10 in decimal 
  20.     '    -42    ' parsed to an int32 is '-42'
  21.     '    (42)   ' parsed to an int32 is '-42'
  22. #> 
  23.  
  24.  
  25. ### 
  26. #  Start of Script 
  27. ### 
  28.  
  29. # Parse the string as a hex value and display the value as a decimal. 
  30. $num = "A" 
  31. $val = [system.int32]::Parse($num, [System.Globalization.NumberStyles]::HexNumber) 
  32.  
  33. "{0} in hex = {1} in decimal" -f $num,$val 
  34.  
  35. # Parse the string, allowing a leading sign, and ignoring leading and trailing white spaces. 
  36. $num = "    -42    " 
  37.  
  38. # create parsing value using value__ 
  39. $format  = [System.Globalization.NumberStyles]::AllowLeadingSign.value__+ 
  40.            [System.Globalization.NumberStyles]::AllowLeadingWhite.value__ + 
  41.            [System.Globalization.NumberStyles]::AllowTrailingWhite.value__   
  42. $parsing = [System.Globalization.NumberStyles] $format      
  43.  
  44. # parse and display 
  45. $val = [system.int32]::Parse($num,$parsing
  46. "'{0}' parsed to an int32 is '{1}'." -f $num, $val 
  47.  
  48. # Now try a negative number 
  49. $num = "    (42)   " 
  50. $format  = [System.Globalization.NumberStyles]::AllowParentheses.value__  + 
  51.            [System.Globalization.NumberStyles]::AllowLeadingSign.value__  + 
  52.            [System.Globalization.NumberStyles]::AllowLeadingWhite.value__ + 
  53.            [System.Globalization.NumberStyles]::AllowTrailingWhite.value__ 
  54. $parsing = [System.Globalization.NumberStyles] $format              
  55.  
  56. # And parse/display it 
  57. $val = [system.int32]::Parse($num, $parsing
  58. "'{0}' parsed to an int32 is '{1}'." -f $num, $val 

Sunday, 21 December 2008

Get-RegexTest.ps1

  1. # Get-RegexTest.ps1 
  2. # Sample Using PowerShell 
  3. # Thomas Lee - tfl@psp.co.uk 
  4.  
  5. # Define a regular expression for currency values. 
  6. $rx = New-Object system.text.RegularExpressions.Regex "^-?\d+(\.\d{2})?$" 
  7.  
  8. # Define tests 
  9. $tests = "-42", "19.99", "0.001", "100 USD", ".34", "0.34", "1,052.21", "Jerry Garcia" 
  10.  
  11. # Now test and report 
  12. foreach ($test in $tests)  { 
  13. if ($rx.IsMatch($test)) { 
  14. "{0} is a currency value." -f $test 
  15. else
  16. "{0} is not a currency value." -f $test 
  17. }     

This script produces the following output:

PS C:\foo> .\GetRegexTest.ps1'
-42 is a currency value.
19.99 is a currency value.
0.001 is not a currency value.
100 USD is not a currency value.
.34 is not a currency value.
0.34 is a currency value.
1,052.21 is not a currency value.
Jerry Garcia is not a currency value.

Saturday, 20 December 2008

Get-FirewallDetails.ps1

  1. # Get-FirewallDetails.ps1 
  2. # Gets details of Windows Firewall (on Vista and Server 2008 or later) 
  3. # Runs on the local machine 
  4. # Thomas Lee - tfl@psp.co.uk 
  5.  
  6. # First create COM object for policy profile and get host name 
  7. $profile = (new-object -com HNetCfg.FwMgr).LocalPolicy.CurrentProfile 
  8. $Hostname=hostname 
  9.  
  10. # Is firewall enabled? 
  11. if ($profile.FirewallEnabled) { 
  12. "Firewall is enabled on system {0}" -f $Hostname 
  13. else
  14. "Firewall is NOT enabled on system {0}" -f $Hostname 
  15.  
  16. # Exceptions allowed? 
  17. if ($profile.ExceptionsNotAllowed) {"Exceptions NOT allowed"}  
  18. else {"Exceptions are allowed"
  19.  
  20. # Notifications? 
  21. if ($profile.NotificationsDisabled) {"Notifications are disabled"
  22. else {"Notifications are not disabled"
  23.  
  24. # Display determine global open ports  
  25. $ports = $profile.GloballyOpenPorts  
  26. if (!$ports -or $ports.count -eq 0) { 
  27. "There are no global open ports" 
  28. else
  29. "There are {0} open ports as follows:" -f $ports.count 
  30. $ports 
  31. "" 
  32.  
  33. # Display ICMP settings 
  34. "ICMP Settings:" 
  35. $profile.IcmpSettings 
  36.  
  37. # Display authorised applications 
  38. $apps = $profile.AuthorizedApplications  
  39. # 
  40. if (!$apps) { 
  41. "There are no authorised applications" 
  42. else
  43. "There are {0} global applications as follows:" -f $apps.count 
  44. $apps  
  45.  
  46. # Display authorised services 
  47. $services = $profile.services 
  48. # 
  49. if (!$services) { 
  50. "There are no authorised services" 
  51. else
  52. "There are {0} authorised services as follows:" -f $services.count 
  53. $services 

This script produces the following output:

PS C:\foo> .\Get-FirewallDetails.ps1
Firewall is enabled on system Cookham8
Exceptions are allowed
Notifications are disabled
There are no global open ports

ICMP Settings:
AllowOutboundDestinationUnreachable : False
AllowRedirect                       : False
AllowInboundEchoRequest             : True
AllowOutboundTimeExceeded           : False
AllowOutboundParameterProblem       : False
AllowOutboundSourceQuench           : False
AllowInboundRouterRequest           : False
AllowInboundTimestampRequest        : False
AllowInboundMaskRequest             : False
AllowOutboundPacketTooBig           : True

There are 4 global applications as follows:
Name                 : BitTorrent
ProcessImageFileName : C:\Program Files (x86)\BitTorrent\bittorrent.exe
IpVersion            : 2
Scope                : 0
RemoteAddresses      : *
Enabled              : True

Name                 : DNA
ProcessImageFileName : C:\Program Files (x86)\DNA\btdna.exe
IpVersion            : 2
Scope                : 0
RemoteAddresses      : *
Enabled              : True

Name                 : Microsoft Office OneNote
ProcessImageFileName : C:\Program Files (x86)\Microsoft Office\Office12\ONENOTE.EXE
IpVersion            : 2
Scope                : 0
RemoteAddresses      : *
Enabled              : True

Name                 : Microsoft Office Groove
ProcessImageFileName : C:\Program Files (x86)\Microsoft Office\Office12\GROOVE.EXE
IpVersion            : 2
Scope                : 0
RemoteAddresses      : *
Enabled              : True

There are 3 authorised services as follows:
Name              : File and Printer Sharing
Type              : 0
Customized        : False
IpVersion         : 2
Scope             : 0
RemoteAddresses   : *
Enabled           : True
GloballyOpenPorts : System.__ComObject

Name              : Network Discovery
Type              : 1
Customized        : True
IpVersion         : 2
Scope             : 1
RemoteAddresses   : LocalSubnet
Enabled           : True
GloballyOpenPorts : System.__ComObject

Name              : Remote Desktop
Type              : 2
Customized        : False
IpVersion         : 2
Scope             : 0
RemoteAddresses   : *
Enabled           : False
GloballyOpenPorts : System.__ComObject

Friday, 19 December 2008

Get-DomainModeEnumValues.ps1

 

  1. # Get-DomainModeEnumValues.ps1 
  2. # Prints out the values of the DomainMode Enum 
  3. # Thomas Lee - tfl@psp.co.uk 
  4.  
  5. # Enumerate System.DirectoryServices.ActiveDirectory.DomainMode 
  6.  
  7. $enums=[enum]::GetValues([System.DirectoryServices.ActiveDirectory.DomainMode]) 
  8.  
  9. # Display values 
  10. "System.Net.DirectoryServices.ActiveDirectory.DomainMode enum has {0} possible values:" -f $enums.count 
  11. $i=1 
  12. $enums | %{"Value {0}: {1}" -f $i,$_.tostring();$i++} 
  13. ""  
  14.  
  15. # Checking against an enum value  
  16. $ToCheck = "Windows2008Domain" 
  17. if ($ToCheck -eq  [System.DirectoryServices.ActiveDirectory.DomainMode]::Windows2008Domain) { 
  18. "`$ToCheck is Windows2008Domain" 
  19.     } 
  20. else
  21.     "`$ToCheck is NOT Windows2008Domain" 
  22.     } 

This script produces the following output:

PS C:\Foo> .\Get-DomainModeEnumValues.ps1
System.Net.DirectoryServices.ActiveDirectory.DomainMode enum has 5 possible values:
Value 1: Windows2000MixedDomain
Value 2: Windows2000NativeDomain
Value 3: Windows2003InterimDomain
Value 4: Windows2003Domain
Value 5: Windows2008Domain

$ToCheck is Windows2008Domain