Showing posts with label PowerShell V2. Show all posts
Showing posts with label PowerShell V2. Show all posts

Wednesday, 3 October 2012

Set-PowerShellAsShell

  1. <# 
  2. .Synopsis 
  3.    Creates a function to set PowerShell as GUI in Server 2012 
  4. .DESCRIPTION 
  5.    The function in this script sets PowerShell as the  
  6.    default shell in Server 2012. When the server is rebooted, 
  7.    it runs PowerShell.exe by default. When PowerShell starts, it 
  8.    displays the $PSVersionTable variable. 
  9. .NOTES 
  10.     File Name   : Set-PowerShellAsGui.ps1 
  11.     Author      : Thomas Lee - tfl@psp.co.uk 
  12.     Requires    : Server 2012 
  13. .LINK 
  14.     This script posted to: 
  15.         http://www.pshscripts.blogspot.com   
  16. .EXAMPLE 
  17.     Left as an exercise to the reader 
  18. #> 
  19.  
  20.  
  21. Function Set-PowerShellAsShell { 
  22.  
  23. [CmdletBinding()] 
  24. Param ( 
  25. [switch] $Reboot = $false 
  26.  
  27. # Create Registry Path variable 
  28. $RegPath =  "Microsoft.PowerShell.Core\Registry::"  
  29. $RegPath += "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\" 
  30. $RegPath += "Windows NT\CurrentVersion\winlogon" 
  31.  
  32. # Create splatted parameter hash table 
  33. $parm  =  @{Path    = $regpath}           # key 
  34. $parm +=  @{Name    = 'Shell'}            # value name 
  35. $parm +=  @{Value   = 'PowerShell.exe –NoExit 
               -Command "
    $psversiontable"'}   # value’s value 
  36.  
  37. # Set Registry value entry 
  38. Set-ItemProperty @parm  
  39.  
  40. # And restart to see PowerShell 
  41. if ($Reboot) {Restart-Computer -confirm} 

Tuesday, 29 March 2011

New-Credential.ps1

  1. <# 
  2. .SYNOPSIS 
  3.    A function to create a credential object from script. 
  4. .DESCRIPTION 
  5.    Enables you to create a credential objects from stored details. 
  6. .NOTES 
  7.     File Name  : New-Credential.ps1 
  8.     Author     : Thomas Lee - tfl@psp.co.uk 
  9.     Requires   : PowerShell Version 2.0 
  10. .LINK 
  11.     This script posted to: 
  12.         http://pshscripts.blogspot.com/2011/03/new-credentialps1.html 
  13. .PARAMETER UserId 
  14.    The userid in the form of "domain\user" 
  15. .PARAMETER Password 
  16.    The password for this user 
  17. .EXAMPLE 
  18.    New-Credential contoso\administrator  Pa$$w0rd 
  19. #> 
  20.  
  21. function New-Credential { 
  22. param ( 
  23. [string] $Userid, 
  24. [string] $Pwd 
  25. # Create the credential 
  26. $spwd = ConvertTo-SecureString -AsPlainText $pwd -Force  
  27. $cred = New-Object System.Management.Automation.PSCredential $userid,$spwd 
  28. # Now return it to the caller 
  29. return $cred 
  30.  
  31. # Call the function to demostrate example 
  32. New-Credential "contoso\administrator" "Pa$$w0rd" 
Technorati Tags: ,,

Thursday, 23 December 2010

Set-IseThemeVim.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script sets an ISE Theme to similar to the old VIM editor. 
  4. .DESCRIPTION 
  5.     This script sets the key values in $PsIse.Options to values consistent 
  6.     with the VIM editor, beloved by many, particularly on the Powershell 
  7.     product team. This script is based on Davis Mohundro's blog post
  8.     (http://bit.ly/iib5IM), updated for RTM of PowerShell V2.0. See also  
  9. .NOTES 
  10.     File Name  : Set-ISEThemeVIM.ps1 
  11.     Author     : Thomas Lee - tfl@psp.co.uk 
  12.     Requires   : PowerShell Version 2.0 (ISE only) 
  13. .LINK 
  14.     This script posted to: 
  15.         http://pshscriptsbog.blogspot.com  
  16.         http://bit.ly/iaA2iX
  17. .EXAMPLE 
  18.     This script when run resets colours on key panes, including 
  19.     colourising tokens in the script pane. Try it and see it... 
  20. #> 
  21.  
  22.  
  23. # PowerShell ISE version of the VIM blackboard theme at  
  24. # http://www.vim.org/scripts/script.php?script_id=2280 
  25.  
  26. # Set font name and size 
  27. $psISE.Options.FontName = 'Courier New' 
  28. $psISE.Options.FontSize = 16 
  29.  
  30. # Set colours for output pane 
  31. $psISE.Options.OutputPaneBackgroundColor     = '#FF000000' 
  32. $psISE.Options.OutputPaneTextBackgroundColor = '#FF000000' 
  33. $psISE.Options.OutputPaneForegroundColor     = '#FFFFFFFF' 
  34.  
  35. # Set colours for command pane 
  36. $psISE.Options.CommandPaneBackgroundColor    = '#FF000000' 
  37.  
  38. # Set colours for script pane 
  39.  
  40. $psise.options.ScriptPaneBackgroundColor    ='#FF000000' 
  41.  
  42. # Set colours for tokens in Script Pane 
  43. $psISE.Options.TokenColors['Command'] = '#FFFFFF60' 
  44. $psISE.Options.TokenColors['Unknown'] = '#FFFFFFFF' 
  45. $psISE.Options.TokenColors['Member'] = '#FFFFFFFF' 
  46. $psISE.Options.TokenColors['Position'] = '#FFFFFFFF' 
  47. $psISE.Options.TokenColors['GroupEnd'] = '#FFFFFFFF' 
  48. $psISE.Options.TokenColors['GroupStart'] = '#FFFFFFFF' 
  49. $psISE.Options.TokenColors['LineContinuation'] = '#FFFFFFFF' 
  50. $psISE.Options.TokenColors['NewLine'] = '#FFFFFFFF' 
  51. $psISE.Options.TokenColors['StatementSeparator'] = '#FFFFFFFF' 
  52. $psISE.Options.TokenColors['Comment'] = '#FFAEAEAE' 
  53. $psISE.Options.TokenColors['String'] = '#FF00D42D' 
  54. $psISE.Options.TokenColors['Keyword'] = '#FFFFDE00' 
  55. $psISE.Options.TokenColors['Attribute'] = '#FF84A7C1' 
  56. $psISE.Options.TokenColors['Type'] = '#FF84A7C1' 
  57. $psISE.Options.TokenColors['Variable'] = '#FF00D42D' 
  58. $psISE.Options.TokenColors['CommandParameter'] = '#FFFFDE00' 
  59. $psISE.Options.TokenColors['CommandArgument'] = '#FFFFFFFF' 
  60. $psISE.Options.TokenColors['Number'] = '#FF98FE1E' 
Technorati Tags: ,,,

Set-ISEThemeDefault.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script resets the ISE to default ‘theme’. 
  4. .DESCRIPTION 
  5.     This script sets the key values in $PsIse.Options to their default 
  6.     options in $Psise.Options.DefaultOptions. This script is useful if you 
  7.     are playing with ISE options and don't quite get it right - just run this  
  8.     script to set things back to default.        
  9. .NOTES 
  10.     File Name  : Set-ISEThemeDefault.ps1 
  11.     Author     : Thomas Lee - tfl@psp.co.uk 
  12.     Requires   : PowerShell Version 2.0 (ISE only) 
  13. .LINK 
  14.     This script posted to: 
  15.         http://bit.ly/gJpu2W  
  16. .EXAMPLE 
  17.     This script when run just resets the theme to the default. To view, run from 
  18.     the ISE after changing options! 
  19. #> 
  20.  
  21. # Set Basic options 
  22. $psise.options.SelectedScriptPaneState = $psise.options.DefaultOptions.SelectedScriptPaneState 
  23. $psise.options.ShowToolBar             = $psise.options.DefaultOptions.ShowToolBar 
  24. $psise.options.FontSize                = $psise.options.DefaultOptions.FontSize 
  25. $psise.options.Fontname                = $psise.options.DefaultOptions.Fontname 
  26.  
  27. # set colouring 
  28. $psise.options.ErrorForegroundColor          = $psise.options.DefaultOptions.ErrorForegroundColor 
  29. $psise.options.ErrorBackgroundColor          = $psise.options.DefaultOptions.ErrorBackgroundColor 
  30. $psise.options.WarningForegroundColor        = $psise.options.DefaultOptions.WarningForegroundColor 
  31. $psise.options.WarningBackgroundColor        = $psise.options.DefaultOptions.WarningBackgroundColor 
  32. $psise.options.VerboseForegroundColor        = $psise.options.DefaultOptions.VerboseForegroundColor 
  33. $psise.options.VerboseBackgroundColor        = $psise.options.DefaultOptions.VerboseBackgroundColor 
  34. $psise.options.DebugBackgroundColor          = $psise.options.DefaultOptions.DebugBackgroundColor 
  35. $psise.options.DebugForegroundColor          = $psise.options.DefaultOptions.DebugForegroundColor 
  36. $psise.options.OutputPaneBackgroundColor     = $psise.options.DefaultOptions.OutputPaneBackgroundColor 
  37. $psise.options.OutputPaneTextBackgroundColor = $psise.options.DefaultOptions.OutputPaneTextBackgroundColor 
  38. $psise.options.OutputPaneForegroundColor     = $psise.options.DefaultOptions.OutPutPaneForegroundColor 
  39. $psise.options.CommandPaneBackgroundColor    = $psise.options.DefaultOptions.CommandPaneBackgroundColor 
  40. $psise.options.ScriptPaneBackgroundColor     = $psise.options.DefaultOptions.ScriptPaneBackgroundColor  
  41. $psise.options.ScriptPaneForegroundColor     = $psise.options.DefaultOptions.ScriptPaneForegroundColor  
  42.  
  43. # More options 
  44. $psise.options.ShowWarningForDuplicateFiles  = $psise.options.DefaultOptions.ShowWarningForDuplicateFiles   
  45. $psise.options.ShowWarningBeforeSavingOnRun  = $psise.options.DefaultOptions.ShowWarningBeforeSavingOnRun 
  46. $psise.options.UseLocalHelp                  = $psise.options.DefaultOpitons.UseLocalHelp 
  47. $psise.options.CommandPaneUp                 = $psise.options.DefaultOptions.CommandPaneUp 
  48.  
  49. # Reset Tokens Colors 
  50. $psISE.Options.TokenColors['Attribute']          = $psISE.Options.DefaultOptions.TokenColors['Attribute'] 
  51. $psISE.Options.TokenColors['Command']            = $psISE.Options.DefaultOptions.TokenColors['Command'] 
  52. $psISE.Options.TokenColors['CommandArgument']    = $psISE.Options.DefaultOPtions.TokenColors['CommandArgument'] 
  53. $psISE.Options.TokenColors['CommandParameter']   = $psISE.Options.DefaultOptions.TokenColors['CommandParameter'] 
  54. $psISE.Options.TokenColors['Comment']            = $psISE.Options.DefaultOptions.TokenColors['Comment'] 
  55. $psISE.Options.TokenColors['GroupEnd']           = $psISE.Options.DefaultOptions.TokenColors['GroupEnd'] 
  56. $psISE.Options.TokenColors['GroupStart']         = $psISE.Options.DefaultOptions.TokenColors['GroupStart'] 
  57. $psISE.Options.TokenColors['Keyword']            = $psISE.Options.DefaultOptions.TokenColors['Keyword'] 
  58. $psISE.Options.TokenColors['LineContinuation']   = $psISE.Options.DefaultOptions.TokenColors['LineContinuation'] 
  59. $psISE.Options.TokenColors['LoopLabel']          = $psISE.Options.DefaultOptions.TokenColors['LoopLabel'] 
  60. $psISE.Options.TokenColors['Member']             = $psISE.Options.DefaultOptions.TokenColors['Member'] 
  61. $psISE.Options.TokenColors['NewLine']            = $psISE.Options.DefaultOptions.TokenColors['NewLine'] 
  62. $psISE.Options.TokenColors['Number']             = $psISE.Options.DefaultOPtions.TokenColors['Number'] 
  63. $psISE.Options.TokenColors['Position']           = $psISE.Options.DefaultOptions.TokenColors['Position'] 
  64. $psISE.Options.TokenColors['StatementSeparator'] = $psISE.Options.DefaultOptions.TokenColors['StatementSeparator'] 
  65. $psISE.Options.TokenColors['String']             = $psISE.Options.DefaultOptions.TokenColors['String'] 
  66. $psISE.Options.TokenColors['Type']               = $psISE.Options.DefaultOptions.TokenColors['Type']  
  67. $psISE.Options.TokenColors['Unknown']            = $psISE.Options.DefaultOptions.TokenColors['Unknown'] 
  68. $psISE.Options.TokenColors['Variable']           = $psISE.Options.DefaultOptions.TokenColors['Variable'] 
  69.  
  70. # Done 

Thursday, 7 October 2010

Get-WMINameSpace.ps1


  1. <# 
  2. .SYNOPSIS 
  3.     This script displays all the WMI namespaces within a Windows system 
  4. .DESCRIPTION 
  5.     This script uses Get-WMIObject to retrieve the names of all the namespaces 
  6.     within a system. 
  7. .NOTES 
  8.     File Name  : Get-WMINameSpace.ps1 
  9.     Author     : Thomas Lee - tfl@psp.co.uk 
  10.     Requires   : PowerShell Version 2.0 
  11. .LINK 
  12.     This script posted to:
  13.         http://pshscripts.blogspot.com/2010/10/get-wminamespaceps1.html
  14. .EXAMPLE 
  15.     PSH [C:\foo]: .\Get-WMINameSpace.ps1 
  16.     37 Namespaces on: Cookham8 
  17.  
  18.     Namespace 
  19.     --------- 
  20.     ROOT 
  21.     ROOT\aspnet 
  22.     ROOT\CIMV2 
  23.     ROOT\CIMV2\Security 
  24.     ROOT\CIMV2\Security\MicrosoftTpm 
  25.     ... {Remainder of list snipped to save space on this page} 
  26. #> 
  27.  
  28. # Set computer name
  29. $comp = "." 
  30. # Get the name spaces on the local computer, and the local computer name 
  31. $Namespace = get-wmiobject __namespace -namespace 'root' -list -recurse -computer $comp  
  32. $hostname = hostname 
  33.  
  34. # Display number of and names of the namespaces 
  35. "{0} Namespaces on: {1}" -f $namespace.count, $hostname 
  36. $NameSpace| sort __namespace  | Format-Table @{Expression = "__Namespace"; Label = "Namespace"
Technorati Tags: ,,,

Friday, 24 September 2010

New-Task.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script creates a scheduled task object. 
  4. .DESCRIPTION 
  5.     This script re-implements an MSDN sample using PowerShell 
  6. .NOTES 
  7.     File Name  : New-Task.ps1 
  8.     Author     : Thomas Lee - tfl@psp.co.uk 
  9.     Requires   : PowerShell Version 2.0 
  10. .LINK 
  11.     This script posted to: 
  12.         http://www.pshscripts.blogspot.com 
  13.     MSDN sample posted tot: 
  14.         http://msdn.microsoft.com/en-us/library/aa383665%28VS.85%29.aspx 
  15. .EXAMPLE 
  16.     PSH [C:\foo]: .\New-Task.ps1
  17.     Time Now       : 9/24/2010 12:43:47 PM 
  18.     Task startTime : 2010-09-24T12:44:17 
  19.     Task endTime   : 2010-09-24T12:48:47 
  20.     Task definition created. About to submit the task... 
  21.   
  22.   
  23.     Name               : Test TimeTrigger 
  24.     Path               : Test TimeTrigger 
  25.     State              : 3 
  26.     Enabled            : True 
  27.     LastRunTime        : 12/30/1899 12:00:00 AM 
  28.     LastTaskResult     : 1 
  29.     NumberOfMissedRuns : 0 
  30.     NextRunTime        : 9/24/2010 12:44:17 PM 
  31.     Definition         : System.__ComObject 
  32.     Xml                : <?xml version="1.0" encoding="UTF-16"?> 
  33.                          <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"
  34.                            <RegistrationInfo> 
  35.                              <Author>Thomas Lee</Author> 
  36.                              <Description>Start notepad at a certain time</Description> 
  37.                            </RegistrationInfo> 
  38.                            <Triggers> 
  39.                              <TimeTrigger id="TimeTriggerId"
  40.                                <StartBoundary>2010-09-24T12:44:17</StartBoundary> 
  41.                                <EndBoundary>2010-09-24T12:48:47</EndBoundary> 
  42.                                <ExecutionTimeLimit>PT5M</ExecutionTimeLimit> 
  43.                                <Enabled>true</Enabled> 
  44.                              </TimeTrigger> 
  45.                            </Triggers> 
  46.                            <Settings> 
  47.                              <IdleSettings> 
  48.                                <Duration>PT10M</Duration> 
  49.                                <WaitTimeout>PT1H</WaitTimeout> 
  50.                                <StopOnIdleEnd>true</StopOnIdleEnd> 
  51.                                <RestartOnIdle>false</RestartOnIdle> 
  52.                              </IdleSettings> 
  53.                              <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy> 
  54.                              <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries> 
  55.                              <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries> 
  56.                              <AllowHardTerminate>true</AllowHardTerminate> 
  57.                              <StartWhenAvailable>true</StartWhenAvailable> 
  58.                              <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable> 
  59.                              <AllowStartOnDemand>true</AllowStartOnDemand> 
  60.                              <Enabled>true</Enabled> 
  61.                              <Hidden>false</Hidden> 
  62.                              <RunOnlyIfIdle>false</RunOnlyIfIdle> 
  63.                              <WakeToRun>false</WakeToRun> 
  64.                              <ExecutionTimeLimit>PT72H</ExecutionTimeLimit> 
  65.                              <Priority>7</Priority> 
  66.                            </Settings> 
  67.                            <Actions Context="Author"
  68.                              <Exec> 
  69.                                <Command>C:\Windows\System32\notepad.exe</Command> 
  70.                              </Exec> 
  71.                            </Actions> 
  72.                            <Principals> 
  73.                              <Principal id="Author"
  74.                                <UserId>COOKHAM\tfl</UserId> 
  75.                                <LogonType>InteractiveToken</LogonType> 
  76.                              </Principal> 
  77.                            </Principals> 
  78.                          </Task> 
  79.  
  80.     Task submitted. 
  81. #> 
  82. # Helper Function 
  83. function XMLTIME{ 
  84. Param ( $T) 
  85. $csecond = $t.Second.ToString() 
  86. $cminute = $t.minute.ToString() 
  87. $chour = $t.hour.ToString() 
  88. $cday  = $t.day.ToString() 
  89. $cmonth  = $t.month.ToString() 
  90. $cyear = $t.year.ToString() 
  91.  
  92. $date =  $cyear + "-" 
  93. if ($cmonth.Length -eq 1) { $date += "0" + $cmonth + "-"}  
  94. else                      { $date += $cmonth + "-"
  95. if ($cday.length -eq 1)   { $date += "0" + $cday + "T"
  96. else                      { $date += $cday + "T"
  97. if ($chour.length -eq 1)  { $date += "0" + $chour + ":"
  98. else                      { $date += $chour + ":"
  99. if ($cminute.length -eq 1){ $date += "0" + $cminute + ":"
  100. else                      { $date += $cminute + ":"
  101. if ($csecond.length -eq 1){ $date += "0" + $csecond} 
  102. else                      { $date += $csecond} 
  103. # return 
  104. $date 
  105.  
  106. ## Script starts here 
  107.  
  108. # A constant that specifies a time-based trigger. 
  109. $TriggerTypeTime = 1 
  110. # A constant that specifies an executable action. 
  111. $ActionTypeExec = 0    
  112.  
  113. # Create and connect to the service 
  114. $service = New-Object -com schedule.service  
  115. $service.Connect() 
  116.  
  117. # Get a folder to create a task definition in.  
  118. $rootFolder = $service.GetFolder("\") 
  119.  
  120. # The taskDefinition variable is the TaskDefinition object. 
  121. # The flags parameter is 0 because it is not supported. 
  122. $taskDefinition = $service.NewTask(0)  
  123.  
  124. # Define information about the task. 
  125. # Set the registration info for the task by  
  126. # creating the RegistrationInfo object. 
  127. $regInfo = $taskDefinition.RegistrationInfo 
  128. $regInfo.Description = "Start notepad at a certain time" 
  129. $regInfo.Author = "Thomas Lee" 
  130.  
  131. # Set the principal for the task 
  132. $principal = $taskDefinition.Principal 
  133.  
  134. # Set the logon type to interactive logon 
  135. $principal.LogonType = 3 
  136.  
  137. # Set the task setting info for the Task Scheduler by 
  138. # creating a TaskSettings object. 
  139. $settings = $taskDefinition.Settings 
  140. $settings.Enabled = $True 
  141. $settings.StartWhenAvailable = $True 
  142. $settings.Hidden = $False 
  143.  
  144. # Create a time-based trigger. 
  145. $triggers = $taskDefinition.Triggers 
  146. $trigger = $triggers.Create($TriggerTypeTime) 
  147.  
  148. # Trigger variables that define when the trigger is active. 
  149. $time = ([system.datetime]::now).addseconds(30) 
  150. $startTime = XmlTime($time) 
  151.  
  152. $time = ([system.datetime]::now).addminutes(5) 
  153. $endTime = XmlTime($time) 
  154.  
  155. "Time Now       : {0}" -f (Get-Date -display time) 
  156. "Task startTime : {0}" -f $startTime 
  157. "Task endTime   : {0}" -f $endTime 
  158.  
  159. $trigger.StartBoundary = $startTime 
  160. $trigger.EndBoundary = $endTime 
  161. $trigger.ExecutionTimeLimit = "PT5M"    #Five minutes 
  162. $trigger.Id = "TimeTriggerId" 
  163. $trigger.Enabled = $True 
  164.  
  165. # Create the action for the task to execute. 
  166.  
  167. # Add an action to the task to run notepad.exe. 
  168. $Action = $taskDefinition.Actions.Create( $ActionTypeExec ) 
  169. $Action.Path = "C:\Windows\System32\notepad.exe" 
  170.  
  171. "Task definition created. About to submit the task..." 
  172.  
  173. # Register (create) the task. 
  174. $rootFolder.RegisterTaskDefinition("Test TimeTrigger", $taskDefinition, 6,"" ,"" , 3) 
  175.  
  176. # all done! 
  177. "Task submitted." 

Thursday, 2 September 2010

Get-UmAlQuraCalendar.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script displays details of a UmAlQura Calendar in PowerShell 
  4. .DESCRIPTION 
  5.     This script shows the various aspects of this calendar including key properties, 
  6.     fields and selected methods. 
  7. .NOTES 
  8.     File Name  : Get-UmAlQuraCalendar.ps1 
  9.     Author     : Thomas Lee - tfl@psp.co.uk 
  10.     Requires   : PowerShell Version 2.0 
  11. .LINK 
  12.     This script posted to: 
  13.         http://www.pshscripts.blogspot.com 
  14.     MSDN Sample posted at: 
  15.         http://msdn.microsoft.com/en-us/library/system.globalization.umalquracalendar.aspx 
  16. .EXAMPLE 
  17.     PSH [C:\foo]: .\Get-UmAlQuraCalendar.ps1' 
  18.     Um Al Qura Calendar 
  19.     Algorithm Type          : LunarCalendar 
  20.     Eras in Calendar        : 1 
  21.     Is read only?           : False 
  22.     Max Supported Date/Time : 5/13/2029 11:59:59 PM 
  23.     Min Supported Date/Time : 4/30/1900 12:00:00 AM 
  24.     Two Digit Year Max      : 1451 
  25.   
  26.     April 3, 2002 of the Gregorian calendar equals the following in the UmAlQura calendar: 
  27.        Era:            1 
  28.        Year:           1423 
  29.        Is Leap Year?   False 
  30.        Days In Year:   354 
  31.        Month:          1 
  32.        Months in Year: 12 
  33.        Days in Month:  29 
  34.        Leap Month:     0 
  35.        DayOfYear:      20 
  36.        DayOfMonth:     20 
  37.        DayOfWeek:      Wednesday 
  38.   
  39.     After adding two years and ten months and one day: 
  40.        Era:            1 
  41.        Year:           1425 
  42.        Is Leap Year?   True 
  43.        Days In Year:   355 
  44.        Month:          11 
  45.        Months in Year: 12 
  46.        Days in Month:  30 
  47.        Leap Month:     0 
  48.        DayOfYear:      317 
  49.        DayOfMonth:     21 
  50.        DayOfWeek:      Sunday 
  51. #>     
  52.  
  53. # Helper Function 
  54. Function DisplayValues { 
  55. param ($MyCal, $MyDT
  56.  
  57. "   Era:            {0}" -f $MyCal.GetEra($MyDT)  
  58. "   Year:           {0}" -f $MyCal.GetYear($MyDT
  59. "   Is Leap Year?   {0}" -f $MyCal.IsLeapYear($MyCal.GetYear($MyDT)) 
  60. "   Days In Year:   {0}" -f $MyCal.GetDaysInYear($MyCal.GetYear($MyDT)) 
  61. "   Month:          {0}" -f $MyCal.GetMonth($MyDT
  62. "   Months in Year: {0}" -f $MyCal.GetMonthsInYear($MyCal.GetYear($MyDT)) 
  63. "   Days in Month:  {0}" -f $MyCal.GetDaysInMonth($MyCal.GetYear($MyDT), $MyDT.Month) 
  64. "   Leap Month:     {0}" -f $MyCal.GetLeapMonth($MyCal.GetYear($MyDT)) 
  65. "   DayOfYear:      {0}" -f $MyCal.GetDayOfYear($MyDT
  66. "   DayOfMonth:     {0}" -f $MyCal.GetDayOfMonth($MyDT
  67. "   DayOfWeek:      {0}" -f $MyCal.GetDayOfWeek($MyDT
  68. "" 
  69.        
  70. # Sets a DateTime to April 3, 2002 of the Gregorian calendar. 
  71.  $MyDT = New-Object System.DateTime 2002, 4, 3, (New-Object System.Globalization.GregorianCalendar) 
  72.    
  73. # Creates an instance of the UmAlQuraCalendar. 
  74. $MyCal = New-Object System.Globalization.UmAlQuraCalendar 
  75. # Display properties of the calendar 
  76. "Um Al Qura Calendar" 
  77. "Algorithm Type          : {0}" -f $MyCal.AlgorithmType 
  78. "Eras in Calendar        : {0}" -f $MyCal.Eras.count 
  79. "Is read only?           : {0}" -f $MyCal.IsReadOnly 
  80. "Max Supported Date/Time : {0}" -f $MyCal.MaxSupportedDateTime 
  81. "Min Supported Date/Time : {0}" -f $MyCal.MinSupportedDateTime 
  82. "Two Digit Year Max      : {0}" -f $MyCal.TwoDigitYearMax 
  83. "" 
  84.   
  85. # Display the values of the DateTime. 
  86.  "April 3, 2002 of the Gregorian calendar equals the following in the UmAlQura calendar:"  
  87. DisplayValues $MyCal $MyDT  
  88.  
  89. # Adds two years and ten months and one Day. 
  90. $MyDT = $MyCal.AddYears( $MyDT, 2 ) 
  91. $MyDT = $MyCal.AddMonths($MyDT, 10 ) 
  92. $MyDT = $MyCal.AddDays($MyDT, 1 ) 
  93.   
  94. # Display the values of the DateTime. 
  95. "After adding two years and ten months and one day:" 
  96. DisplayValues $MyCal $MyDT 

Wednesday, 4 August 2010

Get-MultiplyBigInteger.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script re-implements this MSDN Sample of  
  4.     multiplying a big integer. 
  5. .DESCRIPTION 
  6.     This script first tries and fails to multiple a pair of large integers. The 
  7.     script catches the error and then used BigInteger.Multiply to multiply  
  8.     the two big itegers. 
  9. .NOTES 
  10.     File Name  : Get-MultiplyBigInteger.ps1 
  11.     Author     : Thomas Lee - tfl@psp.co.uk 
  12.     Requires   : PowerShell Version 2.0 
  13. .LINK 
  14.     This script posted to: 
  15.         http://www.pshscripts.blogspot.com 
  16.     MSDN Sample posted at: 
  17.         http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.multiply.aspx 
  18. .EXAMPLE 
  19.     PSH [C:\foo]: .Get-MultiplyBigInteger.ps1 
  20.     Too big for long, try biginteger 
  21.     12,193,263,111,263,526,900 
  22. #> 
  23. # Add System.Numerics namespace 
  24. $r=[system.Reflection.Assembly]::LoadWithPartialName("System.Numerics"
  25.  
  26. # Two big numbers 
  27. $number1 = 1234567890 
  28. $number2 = 9876543210 
  29.  
  30. # Try normal [long] then catch error and do biginteger 
  31. try 
  32.    [long] $product = $number1 * $number2 
  33. catch  
  34. "Too big for long, try biginteger" 
  35.    $product = New-Object System.Numerics.BigInteger 
  36.    $product = [System.Numerics.BigInteger]::Multiply($number1, $number2
  37.    $product.ToString("N0"
  38. }    

Saturday, 31 July 2010

Get-WmiClassDescription.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script gets and displays the description of a WMI Class.  
  4. .DESCRIPTION 
  5.     This script takes a WMI Class name as a parameter. The script 
  6.     then gets the class's description from the CIM repository and 
  7.     displays it. Based on a PowerShell.Com tip of the day! 
  8. .NOTES 
  9.     File Name  : Get-WmiClassDescription.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.     PSH [C:\foo]: .\Get-WmiClassDescription.ps1 
  17.     Description for WMI Class Win32_ComputerSystem: 
  18.     The Win32_ComputerSystem class represents a computer system operating in a Win32 environment. 
  19. .EXAMPLE 
  20.     PSH [C:\foo]: . \Get-WmiClassDescription.ps1 win32_bios 
  21.     Description for WMI Class win32_bios: 
  22.     The Win32_BIOS class represents the attributes of the computer system's basic input/output services 
  23.     (BIOS) that are installed on the computer. 
  24. #> 
  25.  
  26. param
  27. [string] $WMIClassName = "Win32_ComputerSystem" 
  28.  
  29. # Get WMI class from class name 
  30. $class = [wmiclass]$wmiclassname 
  31.  
  32. # Now get then print the class description 
  33. # First use ammended qualifiers to get description 
  34. $class.psbase.Options.UseAmendedQualifiers = $true 
  35. "Description for WMI Class {0}:"  -f $WmiClassName 
  36. ($class.psbase.qualifiers["description"]).Value 

Thursday, 15 July 2010

Copy-File2.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script creates a file, then reads it and displays the output. 
  4. .DESCRIPTION 
  5.     This script implements the MSDN sample for this page. It first creates a file (assuming the file 
  6.     does not already exist) and writes three lines to it. The script then opens the file, reads each 
  7.     line and displays it.    
  8.      
  9. .NOTES 
  10.     File Name  : Copy-File2.ps1 
  11.     Author     : Thomas Lee - tfl@psp.co.uk 
  12.     Requires   : PowerShell Version 2.0 
  13. .LINK 
  14.     This script posted to: 
  15.         http://pshscripts.blogspot.com/2010/07/copy-file2ps1.html
  16.     MSDN Sample posted at: 
  17.         http://msdn.microsoft.com/en-us/library/system.io.file.aspx        
  18.         http://msdn.microsoft.com/en-us/library/system.io.file.createtext.aspx
  19.         http://msdn.microsoft.com/en-us/library/system.io.file.opentext.aspx
  20. .EXAMPLE 
  21.     PSH [C:\foo]: . 'E:\PowerShellScriptLib\System.Io.File\Copy-File2.PS1' 
  22.     Hello 
  23.     And 
  24.     Welcome  
  25. #> 
  26.    
  27. # Set name of file to use for this script 
  28. $path = "c:\foo\MyTest.txt" 
  29.    
  30. # Create the file if it does not already exist 
  31. if (![System.IO.File]::Exists($path))  { 
  32.   $sw = [System.Io.File]::CreateText($path
  33.   $sw.WriteLine("Hello"
  34.   $sw.WriteLine("And"
  35.   $sw.WriteLine("Welcome"
  36.    
  37. # Open the file to read from and set $s to an empty string 
  38. $sr = [System.Io.File]::OpenText($path
  39. $s = ""
  40.  
  41. # Loop through the file, line at a time and display the output 
  42. while (($s = $sr.ReadLine()) -ne $null)  { 
  43.   $s 
  44.   
  45. # And close the reader/writer 
  46. $sw.Close() 
  47. $sr.Close() 

Saturday, 22 May 2010

Get-ServiceDetails.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script displays service details 
  4. .DESCRIPTION 
  5.     This script first enumerates all the service controllers (ie services) 
  6.     running on the local system. For each service, we look into WMI and 
  7.     get info about that running service. 
  8. .NOTES 
  9.     File Name  : Get-ServiceDetails.ps1 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell Version 2.0 
  12. .LINK 
  13.     This script posted to: 
  14.         http://pshscripts.blogspot.com/2010/05/get-servicedetailsps1.html 
  15.     MSDN Sample posted at: 
  16.         http://msdn.microsoft.com/en-us/library/hde9d63a.aspx   
  17. .EXAMPLE 
  18.     PSH [C:\foo]: .\Get-ServiceDetails.ps1' 
  19.     Services running on the local computer: 
  20.  
  21.       Service :        AeLookupSvc 
  22.         Display name:    Application Experience 
  23.         Start name:      localSystem 
  24.         Description:     Processes application compatibility cache requests for applications as they are launched 
  25.  
  26.       Service :        AppHostSvc 
  27.         Display name:    Application Host Helper Service 
  28.         Start name:      LocalSystem 
  29.         Description:     Provides administrative services for IIS, for example configuration history and Applicati 
  30. on Pool account mapping. If this service is stopped, configuration history and locking down files or directori 
  31. es with Application Pool specific Access Control Entries will not work. 
  32. <rest snipped to save space!> 
  33. #> 
  34.  
  35. ## 
  36. # Start of script 
  37. ## 
  38.   
  39. # Load assembly with ServiceProcess class 
  40. $result = [reflection.Assembly]::LoadWithPartialName("System.ServiceProcess"
  41. $Services = [System.ServiceProcess.ServiceController]::GetServices() 
  42.   
  43. # Get WMI Services 
  44. $WMIServices = gwmi win32_service 
  45. # Display the list of services currently running on this computer. 
  46.   
  47. "Services running on the local computer:" 
  48. foreach ($Service in $Services) { 
  49.   
  50. if ($Service.Status -eq [system.ServiceProcess.ServiceControllerStatus]::Running)  { 
  51.   # Write the service name and the display name 
  52.   # for each running service. 
  53.   "" 
  54.   "  Service :        {0}"      -f  $Service.ServiceName 
  55.   "    Display name:    {0}"    -f  $Service.DisplayName 
  56.   # query WMI for more info on service 
  57.   $svc = $wmiServices  | where {$_.name -eq $service.servicename}   
  58.   "    Start name:      {0}"    -f  $Svc.StartName 
  59.   "    Description:     {0}"    -f  $Svc.Description 
  60. # End