- <#
- .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
This blog contains PowerShell scripts, more PowerShell scripts and still more PowerShell scripts. Occasionally you may see some organisational posts.
Monday, 22 December 2008
Get-ParsedString.ps1
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
Thursday, 18 December 2008
Get-ForestModeEnumValues.ps1
- # Get-ForestModeEnumValues.ps1
- # Prints out the values of the ForestMode Enum
- # Thomas Lee - tfl@psp.co.uk
- # Enumerate System.DirectoryServices.ActiveDirectory.forestmode
- $enums=[enum]::GetValues([System.DirectoryServices.ActiveDirectory.ForestMode])
- # Display values
- "System.Net.DirectoryServices.ActiveDirectory.Forest mode enum has {0} possible values:" -f $enums.count
- $i=1
- $enums | %{"Value {0}: {1}" -f $i,$_.tostring();$i++}
- ""
- # Checking against an enum value
- $ToCheck = "Windows2008Forest"
- if ($ToCheck -eq [System.DirectoryServices.ActiveDirectory.ForestMode]::Windows2008Forest) {
- "`$ToCheck is Windows2008Forest"
- }
- else {
- "`$ToCheck is NOT Windows2008Forest"
- }
This script produces the following output:
PS C:\foo> .\Get-ForestModeEnumValues.ps1
System.Net.DirectoryServices.ActiveDirectory.Forest mode enum has 4 possible values:
Value 1: Windows2000Forest
Value 2: Windows2003InterimForest
Value 3: Windows2003Forest
Value 4: Windows2008Forest$ToCheck is Windows2008Forest
Wednesday, 17 December 2008
Get-FSMOHolders.ps1
- # Get-FSMOHolders.ps1
- # Gets the names of the systems holding the 5 FSMO holders
- # Runs on a domain-joined machine
- # Thomas Lee - tfl@psp.co.uk
- # Get host,forest and domain details
- $Hostname = hostname
- $forest = [DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
- $domain = [DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
- #Display FSMOs, forest wide first
- "For Host {0}" -f $hostname
- "In Forest {0}, forest masters are: " -f $for.name
- "Schema master : {0}" -f $forest.SchemaRoleOwner.Name
- "Domain Master : {0}" -f $forest.NamingRoleOwner.Name
- ""
- # Current domain
- "In domain {0}, domain masters are:" -f $dom.Name
- "PDC Master : {0}" -f $domain.PdcRoleOwner
- "Infrastructure Master : {0}" -f $domain.InfrastructureRoleOwner
- "RID Master : {0}" -f $domain.RidRoleOwner
This code produces the following output:
PS C:\foo> .\Get-FSMOHolders.ps1
For Host Cookham8
In Forest cookham.net, forest masters are:
Schema master : Cookham1.cookham.net
Domain Master : Cookham1.cookham.netIn domain cookham.net, domain masters are:
PDC Master : Cookham1.cookham.net
Infrastructure Master : Cookham1.cookham.net
RID Master : Cookham1.cookham.net
Tuesday, 16 December 2008
Get-System.EnvorinmentStaticProperties1.ps1
This script produces the following output:# Get-System.EnvorinmentStaticProperties1.ps1
# This script demonstrates the static properties on System.Environment
# Thomas Lee - tfl@psp.co.uk
#
# Get and display statics in system.environment class
"Static properties in [System.Environment]"
[System.Environment] | Get-Member -Static -MemberType properties
# Now display the values of the simple static properties
"";"Static Property values for [System.Environment]"
"CommandLine: : {0}" -f [System.Environment]::CommandLine
"CurrentDirectory : {0}" -f [System.Environment]::CurrentDirectory
"ExitCode : {0}" -f [System.Environment]::ExitCOde
"HasShutdownStarted : {0}" -f [System.Environment]::HasShutdownStarted
"MchineName : {0}" -f [System.Environment]::MachineNam
"NewLine : {0}" -f [System.Environment]::NewLine
"OSVersion : {0}" -f [System.Environment]::OSVersion
"ProcessorCount : {0}" -f [System.Environment]::ProcessorCount
"SystemDirctory : {0}" -f [System.Environment]::SystemDirectory
"TickCount : {0}" -f [System.Environment]::TickCount
"UserDomainName : {0}" -f [System.Environment]::UserDomainName
"UserInteractive : {0}" -f [System.Environment]::UserInteractive
"UserName : {0}" -f [System.Environment]::UserName
"Version : {0}" -f [System.Environment]::Version
"WorkingSet : {0}" -f [System.Environment]::WorkingSet
# Here is the stack trace:
"";"StackTrace:"
[System.Environment]::StackTrace
PS C:\foo> Get-System.EnvironmentStaticProperties.ps1'
Static properties in [System.Environment]
TypeName: System.Environment
Name MemberType Definition
---- ---------- ----------
CommandLine Property static System.String CommandLine {get;}
CurrentDirectory Property static System.String CurrentDirectory {get;set;}
ExitCode Property static System.Int32 ExitCode {get;set;}
HasShutdownStarted Property static System.Boolean HasShutdownStarted {get;}
MachineName Property static System.String MachineName {get;}
NewLine Property static System.String NewLine {get;}
OSVersion Property static System.OperatingSystem OSVersion {get;}
ProcessorCount Property static System.Int32 ProcessorCount {get;}
StackTrace Property static System.String StackTrace {get;}
SystemDirectory Property static System.String SystemDirectory {get;}
TickCount Property static System.Int32 TickCount {get;}
UserDomainName Property static System.String UserDomainName {get;}
UserInteractive Property static System.Boolean UserInteractive {get;}
UserName Property static System.String UserName {get;}
Version Property static System.Version Version {get;}
WorkingSet Property static System.Int64 WorkingSet {get;}
Static Property values for [System.Environment]
CommandLine: : "C:\psp\PowerShellPlus.exe"
CurrentDirectory : C:\psp
ExitCode : 0
HasShutdownStarted : False
MchineName : COOKHAM8
NewLine :
OSVersion : Microsoft Windows NT 6.0.6001 Service Pack 1
ProcessorCount : 8
SystemDirctory : C:\Windows\system32
TickCount : -1879673533
UserDomainName : COOKHAM
UserInteractive : True
UserName : tfl
Version : 2.0.50727.1434
WorkingSet : 47669248
StackTrace:
at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at getter(Object )
at System.Management.Automation.DotNetAdapter.PropertyGet(PSProperty property)
at System.Management.Automation.Adapter.BasePropertyGet(PSProperty property)
at System.Management.Automation.PSProperty.GetAdaptedValue()
at System.Management.Automation.PSProperty.get_Value()
at System.Management.Automation.PropertyReferenceNode.GetValue(PSObject obj, Object property)
at System.Management.Automation.PropertyReferenceNode.Execute(Array input, Pipe outputPipe)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultL
at System.Management.Automation.StatementListNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe)
at System.Management.Automation.ScriptCommandProcessor.ExecuteWithCatch(ParseTreeNode ptn, Array inputToProcess)
at System.Management.Automation.ScriptCommandProcessor.RunClause(ParseTreeNode clause, Object dollarUnderbar, Object inputToProcess)
at System.Management.Automation.ScriptCommandProcessor.Complete()
at System.Management.Automation.CommandProcessorBase.DoComplete()
at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input, Hashtable errorResults, Boolean enumera
at System.Management.Automation.PipelineNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultL
at System.Management.Automation.StatementListNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe)
at System.Management.Automation.ScriptCommandProcessor.ExecuteWithCatch(ParseTreeNode ptn, Array inputToProcess)
at System.Management.Automation.ScriptCommandProcessor.RunClause(ParseTreeNode clause, Object dollarUnderbar, Object inputToProcess)
at System.Management.Automation.ScriptCommandProcessor.Complete()
at System.Management.Automation.CommandProcessorBase.DoComplete()
at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input, Hashtable errorResults, Boolean enumera
at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Sunday, 7 December 2008
Write-RSSStream.ps1
# Write-RSSStream.ps1
# This sample shows how to use the XMLTextWriter
# Based on Halr's content, but extended.
# Thomas Lee - tfl@psp.co.uk
# Define output
$path = "c:\foo\file.xml"
# Create encoding, and create xml writer
$encoding = [System.Text.Encoding]::UTF8
$writer = New-Object System.Xml.XmlTextWriter( $Path, $encoding )
$writer.Formatting = [system.xml.formatting]::indented
# Write start of document
$writer.WriteStartDocument()
# Write Start of rss stream
$writer.WriteStartElement( "rss" )
$writer.WriteAttributeString( "version", "2.0" )
# write channel start info
$writer.WriteStartElement("channel")
$writer.WriteStartElement("title")
$writer.writestring("My Channel")
$writer.WriteEndElement() #end title
$Writer.WriteStartElement("Last Build Date")
$writer.WriteString((Get-Date).ToString())
$writer.WriteEndElement() #end last build date
$writer.WriteStartElement("subtitle")
$writer.WriteString("This Blog's subtitle")
$writer.WriteEndElement() #end subtitle
# Now here put an item in
$writer.WriteStartElement("item")
$writer.WriteStartElement("title")
$writer.WriteString("A cool RSS Feed Item")
$writer.WriteEndElement() #end title
$writer.WriteStartElement("link")
$writer.WriteString("http://pshscripts.blogspot.com")
$writer.WriteEndElement() #end link
$writer.WriteStartElement("description")
$writer.WriteString("This is the body of a blog post. It could go on, and on. ")
$writer.Writestring("Or not as the case may be!")
$writer.WriteEndElement() #end description
$writer.WriteStartElement("author")
$writer.WriteString("Thomas Lee - tfl@psp.co.uk")
$writer.WriteEndElement() #end author
$writer.WriteEndElement() #end item
# Write end of document information
$writer.WriteEndElement() # End Channel
$writer.WriteEndElement() #End RSS
# Make sure we close the file
$writer.close()
# Let's see what it has done
cat $path
PS C:\foo> . 'C:\foo\write-rssstream.PS1'
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>My Channel</title>
<Last Build Date>12/5/2008 8:50:26 AM</Last Build Date>
<subtitle>This Blog's subtitle</subtitle>
<item>
<title>A cool RSS Feed Item</title>
<link>http://pshscripts.blogspot.com</link>
<description>This is the body of a blog post. It could go on, and on.
Or not as the case may be!</description>
<author>Thomas Lee - tfl@psp.co.uk</author>
</item>
</channel>
</rss>
Saturday, 6 December 2008
PowerShell Script Library Available for Download
Thus far, I have published around 65 scripts to this blog. To help readers, I’m publishing a zip of the entire library to my www.reskit.net site. You can get the full library at http://www.reskit.net/powershell/scriptlib.zip.
I’ll try to keep this archive relatively up to date as I add new scripts. I’ll also publish the script I’ve developed that creates the zip file and uploads it to the web site!
Friday, 5 December 2008
Send-UDPDatagram.ps1
- <#
- .SYNOPSIS
- Sends a UDP datagram to a port
- .DESCRIPTION
- This script used system.net.socckets to send a UDP
- datagram to a particular port. Being UDP, there's
- no way to determine if the UDP datagram actually
- was received.
- for this sample, a port was chosen (20000).
- .NOTES
- File Name : Send-UDPDatagram
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell V2 CTP3
- .LINK
- http://www.pshscripts.blogspot.com
- .EXAMPLE
- #>
- ###
- # Start of Script
- ##
- # Define port and target IP address
- # Random here!
- [int] $Port = 20000
- $IP = "10.10.1.100"
- $Address = [system.net.IPAddress]::Parse($IP)
- # Create IP Endpoint
- $End = New-Object System.Net.IPEndPoint $address, $port
- # Create Socket
- $Saddrf = [System.Net.Sockets.AddressFamily]::InterNetwork
- $Stype = [System.Net.Sockets.SocketType]::Dgram
- $Ptype = [System.Net.Sockets.ProtocolType]::UDP
- $Sock = New-Object System.Net.Sockets.Socket $saddrf, $stype, $ptype
- $Sock.TTL = 26
- # Connect to socket
- $sock.Connect($end)
- # Create encoded buffer
- $Enc = [System.Text.Encoding]::ASCII
- $Message = "Jerry Garcia Rocks`n"*10
- $Buffer = $Enc.GetBytes($Message)
- # Send the buffer
- $Sent = $Sock.Send($Buffer)
- "{0} characters sent to: {1} " -f $Sent,$IP
- "Message is:"
- $Message
- # End of Script
If you run this script and are using WireShark to capture the network traffic, you might see something like this:
From this trace, you can see the UDP Datagram that was sent. And since the port does not exist on the target machine (10.10.1.100), that machine returns a Destination Port Unreachable as expected.