Tuesday, 1 July 2014

Zip-Pshscripts3.ps1

#Requires –Version 5.0
#
#.Synopsis
# Creates a zip file of PowerShell scripts
#.Description
# The script creates a zip file containing all the files,
# recursing through the top level PowerShell Script Library folder.
#
#.Notes
# This script require PowerShell V5 for the zip file cmdlets!
# Author - Thomas Lee - tfl@psp.co.uk
#
#.Example
# OSH [c:\foo]> .\Zip-PSHScripts3.ps1
# Total files : 347
# ps1 files : 342
# txt files : 1
# other files : 4


# Define what to zip and from where
$zipfile = "C:\foo\ScriptLib.ZIP"
$zipfrom = "C:\Users\tfl\Dropbox\PowerShell Script Library (master)"
$recurse = "true"
$ziptoadd = "ps1"

# Check it out
if ( ! (Test-path -Path $zipfrom ))
{
Write-Host 'scripts folder does not exist'
}

# Zip it up!
Try
{
Compress-Archive -Path $zipfrom -DestinationPath $zipfile -CompressionLevel Optimal -Update
}
Catch
{
Write-Host ' Error Zipping up the script library'
$Error[0]
}

# Stats
$files = ls $zipfrom -file -recurse
$files_ps1 = $files | Where-Object Extension -eq '.ps1'
$files_txt = $files | Where-Object Extension -eq '.txt'
$files_other = $files | Where-Object { $_.extension -NE '.PS1' -and $_.Extension -ne '.txt'}

"Total files : {0}" -f $($files.count)
"ps1 files : {0}" -f $($files_ps1.count)
"txt files : {0}" -f $($files_txt.count)
"other files : {0}" -f $($files_other.count)


# All done
ls $zipfile

Thursday, 23 January 2014

Show-Message.ps1

<#
.SYNOPSIS
This script creates a function to display a message
in a message block, then demonstrates its usage
.DESCRIPTION
This script used Windows Forms to put up a message
box containing text and a window title passed as
parameters
.NOTES
File Name : Show-Message.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell Version 3.0
.LINK
This script posted to:
http://www.pshscripts.blogspot.com
.EXAMPLE
Left as an exercise to the Reader
#>

Function Show-Message {

[CmdletBinding()]
Param (
[Parameter(Mandatory=$True,
HelpMessage="Content of Message box")]
[string]$Message ,

[Parameter(Mandatory=$False,
HelpMessage="Title for Message box")]
[string]$BoxTitle = "Message"
)

# just in case, load the relevant assembly
$v1 = [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

# now use the messagebox class to display the message
[Windows.Forms.MessageBox]::Show($Message, $BoxTitle,
[Windows.Forms.MessageBoxButtons]::OK ,
[Windows.Forms.MessageBoxIcon]::Information)

} # End of function

# Set an alias
Set-Alias sm Show-Message

# call the function
sm 'testing' 'details, details'

Sunday, 5 January 2014

Show-TimeSpanFormatting.ps1

<# 
.SYNOPSIS
This script demonstrates formatting System.TimeSpan objects
Using PowerShell
.DESCRIPTION
This scipt re-writes some MSDN Samples that demostarate
timespan formatting - the original article lacks PowerShell
Examples. And sadly, the MSDN page no longer accepts community
additions.

.NOTES
File Name : Show-TimeSpanFormatting
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell Version 3.0
.LINK
This script posted to:
http://pshscripts.blogspot.co.uk/2014/01/show-timespanformattingps1.html
Reference MSDN Page
http://msdn.microsoft.com/en-us/library/ee372286%28v=vs.110%29.aspx
.EXAMPLE
Psh> .\Show-TimeSpanFormatting.ps1
Example 1
Time of Travel: 1.12:24:02
Time of Travel: 1.12:24:02
Example 2
Converted '1.03:14:56.1667' to 1.03:14:56.1667000
Converted '1.03:14:56.1667' to 1.03:14:56.1667000
Example 3
07:45:16 - 18:12:38 = -10:27:22
07:45:16 + 18:12:38 = 1.01:57:54
00:01:14.3650000 + 00:00:00.2143756 = 00:01:14.5793756
Example 4
7:45:16 - 18:12:38 = -10:27:22
7:45:16 + 18:12:38 = 1:1:57:54
0:01:14.036 + 0:00:00.2143756 = 0:01:14.2503756
Example 5
0:07:45:16.0000000 - 0:18:12:38.0000000 = -0:10:27:22.0000000
0:07:45:16,0000000 + 0:18:12:38,0000000 = 1:01:57:54,0000000
0:00:01:14.0360000 + 0:00:00:00.2143756 = 0:00:01:14.2503756
#>

# Show Time Span Format Strings

# Example 1 - use both tostring() and -f operators
"Example 1"
# Create Timespan object
$duration = New-Object System.TimeSpan 1, 12, 23, 62

# Now output using both tostring() and -f
"Time of Travel: " + $duration.ToString("c")
"Time of Travel: {0:c}" -f $duration

# Example 2
# Demonstrate the use of ParseExact and TryParseExact
"Example 2"

$value = "1.03:14:56.1667"
$interval = New-Object System.TimeSpan

Try {
$interval = [System.TimeSpan]::ParseExact($value, "c", $null)
"Converted '{0}' to {1}" -f $value, $interval
}
Catch [System.FormatException] {"{0}: Bad Format" -f $value}
Catch [System.OverflowException] {"{0}: Out of Range" -f $value }

If ([System.TimeSpan]::TryParseExact($value, "c", $null, [ref] $interval)) {
"Converted '{0}' to {1}" -f $value, $interval
}
Else {
"Unable to convert {0} to a time interval." -f $value
}

# Example 3
# Create two TimeSpan objects, perform arithmetic operations
# on them then displays the result using the 'C' format specifier
"Example 3"

$interval1 = New-Object System.TimeSpan 7, 45, 16
$interval2 = New-Object System.TimeSpan 18, 12, 38

"{0:c} - {1:c} = {2:c}" -f $interval1,$interval2, $($interval1 - $interval2)
"{0:c} + {1:c} = {2:c}" -f $interval1,$interval2, $($interval1 + $interval2)

$interval1 = New-Object System.TimeSpan 0, 0, 1, 14, 365
$interval2 = [System.TimeSpan]::FromTicks(2143756)
"{0:c} + {1:c} = {2:c}" -f $interval1, $interval2, $($interval1 + $interval2)

# Example 4 - The "g" Format Specifier
# This specifier returns the string representation of a TimeSpan value in a compact form
# by including only the elements that are necessary.
"Example 4"

$interval1 = New-Object System.TimeSpan 7, 45, 16
$interval2 = New-Object System.TimeSpan 18, 12, 38

"{0:g} - {1:g} = {2:g}" -f $interval1, $interval2, $($interval1 - $interval2)

# do it in French
$CI = New-object System.Globalization.CultureInfo 'fr-FR'
[System.String]::Format($CI, $("{0:g} + {1:g} = {2:g}") ,
$interval1,$interval2,$($interval1 + $interval2) )
# Another interval
$interval1 = new-object System.TimeSpan 0, 0, 1, 14, 36
$interval2 = [System.TimeSpan]::FromTicks(2143756)
"{0:g} + {1:g} = {2:g}" -f $interval1, $interval2, $($interval1 + $interval2)

# Example 5
# Using the "G' Specifier
#
"Example 5"
$interval1 = new-object System.TimeSpan 7, 45, 16
$interval2 = new-object System.TimeSpan 18, 12, 38
"{0:G} - {1:G} = {2:G}" -f $interval1, $interval2, $($interval1 -$interval2)
[System.String]::Format($(New-Object CultureInfo("fr-FR")),
"{0:G} + {1:G} = {2:G}", $interval1,
$interval2, $($interval1 + $interval2))

$interval1 = new-object System.TimeSpan 0, 0, 1, 14, 36
$interval2 = [System.TimeSpan]::FromTicks(2143756)
"{0:G} + {1:G} = {2:G}" -f $interval1,$interval2, $($interval1 + $interval2)

Thursday, 14 November 2013

Fix-FileName.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Defines a function to remove 'invalid' characters 
  4.     from a file name. 
  5. .DESCRIPTION 
  6.     Some programs do not like certain 'invalid' characters 
  7.     in a file name used by that application. The function 
  8.     takes a look at each the file name and replaces some invalid 
  9.     characters with '-'
  10.  
  11.     This function takes a file name and 'fixes' it and returns 
  12.     the 'fixed' file name. Needless to say the characters to match 
  13.     and what to replace them with is an application specific decision! 
  14. .NOTES 
  15.     File Name  : Fix-FileName.ps1 
  16.     Author     : Thomas Lee - tfl@psp.co.uk 
  17.     Requires   : PowerShell Version 3.0 
  18. .LINK 
  19.     This script posted to: 
  20.         http://www.pshscripts.blogspot.com 
  21. .EXAMPLE 
  22.     Psh> .\Fix-FileName.ps1 
  23.     File name was: 123{}{{{|[\] 
  24.     Fixed name is: 123-------- 
  25.  
  26. #> 
  27.  
  28.  
  29. Function Fix-FileName { 
  30. [CMdletbinding()] 
  31. Param ( 
  32. $fn = $(throw 'no file name specified - returning'
  33.  
  34. Switch -Regex ($fn) { 
  35.   "}"  { $fn = $fn -replace '{','-'  } 
  36.   "}"  { $fn = $fn -replace '}','-'  } 
  37.   "\]" { $fn = $fn -replace ']','-'  } 
  38.   "\[" { $fn = $fn -replace '\[','-'
  39.   "\\" { $fn = $fn -replace '\\','-' } 
  40.   "\|" { $fn = $fn -replace '\|','-' } 
  41. } 
  42. $fn 
  43. } 
  44.  
  45. $fn = "123{}{{{|[\]" 
  46. $fnf = Fix-FileName $fn 
  47. "File name was: $fn" 
  48. "Fixed name is: $fnf

Wednesday, 16 October 2013

Get-SQLServer2.ps1

  1. #Requires -Version 3.0 
  2. <# 
  3. .SYNOPSIS 
  4.     This script Gets a list of SQL Severs on the Subnet 
  5. .DESCRIPTION 
  6.     This script uses SMO to Find all the local SQL Servers  
  7.     and displays them 
  8.  
  9. .NOTES 
  10.     File Name  : Get-SQLServer2.ps1 
  11.     Author     : Thomas Lee - tfl@psp.co.uk 
  12.     Requires   : PowerShell Version 3.0 
  13. .LINK 
  14.     This script posted to: 
  15.         http://www.pshscripts.blogspot.com 
  16. .EXAMPLE 
  17.     PS>  # On a Lync Server looking at Lync Implementation 
  18.     PS>  Get-SQLServer2 
  19.     There are 7 SQL Server(s) on the Local Subnet 
  20.  
  21.     ServerName      InstanceName Version      
  22.     ----------      ------------ -------      
  23.     2013-LYNC-MGT   MON          10.50.2500.0 
  24.     2013-LYNC-MGT   SCOM         10.50.2500.0 
  25.     2013-TS         RTCLOCAL     11.0.2100.60 
  26.     2013-SHAREPOINT SPSDB        11.0.3000.0  
  27.     2013-LYNC-FE    RTC          11.0.2100.60 
  28.     2013-LYNC-FE    RTCLOCAL     11.0.2100.60 
  29.     2013-LYNC-FE    LYNCLOCAL    11.0.2100.60 
  30.      
  31. #> 
  32. Import-Module SQLPS 
  33.  
  34. # Now get all the database servers on the local subnet 
  35.  
  36. $SQLservers = [System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources() 
  37. $Srvs= @() 
  38.  
  39. # Convert collection to an array 
  40. Foreach ($srv in $SQLservers) { 
  41. $srvs += $srv 
  42.  
  43. # Now display results 
  44. If ($Srvs.count -LE 0) { 
  45. "There are no SQL Servers on the Local Subnet" 
  46. return
  47.  
  48. # Now print server details 
  49. "There are {0} SQL Server(s) on the Local Subnet" -f $Srvs.count 
  50. $Srvs | Select ServerName, InstanceName, Version | Format-Table -AutoSize 

Saturday, 12 October 2013

Get-OLCalendarItem

  1. Function Get-OLCalendarItem { 
  2.  
  3.  
  4. <# 
  5. .SYNOPSIS 
  6.     A function to retreive Outlook Calender items between two dates.  
  7.     Returns PSobjects containing each item. 
  8. .DESCRIPTION 
  9.     The function opens one's outlook calender, then retrieves the items.  
  10.     The function takes 2 parameter: start, end - items are returned that  
  11.     start betweween these two dates. 
  12. .NOTES 
  13.     File Name  : Get-OLCalendarItem 
  14.     Author     : Thomas Lee - tfl@psp.co.uk 
  15.     Requires   : PowerShell Version 3.0 
  16. .LINK 
  17.     This script posted to: 
  18.         http://www.pshscripts.blogspot.com 
  19.      
  20. .EXAMPLE 
  21.     Left as an exercise for the reader      
  22.  
  23. #> 
  24.  
  25. [CmdletBinding()] 
  26. Param ( 
  27. $start = $(Get-Date) , 
  28. $end   = $((Get-date).AddMonths(1)) 
  29.  
  30. Write-Verbose "Returning objects between: $($start.tostring()) and $($end.tostring())" 
  31. # Load Outlook interop and Outlook iteslf 
  32. [Reflection.Assembly]::LoadWithPartialname("Microsoft.Office.Interop.Outlook") | out-null 
  33. $Outlook = new-object -comobject outlook.application 
  34.  
  35. # Get OL default folders 
  36. $OlFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type] 
  37. $Namespace = $Outlook.GetNameSpace("MAPI"
  38. $Calendar = $namespace.GetDefaultFolder($olFolders::olFolderCalendar) 
  39. Write-Verbose "There are $($calendar.items.count) items in the calender in total" 
  40.  
  41. # Now return psobjects for all items between 2 dates 
  42. ForEach ($citem in ($Calendar.Items | sort start)) { 
  43. #Write-Verbose "Processing [$($citem.Subject)]  Starting: [$($Citem.Start)]" 
  44.  
  45. If ($citem.start -ge $start -and $citem.start -LE $end) {  
  46.  
  47. $CalHT =[ordered]  @{ 
  48. Subject          =  $($Citem.Subject) 
  49. Location         =  $($Citem.Location); 
  50. Start            =  $(Get-Date $Citem.Start); 
  51. StartUTC         =  $(Get-Date $Citem.StartUTC);                                   
  52. End              =  $(Get-Date $Citem.End); 
  53. EndUTC           =  $(Get-Date $Citem.EndUTC); 
  54. Duration         =  $($Citem.Duration); 
  55. Importance       =  $($Citem.Importance); 
  56. IsRecurring      =  $($Citem.IsRecurring); 
  57. AllDayEvent      =  $($citem.AllDayEvent); 
  58. Sensitivity      =  $($Citem.Sensitivity); 
  59. ReminderSet      =  $($Citem.ReminderSet); 
  60. CreationTime     =  $($Citem.CreationTime); 
  61. LastModificationTime = $($Citem.LastModificationTime); 
  62. Body             =  $($Citem.Body); 
  63.  
  64.  
  65. # Write the item out as a custom item 
  66. $o=New-Object PSobject -Property $CalHT 
  67. Write-Output $o 
  68.  
  69. } #End of foreach 
  70.  
  71. }  # End of function 
  72.  
  73. Set-Alias GCALI Get-OLCalendarItem  
Technorati Tags: ,

Wednesday, 28 August 2013

Get-DHCPPerf.Ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script gets and displays perf counters for DHCP 
  4. .DESCRIPTION 
  5.     This script uses the Get-Counter cmdlet to get all 
  6.     the counters for DHCP. The function does this for one 
  7.     DHCP server at a time. 
  8. .NOTES 
  9.     File Name  : Show-.ps1 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell Version 2.0 
  12. .LINK 
  13.     This script posted to: 
  14.         http://www.pshscripts.blogspot.com 
  15. .EXAMPLE 
  16.     C:\Foo> Get-DHCPPerformanceCounters -comp dhcp2 
  17.      Performance counters for: dhcp2 
  18.      \\dhcp1\dhcp server\failover: bndupd dropped.                                           0 
  19.      \\dhcp1\dhcp server\failover: transitions to recover state.                             8 
  20.      \\dhcp1\dhcp server\failover: transitions to partner-down state.                        0 
  21.      \\dhcp1\dhcp server\failover: transitions to communication-interrupted state.           9 
  22.      \\dhcp1\dhcp server\failover: bndupd pending in outbound queue.                         0 
  23.      \\dhcp1\dhcp server\failover: bndack received/sec.                                      0 
  24.      \\dhcp1\dhcp server\failover: bndack sent/sec.                                          0 
  25.      \\dhcp1\dhcp server\failover: bndupd received/sec.                                      0 
  26.      \\dhcp1\dhcp server\failover: bndupd sent/sec.                                          0 
  27.      \\dhcp1\dhcp server\denied due to nonmatch.                                             0 
  28.      \\dhcp1\dhcp server\denied due to match.                                                0 
  29.      \\dhcp1\dhcp server\offer queue length                                                  0 
  30.      \\dhcp1\dhcp server\releases/sec                                                        0 
  31.      \\dhcp1\dhcp server\declines/sec                                                        0 
  32.      \\dhcp1\dhcp server\nacks/sec                                                           0 
  33.      \\dhcp1\dhcp server\acks/sec                                                            0 
  34.      \\dhcp1\dhcp server\informs/sec                                                         0 
  35.      \\dhcp1\dhcp server\requests/sec                                                        0 
  36.      \\dhcp1\dhcp server\offers/sec                                                          0 
  37.      \\dhcp1\dhcp server\discovers/sec                                                       0 
  38.      \\dhcp1\dhcp server\conflict check queue length                                         0 
  39.      \\dhcp1\dhcp server\active queue length                                                 0 
  40.      \\dhcp1\dhcp server\milliseconds per packet (avg).                                     28 
  41.      \\dhcp1\dhcp server\packets expired/sec                                                 0 
  42.      \\dhcp1\dhcp server\duplicates dropped/sec                                              0 
  43. #> 
  44.  
  45.  
  46.  
  47.  
  48. # Get-DHCPPerformanceCounters function 
  49.  
  50. Function Get-DHCPPerformanceCounters { 
  51. Param ( 
  52. $comp = 'localhost'
  53.  
  54. # Get DHCP Counters 
  55. $set = get-counter -listset "DHCP Server" 
  56. $ctrs = $set.counter 
  57.  
  58. " Performance counters for: {0}" -f $comp 
  59. # For each counter, get the sample 
  60. foreach ($ctr in $ctrs) { 
  61.  $sample = (get-counter $ctr).countersamples 
  62.  
  63.  
  64.  "{0,-78} {1,10}" -f $sample.path, $sample.cookedvalue 
  65.  
  66.  
  67.  
  68. # Now test it 
  69. Get-DHCPPerformanceCounters -comp dhcp1 
  70. Get-DHCPPerformanceCounters -comp dhcp2 
Technorati Tags:

Monday, 29 July 2013

Get-Zip.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script demonstrates the use of the Zip lib in .NET 
  4. .DESCRIPTION 
  5.     This script is a re-write of an MSDN sample, using PowerShell 
  6. .NOTES 
  7.     File Name  : Show-ZIP.ps1 
  8.     Author     : Thomas Lee - tfl@psp.co.uk 
  9.     Requires   : PowerShell Version 3.0 
  10. .LINK 
  11.     This script posted to: 
  12.         http://www.pshscripts.blogspot.com 
  13.     MSDN sample posted to: 
  14.          http://msdn.microsoft.com/en-us/library/system.io.compression.zipfile.aspx 
  15. .EXAMPLE 
  16.     PSH> .\Show-Zip 
  17.      
  18.     Directory: C:\example 
  19. Mode        LastWriteTime  Length Name                                                                                                                            
  20. ----        -------------  ------ ----                                                                                                                            
  21. d---- 7/29/2013   4:35 PM        extract                                                                                                                         
  22. d---- 7/29/2013   4:29 PM        start                                                                                                                           
  23. -a--- 7/29/2013   4:35 PM   1668 result.zip                                                                                                                      
  24.  
  25.  
  26.     Directory: C:\example\extract 
  27. Mode        LastWriteTime  Length Name                                                                                                                            
  28. ----        -------------  ------ ----                                                                                                                            
  29. -a---  7/29/2013  4:28 PM    5609 d1.txt                                                                                                                          
  30. -a---  7/29/2013  4:29 PM   67308 d2.txt                                                                                                                          
  31. -a---  7/29/2013  4:29 PM   67308 d3.txt                                                                                                                          
  32. -a---  7/29/2013  4:29 PM   67308 d4.txt                                                                                                                          
  33. -a---  7/29/2013  4:29 PM   67308 d5.txt                                                                                                                          
  34.  
  35.  
  36.     Directory: C:\example\start 
  37. Mode        LastWriteTime     Length Name                                                                                                                            
  38. ----        ------------     ------ ----                                                                                                                            
  39. -a---  7/29/2013  4:28 PM    5609 d1.txt                                                                                                                          
  40. -a---  7/29/2013  4:29 PM   67308 d2.txt                                                                                                                          
  41. -a---  7/29/2013  4:29 PM   67308 d3.txt                                                                                                                          
  42. -a---  7/29/2013  4:29 PM   67308 d4.txt                                                                                                                          
  43. -a---  7/29/2013  4:29 PM   67308 d5.txt                                                                                                                          
  44. #> 
  45.  
  46. # Load the compression namespace  
  47. # And yes, I know this usage is obsolete - but it works.  
  48. # Ignore the output  
  49. [System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') | out-null 
  50.  
  51. # Set locations 
  52. $startPath = "c:\example\start" 
  53. $zipPath = "c:\example\result.zip" 
  54. $extractPath = "c:\example\extract" 
  55. Remove-Item $zipPath -ea SilentlyContinue 
  56. Remove-Item -Path $extractPath -inc * -Recurse -ea SilentlyContinue 
  57.  
  58. # Create the zip file 
  59. [System.IO.Compression.ZipFile]::CreateFromDirectory($startPath, $zipPath
  60.  
  61. # Extract from zip and show what's all there 
  62. [System.IO.Compression.ZipFile]::ExtractToDirectory($zipPath,$extractPath); 
  63. ls c:\example -Recurse 
  64.          

Sunday, 28 July 2013

Show-NumberGroupSizes.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script demonstrates the use of the NumberGroupSizes 
  4. .DESCRIPTION 
  5.     This script is a re-write of an MSDN sample, using PowerShell 
  6. .NOTES 
  7.     File Name  : Show-NumberGroupSizes.ps1 
  8.     Author     : Thomas Lee - tfl@psp.co.uk 
  9.     Requires   : PowerShell Version 3.0 
  10. .LINK 
  11.     This script posted to: 
  12.         http://www.pshscripts.blogspot.com 
  13.     MSDN sample posted to: 
  14.          http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numbergroupsizes%28v=vs.100%29.aspx 
  15. .EXAMPLE 
  16.     PSH> .\Show-NumberGroupSizes.ps1 
  17.     123,456,789,012,345.00 
  18.     12,3456,7890,123,45.00 
  19.     1234567890,123,45.00 
  20. #> 
  21.  
  22. # Get Number Format 
  23. $nf  = New-Object System.Globalization.CultureInfo  "en-US", $False  
  24. $nfi = $nf.NumberFormat 
  25.  
  26. [Int64] $myInt = 123456789012345 
  27. $myInt.ToString( "N", $nfi
  28.  
  29. # Display the same value with different groupings 
  30. [int[]] $MySizes1 = 2,3,4 
  31. [int[]] $MySizes2 = 2,3,0 
  32.  
  33. $nfi.NumberGroupSizes = $mySizes1 
  34. $myInt.ToString( "N",$nfi
  35. $nfi.NumberGroupSizes = $mySizes2 
  36. $myInt.ToString( "N", $nfi )