- <#
- .SYNOPSIS
- Gets stock quotes using a web servoice
- .DESCRIPTION
- This function uses the New-WebServiceProxy cmdlet to
- create a web service proxy. Then it calls that proxy
- to get stock information.
- .NOTES
- File Name : get-stockquote.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell V2 CTP3
- .LINK
- Original post:
- http://PoshCode.org/embed/752
- Updated script posted:
- http://www.pshscripts.blogspot.com
- .INPUTTYPE
- String(s) representing stock tickers to find
- .RETURNVALUE
- XML Element, holding stock details
- .EXAMPLE
- Run from PowerShell Prompt:
- Get-StockQuote "MSFT"
- Output - left as an exercise for the reader
- .EXAMPLE
- Run from Pipeline
- "IBM","INTC" | Get-StockQuote
- Output - left as an exercise for the reader
- .PARAMETER TICKER
- A string, or array of strings representing stock tickers
- The function gets stock details for each stock ticker provided
- #>
- function Get-StockQuote {
- param(
- [Parameter(Position=0, Mandatory=$FALSE, ValueFromPipeline=$TRUE)]
- [String] $TICKER="MSFT" )
- process {
- $ticker
- $s = new-webserviceproxy -uri http://www.webservicex.net/stockquote.asmx
- foreach ($symbol in $ticker) {
- $result = [xml]$s.GetQuote($symbol)
- $result.StockQuotes.Stock
- } # end foreach
- } #end process block
- } # end function
- "Example 1:"
- "=========="
- Get-StockQuote MSFT
- ""
- "Example 2:"
- "=========="
- "IBM","INTC" | Get-StockQuote
This blog contains PowerShell scripts, more PowerShell scripts and still more PowerShell scripts. Occasionally you may see some organisational posts.
Tuesday, 30 December 2008
Get-StockQuote.ps1
Monday, 29 December 2008
Validate-EmailAddress.ps1
- <#
- .SYNOPSIS
- Validates an email address using a web service
- .DESCRIPTION
- This script uses the New-WebServiceProxy cmdlet to
- create a web service proxy. Then it calls that proxy
- to Validate an email address.
- .NOTES
- File Name : validate-emailaddress.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell V2 CTP3
- .LINK
- Script posted to:
- http://www.pshscripts.blogspot.com
- .INPUTTYPE
- String(s) representing email address to validate
- .RETURNVALUE
- [Boolean] - whether email address was valid
- .EXAMPLE
- Run from PowerShell Prompt:
- PS C:\foo> .\Validate-EmailAddress "tfl@psp.co.uk”
- True
- .EXAMPLE
- Run from Pipeline:
- PS C:\foo> "tfl@psp.co.uk", "foo@foo.bar" | .\Validate-EmailAddress
- True
- False
- .PARAMETER addr
- A string, or array of strings representing email addresses to check
- #>
- param(
- [Parameter(Position=0, Mandatory=$FALSE, ValueFromPipeline=$TRUE)]
- [String] $Addr = "doctordns@gmail.com" )
- process {
- $s = new-webserviceproxy -uri http://www.webservicex.net/validateEmail.asmx
- foreach ($a in $addr) {
- $result = $s.IsValidEmail($a)
- $result
- } # end foreach
- } #end process block
Sunday, 28 December 2008
Get-AutoHelp.ps1
- <#
- .SYNOPSIS
- A summary of what this script does
- In this case, this script documents the auto-help text
- in PowerShell CTP 3
- Appears in all basic, -detailed, -full, -examples
- .DESCRIPTION
- A more in depth description of the script
- Should give script developer more things to talk about
- Hopefully this can help the community too
- Becomes: "DETAILED DESCRIPTION"
- Appears in basic, -full and -detailed
- .NOTES
- Additional Notes, eg
- File Name : get-autohelp.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell V2 CTP3
- Appears in -full
- .LINK
- A hyper link, eg
- http://www.pshscripts.blogspot.com/2008/12/get-autohelpps1.html
- Becomes: "RELATED LINKS"
- Appears in basic and -Full
- .EXAMPLE
- The first example - just text documentation
- You should provide a way of calling the script, plus
- any expected output, eg:
- C:\foo> .\get-autohelp.ps1 42
- The meaning of life is 42
- Appears in -detailed and -full
- .EXAMPLE
- The second example - more text documentation
- This would be an example calling the script differently. You
- have lots and lots, and lots of examples if this is useful.
- Appears in -detailed and -full
- .INPUTTYPE
- Documentary text, eg:
- Input type [Universal.SolarSystem.Planetary.CommonSense]
- Appears in -full
- .RETURNVALUE
- Documentary Text, e,g:
- Output type [Universal.SolarSystem.Planetary.Wisdom]
- Appears in -full
- .COMPONENT
- Not sure how to specify or use
- Does not appear in basic, -full, or -detailed
- Should appear in -component
- .ROLE
- Not sure How to specify or use
- Does not appear in basic, -full, or -detailed
- Should appear with -role
- .FUNCTIONALITY
- Not sure How to specify or use
- Does not appear in basic, -full, or -detailed
- Should appear with -functionality
- .PARAMETER foo
- The .Parameter area in the script is used to derive the
- of the PARAMETERS in Get-Help output which documents the
- parameters in the param block. The section takes a
- value (in this case foo, the name of the first actual
- parameter), and only appears if there is parameter of
- that name in the param block. Having a section for a
- parameter that does not exist generate no extra output
- of this section
- Appears in -detailed, -full (with more info than in -det)
- Appears in -Parameter (need to specify the parameter name)
- .PARAMETER bar
- Example of a parameter definition for a parameter that does not exist.
- Does not appear at all.
- #>
- # Note above section does not contain entries for NAME, SYNTAX
- # and REMARKS sections of in get-help output
- #
- # These sections appear as follows:
- # NAME - generated from the name passed to get-help.
- # SYNTAX - generated from param block details.
- # REMARKS - generated based on script name (e.g. what's shown in NAME)
- # inserted into some static text.
- #
- # Not sure how to generate/document -component, -role, -functionality
- # Not sure how to generate/use -category
- param (
- [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
- [int64] $foo=42
- )
- "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
- <#
- .SYNOPSIS
- Demonstrates string formatting using Powershell
- .DESCRIPTION
- This script formats 2 numbers in a variety of ways, also
- formats an enum.
- An adaptation of the C# sample in the MSDN Library. However,
- this script uses a built-in enum, and displays two.
- .NOTES
- Author : Thomas Lee - tfl@psp.co.uk
- .INPUTTYPE
- This script has no effective parameters.
- .RETURNVALUE
- This script produces output as shown in the example
- .LINK
- http://msdn.microsoft.com/en-us/library/fht0f5be.aspx
- http://www.pshscripts.blogspot.com
- .EXAMPLE
- PS C:\foo> . 'Get-StringFormat2.ps1'
- (C) Currency: . . . . . . . . ($123.00)
- (D) Decimal:. . . . . . . . . -123
- (E) Scientific: . . . . . . . -1.234500E+002
- (F) Fixed point:. . . . . . . -123.45
- (G) General:. . . . . . . . . -123
- (default):. . . . . . . . -123
- (N) Number: . . . . . . . . . -123.00
- (P) Percent:. . . . . . . . . -12,345.00 %
- (R) Round-trip: . . . . . . . -123.45
- (X) Hexadecimal:. . . . . . . FFFFFF85
- Date Format
- (d) Short date: . . . . . . . 12/25/2008
- (D) Long date:. . . . . . . . Thursday, December 25, 2008
- (t) Short time: . . . . . . . 2:12 PM
- (T) Long time:. . . . . . . . 2:12:55 PM
- (f) Full date/short time: . . Thursday, December 25, 2008 2:12 PM
- (F) Full date/long time:. . . Thursday, December 25, 2008 2:12:55 PM
- (g) General date/short time:. 12/25/2008 2:12 PM
- (G) General date/long time: . 12/25/2008 2:12:55 PM
- (default):. . . . . . . . 12/25/2008 2:12:55 PM
- (M) Month:. . . . . . . . . . December 25
- (R) RFC1123:. . . . . . . . . Thu, 25 Dec 2008 14:12:55 GMT
- (s) Sortable: . . . . . . . . 2008-12-25T14:12:55
- (u) Universal sortable: . . . 2008-12-25 14:12:55Z
- (U) Universal full date/time: Thursday, December 25, 2008 2:12:55 PM
- (Y) Year: . . . . . . . . . . December, 2008
- Standard Enumeration Format Specifiers
- (G) General:. . . . . . . . . Green
- (default):. . . . . . . . Green
- (F) Flags:. . . . . . . . . . Green
- (D) Decimal number: . . . . . 79
- (X) Hexadecimal:. . . . . . . 0000004F
- Standard Enumeration Format Specifiers (again)
- (G) General:. . . . . . . . . Gainsboro
- (default):. . . . . . . . Gainsboro
- (F) Flags:. . . . . . . . . . Gainsboro
- (D) Decimal number: . . . . . 74
- (X) Hexadecimal:. . . . . . . 0000004A
- .EXAMPLE
- PS C:\Users\tfl> Get-Help .\Get-StringFormat2.ps1'
- Left as an exercise for the reader.
- #>
- ##
- # Start of script
- # #
- #Format a negative integer or floating-point number in various ways.
- "Standard Numeric Format Specifiers"
- "(C) Currency: . . . . . . . . {0:C}" -f -123, -123.45
- "(D) Decimal:. . . . . . . . . {0:D}" -f -123, -123.45
- "(E) Scientific: . . . . . . . {1:E}" -f -123, -123.45
- "(F) Fixed point:. . . . . . . {1:F}" -f -123, -123.45
- "(G) General:. . . . . . . . . {0:G}" -f -123, -123.45
- "(default):. . . . . . . . {0} " -f -123, -123.45
- "(N) Number: . . . . . . . . . {0:N}" -f -123, -123.45
- "(P) Percent:. . . . . . . . . {1:P}" -f -123, -123.45
- "(R) Round-trip: . . . . . . . {1:R}" -f -123, -123.45
- "(X) Hexadecimal:. . . . . . . {0:X}" -f -123, -123.45
- ""
- # Format the current date in various ways.
- $today = Get-Date
- "Date Format"
- "(d) Short date: . . . . . . . {0:d}" -f $today
- "(D) Long date:. . . . . . . . {0:D}" -f $today
- "(t) Short time: . . . . . . . {0:t}" -f $today
- "(T) Long time:. . . . . . . . {0:T}" -f $today
- "(f) Full date/short time: . . {0:f}" -f $today
- "(F) Full date/long time:. . . {0:F}" -f $today
- "(g) General date/short time:. {0:g}" -f $today
- "(G) General date/long time: . {0:G}" -f $today
- " (default):. . . . . . . . {0} " -f $today
- "(M) Month:. . . . . . . . . . {0:M}" -f $today
- "(R) RFC1123:. . . . . . . . . {0:R}" -f $today
- "(s) Sortable: . . . . . . . . {0:s}" -f $today
- "(u) Universal sortable: . . . {0:u}" -f $today
- "(U) Universal full date/time: {0:U}" -f $today
- "(Y) Year: . . . . . . . . . . {0:Y}" -f $today
- ""
- # Format a Color enumeration value in various ways.
- "Standard Enumeration Format Specifiers"
- "(G) General:. . . . . . . . . {0:G}" -f [system.Drawing.KnownColor]::Green
- " (default):. . . . . . . . {0}" -f [system.Drawing.KnownColor]::Green
- "(F) Flags:. . . . . . . . . . {0:F} " -f [system.Drawing.KnownColor]::Green
- "(D) Decimal number: . . . . . {0:D} " -f [system.Drawing.KnownColor]::Green
- "(X) Hexadecimal:. . . . . . . {0:X}" -f [system.Drawing.KnownColor]::Green
- "Standard Enumeration Format Specifiers (again)"
- "(G) General:. . . . . . . . . {0:G}" -f [system.Drawing.KnownColor]::Gainsboro
- " (default):. . . . . . . . {0}" -f [system.Drawing.KnownColor]::Gainsboro
- "(F) Flags:. . . . . . . . . . {0:F} " -f [system.Drawing.KnownColor]::Gainsboro
- "(D) Decimal number: . . . . . {0:D} " -f [system.Drawing.KnownColor]::Gainsboro
- "(X) Hexadecimal:. . . . . . . {0:X}" -f [system.Drawing.KnownColor]::Gainsboro
- # End of Script
Thursday, 25 December 2008
Get-Format1.ps1
- <#
- .SYNOPSIS
- Demonstrates simple string formatting using Powershell
- .DESCRIPTION
- This script formats 5 numbers in Decimal, Hex and Currency and is
- an adaptation of the C# sample in the MSDN Library
- .NOTES
- Author : Thomas Lee - tfl@psp.co.uk
- .INPUTTYPE
- This script has no effective parameters.
- .RETURNVALUE
- This script produces a short table of output, as shown in the Example.
- .LINK
- http:////msdn.microsoft.com/en-us/library/fht0f5be.aspx
- http://www.pshscripts.blogspot.com
- .EXAMPLE
- PS C:\foo> .\Get-StringFormat1.ps1
- Decimal Hex Currency
- -32768: 8000 ($32,768.00)
- -27: FFFFFFE5 ($27.00)
- 0: 0 $0.00
- 1042: 412 $1,042.00
- 32767: 7FFF $32,767.00
- #>
- # Create an array of values to display
- $values = [Int16]::MinValue, -27, 0, 1042, [Int16]::maxValue
- # Print header line then values
- "{0,10} {1,10} {2,14}" -f "Decimal", "Hex", "Currency"
- foreach ($value in $values) {
- "{0,10:G}: {0,10:X} {0,14:C}" -f $value
- }
Wednesday, 24 December 2008
Get-EvenNumber.ps1
- # Requires –Version:2.0
- # Get-EvenNumber.ps1
- # Gets an even number
- # Demonstrates Version 2 functionality
- # Updates Andget-=y Schneider's example at
- # http://get-powershell.com/2008/12/23/industrial-strength-functions-in-powershell-v2-ctp-3/
- function Get-EvenNumber {
- #.Synopsis
- # Detects and reports on even numbers using the Modulo operator (%)
- #.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.
- #.Parameter number
- # One or more integers - values can come from the pipeline as well
- #.Example
- # 1..10 | Get-EvenNumber
- #.Example
- # 1,2,3,4,"foo" | get-EvenNumber
- # (Generates an error)
- param (
- [Parameter(Position=0,
- Mandatory=$true,
- ValueFromPipeline=$true,
- HelpMessage="Please type a integer")]
- [Alias("integer")] [int32]
- $number
- )
- # Begin block - just type out a greeting and initialise
- begin {"Beginning of Pipeline";
- $i=$j=0
- }
- process {
- $i++
- if (($number % 2) -eq 0) {"$number is even"; $j++}
- }
- end {
- "End of Pipeline";
- "{0} integers processed" -f $i;
- "{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 evenPS 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-EvenNumberEnd of Pipeline
0 integers processed
0 were evenPS 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-EvenNumberEnd of Pipeline
0 integers processed
0 were evenPS C:\foo> Get-Help Get-EvenNumber -Full
NAME
Get-EvenNumberSYNOPSIS
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 wellRequired? 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
- # Get-FileCount.ps1
- # Uses shell.application to get a count of files in a folder
- # Thomas Lee - tfl@psp.co.uk
- # First get shell object
- $Shell = new-object -com Shell.Application
- # Now get folder details and item counts for a folder
- $foldername = "D:\Foo"
- $folder = $shell.namespace($foldername)
- if (!$folder) {
- "Folder: {0} does not exist" -f $foldername
- return
- }
- # Now output the count of folders
- if ($folder) {
- $folderitems = $folder.items()
- $count = $folderitems.count
- $folderps1items = $folderitems | where {$_.type -eq "PS1 File"}
- $countps1items=$folderps1items.count
- "Folder `"{0}`" contains {1} files" -f $foldername, $count
- "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
- <#
- .SYNOPSIS
- Formats a number using .NET - an MSDN Sample recoded in PowerShell
- .DESCRIPTION
- This script createa a number and formats it in Hex. Then a negative number
- is created and formatted several ways. Uses int32.parse method to do the
- parsing.
- .NOTES
- File Name : Get-ParsedString
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell V2 CTP3
- .LINK
- Posted to:
- http://pshscripts.blogspot.com/2008/12/get-parsedstringps1.html
- Script also posted to MSDN at:
- http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles(VS.85).aspx
- .EXAMPLE
- PS c:\foo> .\Get-ParsedString.ps1
- A in hex = 10 in decimal
- ' -42 ' parsed to an int32 is '-42'.
- ' (42) ' parsed to an int32 is '-42'.
- #>
- ###
- # Start of Script
- ###
- # Parse the string as a hex value and display the value as a decimal.
- $num = "A"
- $val = [system.int32]::Parse($num, [System.Globalization.NumberStyles]::HexNumber)
- "{0} in hex = {1} in decimal" -f $num,$val
- # Parse the string, allowing a leading sign, and ignoring leading and trailing white spaces.
- $num = " -42 "
- # create parsing value using value__
- $format = [System.Globalization.NumberStyles]::AllowLeadingSign.value__+
- [System.Globalization.NumberStyles]::AllowLeadingWhite.value__ +
- [System.Globalization.NumberStyles]::AllowTrailingWhite.value__
- $parsing = [System.Globalization.NumberStyles] $format
- # parse and display
- $val = [system.int32]::Parse($num,$parsing)
- "'{0}' parsed to an int32 is '{1}'." -f $num, $val
- # Now try a negative number
- $num = " (42) "
- $format = [System.Globalization.NumberStyles]::AllowParentheses.value__ +
- [System.Globalization.NumberStyles]::AllowLeadingSign.value__ +
- [System.Globalization.NumberStyles]::AllowLeadingWhite.value__ +
- [System.Globalization.NumberStyles]::AllowTrailingWhite.value__
- $parsing = [System.Globalization.NumberStyles] $format
- # And parse/display it
- $val = [system.int32]::Parse($num, $parsing)
- "'{0}' parsed to an int32 is '{1}'." -f $num, $val
Sunday, 21 December 2008
Get-RegexTest.ps1
- # Get-RegexTest.ps1
- # Sample Using PowerShell
- # Thomas Lee - tfl@psp.co.uk
- # Define a regular expression for currency values.
- $rx = New-Object system.text.RegularExpressions.Regex "^-?\d+(\.\d{2})?$"
- # Define tests
- $tests = "-42", "19.99", "0.001", "100 USD", ".34", "0.34", "1,052.21", "Jerry Garcia"
- # Now test and report
- foreach ($test in $tests) {
- if ($rx.IsMatch($test)) {
- "{0} is a currency value." -f $test
- }
- else {
- "{0} is not a currency value." -f $test
- }
- }
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
- # Get-FirewallDetails.ps1
- # Gets details of Windows Firewall (on Vista and Server 2008 or later)
- # Runs on the local machine
- # Thomas Lee - tfl@psp.co.uk
- # First create COM object for policy profile and get host name
- $profile = (new-object -com HNetCfg.FwMgr).LocalPolicy.CurrentProfile
- $Hostname=hostname
- # Is firewall enabled?
- if ($profile.FirewallEnabled) {
- "Firewall is enabled on system {0}" -f $Hostname
- }
- else {
- "Firewall is NOT enabled on system {0}" -f $Hostname
- }
- # Exceptions allowed?
- if ($profile.ExceptionsNotAllowed) {"Exceptions NOT allowed"}
- else {"Exceptions are allowed"}
- # Notifications?
- if ($profile.NotificationsDisabled) {"Notifications are disabled"}
- else {"Notifications are not disabled"}
- # Display determine global open ports
- $ports = $profile.GloballyOpenPorts
- if (!$ports -or $ports.count -eq 0) {
- "There are no global open ports"
- }
- else {
- "There are {0} open ports as follows:" -f $ports.count
- $ports
- }
- ""
- # Display ICMP settings
- "ICMP Settings:"
- $profile.IcmpSettings
- # Display authorised applications
- $apps = $profile.AuthorizedApplications
- #
- if (!$apps) {
- "There are no authorised applications"
- }
- else {
- "There are {0} global applications as follows:" -f $apps.count
- $apps
- }
- # Display authorised services
- $services = $profile.services
- #
- if (!$services) {
- "There are no authorised services"
- }
- else {
- "There are {0} authorised services as follows:" -f $services.count
- $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 portsICMP Settings:
AllowOutboundDestinationUnreachable : False
AllowRedirect : False
AllowInboundEchoRequest : True
AllowOutboundTimeExceeded : False
AllowOutboundParameterProblem : False
AllowOutboundSourceQuench : False
AllowInboundRouterRequest : False
AllowInboundTimestampRequest : False
AllowInboundMaskRequest : False
AllowOutboundPacketTooBig : TrueThere are 4 global applications as follows:
Name : BitTorrent
ProcessImageFileName : C:\Program Files (x86)\BitTorrent\bittorrent.exe
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : TrueName : DNA
ProcessImageFileName : C:\Program Files (x86)\DNA\btdna.exe
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : TrueName : Microsoft Office OneNote
ProcessImageFileName : C:\Program Files (x86)\Microsoft Office\Office12\ONENOTE.EXE
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : TrueName : Microsoft Office Groove
ProcessImageFileName : C:\Program Files (x86)\Microsoft Office\Office12\GROOVE.EXE
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : TrueThere are 3 authorised services as follows:
Name : File and Printer Sharing
Type : 0
Customized : False
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : True
GloballyOpenPorts : System.__ComObjectName : Network Discovery
Type : 1
Customized : True
IpVersion : 2
Scope : 1
RemoteAddresses : LocalSubnet
Enabled : True
GloballyOpenPorts : System.__ComObjectName : Remote Desktop
Type : 2
Customized : False
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : False
GloballyOpenPorts : System.__ComObject
Friday, 19 December 2008
Get-DomainModeEnumValues.ps1
- # Get-DomainModeEnumValues.ps1
- # Prints out the values of the DomainMode Enum
- # Thomas Lee - tfl@psp.co.uk
- # Enumerate System.DirectoryServices.ActiveDirectory.DomainMode
- $enums=[enum]::GetValues([System.DirectoryServices.ActiveDirectory.DomainMode])
- # Display values
- "System.Net.DirectoryServices.ActiveDirectory.DomainMode enum has {0} possible values:" -f $enums.count
- $i=1
- $enums | %{"Value {0}: {1}" -f $i,$_.tostring();$i++}
- ""
- # Checking against an enum value
- $ToCheck = "Windows2008Domain"
- if ($ToCheck -eq [System.DirectoryServices.ActiveDirectory.DomainMode]::Windows2008Domain) {
- "`$ToCheck is Windows2008Domain"
- }
- else {
- "`$ToCheck is NOT Windows2008Domain"
- }
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