Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Friday, 28 November 2014

Get-Stack1.ps1


<#
.SYNOPSIS
MSDN sample showing push and other stack processing using PowerShell
.DESCRIPTION
This script creates a script then performs stack operations.
.NOTES
File Name : Get-Stack1.p1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell V2
.LINK
http://www.pshscripts.blogspot.com
.EXAMPLE
PSH [C:\foo]: .\get-stack1.ps1'
Stack at start:
fox
quick
The

(Pop) fox
Stack value after Pop:
brown
quick
The

(Pop) brown
Stack values after 2nd pop:
quick
The

(Peek) quick
Stack values after a peek:
quick
The
#>

##
# start of script
###

# Create and initialise a new stack object
$mystack = new-object system.collections.stack
$myStack.Push( "The" )
$myStack.Push( "quick" )
$myStack.Push( "brown" )
$myStack.Push( "fox" )

# Display the Stack
"Stack at start:"
$myStack
""# Pop an element from the Stack.
"(Pop)`t`t{0}" -f $myStack.Pop()
"Stack value after Pop:"
$myStack
""

# Pop another element from the Stack
"(Pop)`t`t{0}" -f $myStack.Pop()

# Display the Stack after 2nd pop
"Stack values after 2nd pop:"
$myStack
""

# Peek at the front
"(Peek)`t`t{0}" -f $myStack.peek()

# Display the Stack after the peek
"Stack values after a peek:"
$myStack

Monday, 4 February 2013

Configure-DC1-2.ps1

  1. #### 
  2. # Configure-DC1-2 
  3. # Configures DC1 after dcpromo is completed 
  4. # 
  5. # Version    Date         What Changed 
  6. # -------    -----------  ------------------------------------------- 
  7. # 1.0.0      14 Jan 2013  Initial release 
  8. # 1.1.0      24 Jan 2013  Added code to count how long it all took, 
  9. #                         Added checkpoint at the end of this script 
  10. # 1.1.1      25 Jan 2013  Added auto admin logon 
  11. # 1.1.2      5  Feb 2013  Added forced reboot of DC1-1 at script end  
  12. #### 
  13.  
  14. #     Configuration block 
  15. $Conf = { 
  16.  
  17. $StartTime = Get-Date 
  18. Write-Host "Starting at: $StartTime" 
  19.  
  20. #    Set Credentials for use in this configuration block 
  21. $User       = "Reskit\Administrator" 
  22. $Password   = 'Pa$$w0rd' 
  23. $PasswordSS = ConvertTo-SecureString  -String $Password –AsPlainText `
  24.               -Force 
  25. $Dom        = 'Reskit' 
  26. $CredRK     = New-Object  `
  27.     -Typename System.Management.Automation.PSCredential  `
  28.      -Argumentlist $User,$PasswordSS 
  29.  
  30. #    Define registry path for autologon, then set admin logon 
  31. $RegPath  = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' 
  32. Set-ItemProperty -Path  $RegPath -Name AutoAdminLogon   ` 
  33.                  -Value 1      -EA 0   
  34. Set-ItemProperty -Path  $RegPath -Name DefaultUserName   ` 
  35.                  -Value $User  -EA 0   
  36. Set-ItemProperty -Path  $RegPath -Name DefaultPassword   ` 
  37.                  -Value $Password -EA 0 
  38. Set-ItemProperty -Path  $RegPath -Name DefaultDomainName  ` 
  39.                  -Value $Dom -EA 0  
  40.  
  41. #    Install key Windows features for labs 
  42. Write-Verbose 'Installing Windows fetures needed for DC1' 
  43. $Features = @('PowerShell-ISE'
  44.               'Hyper-V-PowerShell'
  45.               'Rsat-AD-PowerShell',               
  46.               'Web-Server','Web-Mgmt-Tools'
  47.               'Web-Mgmt-Console'
  48.               'Web-Scripting-Tools'
  49.               'Telnet-Client'
  50. Install-WindowsFeature @Features -IncludeManagementTools -Verbose 
  51.  
  52. #    Install and configure DHCP 
  53. Write-Verbose -Message 'Adding and then configuring DHCP' 
  54. Install-WindowsFeature DHCP -IncludeManagementTools 
  55. Add-DhcpServerV4Scope -Name "ReskitNet0"
  56.                       -StartRange 10.0.0.100 ` 
  57.                       -EndRange 10.0.0.119 ` 
  58.                       -SubnetMask 255.255.255.0 
  59. Set-DhcpServerV4OptionValue -DnsDomain Reskit.Org ` 
  60.                             -DnsServer 10.0.0.10 
  61. Add-DhcpServerInDC -DnsName Dc1.reskit.org 
  62.  
  63. #    Add users to the AD and then add them to some groups 
  64. #    Hash table for common new user paraemters 
  65. Write-Verbose -Message 
  66. $NewUserHT  = @{AccountPassword       = $PasswordSS
  67.                 Enabled               = $true
  68.                 PasswordNeverExpires  = $true
  69.                 ChangePasswordAtLogon = $false 
  70.                 } 
  71.  
  72. #     Create one new user (me!) and add to enterprise and domain admins security groups 
  73. New-ADUser @NewUserHT -SamAccountName tfl ` 
  74.                       -UserPrincipalName 'tfl@reskit.org'
  75.                       -Name "tfl"
  76.                       -DisplayName 'Thomas Lee' 
  77. Add-ADPrincipalGroupMembership `
  78.        -Identity "CN=tfl,CN=Users,DC=reskit,DC=org"
  79.        -MemberOf "CN=Enterprise Admins,CN=Users,DC=reskit,DC=org"
  80.                  "CN=Domain Admins,CN=Users,DC=reskit,DC=org"  
  81.  
  82. #     Say nice things and finish 
  83. $FinishTime = Get-Date 
  84. Write-Verbose "Finished at: $FinishTime" 
  85. Write-Verbose "DC1 Configuration took $(($FinishTime - $StartTime).TotalSeconds.ToString('n2')) seconds" 
  86.  
  87. } # End Conf configuration script block 
  88.  
  89. #    Start of script proper 
  90.  
  91. #    Set Credentials 
  92. $Username   = "Reskit\administrator" 
  93. $Password   = 'Pa$$w0rd' 
  94. $PasswordSS = ConvertTo-SecureString  -String $Password -AsPlainText
  95.               -Force 
  96. $CredRK     = New-Object -Typename System.Management.Automation.PSCredential `
  97.         -Argumentlist $Username,$PasswordSS 
  98.  
  99. #    Following code used to test the credentials. Remove the comments on next two lines the first time you  
  100. #    run this script 
  101. Invoke-Command -ComputerName DC1 -ScriptBlock {hostname} -Credential $Credrk -verbose 
  102. Pause 
  103.  
  104. Invoke-Command -ComputerName DC1 -Scriptblock $conf -Credential $CredRK `
  105.                -Verbose 
  106.  
  107. #     OK - script block has completed - reboot the system and wait till it comes up 
  108. Restart-Computer -ComputerName DC1  -Wait -For PowerShell –Force
  109.                  -Credential $CredRK 
  110.   
  111. #    Finally, run a post-DCPromo snapshot 
  112. Checkpoint-VM -VM $(Get-VM DC1) `
  113. -SnapshotName "DC1 - post configuration by ConfigureDC1-2.ps1"  

Wednesday, 23 January 2013

Configure-DC1-1.ps1

  1. # Configure-DC1-1.ps1
  2. # Converts Server to DC
  3. # Version 1.0.0 - 14 Jan 2013
  4. # See http://tfl09.blogspot.com for more details
  5. # Config script block
  6. $conf = {
  7. # Install the AD - the reboot is or should be automagic
  8. Install-Windowsfeature AD-Domain-Services -IncludeManagementTools
  9. # Now install the AD to DC1
  10. $PasswordSS = ConvertTo-SecureString -string 'Pa$$w0rd' -AsPlainText -Force
  11. Install-ADDSForest -DomainName Reskit.Org -SafeModeAdministratorPassword $PasswordSS -force -InstallDNS -DomainMode Win2012 -ForestMode Win2012
  12. }
  13. # Here is start of script
  14. $Username = "DC1\administrator"
  15. $PasswordSS = ConvertTo-SecureString 'Pa$$w0rd' -AsPlainText -Force
  16. $Creddc1 = New-Object system.management.Automation.PSCredential $username,$PasswordSS
  17. # First, run a simple script block to check that the server is actually running and is the one we think it is
  18. Invoke-Command -ComputerName DC1 -ScriptBlock { ipconfig;hostname} -Credential $Creddc1 -verbose
  19. Pause
  20. # Now add create our forest/domain/dc
  21. Invoke-Command -ComputerName DC1 -Scriptblock $conf -Credential $Creddc1 -verbose
Technorati Tags: ,,,

Monday, 21 January 2013

Create-VM.PS1

  1. # Create-VM.ps1 
  2. # Script that creates VMs 
  3. # Version 1.0.0 - 20 Jan 2013 
  4. # See http://tfl09.blogspot.co.uk/2013/01/building-hyper-v-test-lab-on-windows-8.html 
  5.  
  6. # First define the Create-VM Function 
  7.  
  8. Function Create-VM { 
  9. #=================================================== 
  10. # Create a New VM 
  11. #=================================================== 
  12.  
  13. # Parameters are Name, Virtual Machine Path, path to reference Vhdx,
  14. # network switch to use, VM Memory, Unattend file, IP address and DNS
  15. # Server to set. Default values are specified in the Param block,
  16. # but these are normally overridden in the call to Create0VM 
  17.  
  18.  
  19. [Cmdletbinding()] 
  20. Param (  
  21.  $Name         = "Server"
  22.  $VmPath       = "C:\v3"
  23.  $ReferenceVHD = "C:\v3\Ref2012.vhdx"
  24.  $Network      = "Internal"
  25.  $VMMemory     = 512mb, 
  26.  $UnattendXML  = "C:\v3\unattend.xml"
  27.  $IPAddr       = '10.0.0.250/24'
  28.  $DnsSvr       = '10.0.0.10' 
  29.  
  30. $Starttime = Get-Date 
  31. Write-Verbose "Starting Create-VM at $Starttime" 
  32. Write-verbose "Creating VM: [$name]" 
  33. Write-verbose "Path to VM : [$VMpath]" 
  34.  
  35. #    Set path to differencing disk location 
  36. $path = "$vmpath\$name.vhdx" 
  37. Write-Verbose "Creating Disk at [$path]" 
  38.  
  39. #    Add a new differencing VHDX, Based on parent parent 
  40. $vmDisk01 = New-VHD –Path $path -Differencing –ParentPath $ReferenceVHD -ErrorAction Stop 
  41. Write-Verbose "Added VM Disk [$VMdisk01], pointing to [ReferenceVHD]" 
  42.  
  43. #    Create a New VM 
  44. $VM = New-VM –Name $name –MemoryStartupBytes $VMMemory –VHDPath $VMDisk01.path -SwitchName $Network -Path $vmPath 
  45. Write-Verbose "VM [$name] created" 
  46.  
  47. # Mount the Disk into the VM 
  48. Mount-DiskImage -ImagePath $path 
  49. $VHDDisk = Get-DiskImage -ImagePath $path | Get-Disk 
  50. $VHDPart = Get-Partition -DiskNumber $VHDDisk.Number 
  51. $VHDVolumeName = [string]$VHDPart.DriveLetter 
  52. $VHDVolume = [string]$VHDPart.DriveLetter + ":" 
  53. Write-verbose "Volume [$Volumename] created in VM [$name]" 
  54.  
  55.  
  56. #    Get Unattended.XML file 
  57. Write-Verbose "Using Unattended XML file [$unattendXML]" 
  58.  
  59. #    Open XML file 
  60. $Xml = [xml](get-content $UnattendXML
  61.  
  62. #    Change ComputerName 
  63. Write-Verbose "Setting VM ComputerName to: [$name]" 
  64. $Xml.unattend.settings.component | Where-Object { $_.Name -eq "Microsoft-Windows-Shell-Setup" } | 
  65.  ForEach-Object
  66.    if($_.ComputerName) { 
  67.      $_.ComputerName = $name 
  68.    } 
  69.  
  70. #    Change IP address 
  71. Write-Verbose "Setting VM ComputerName to: [$name]" 
  72. $Xml.unattend.settings.component | Where-Object { $_.Name -eq "Microsoft-Windows-TCPIP" } | 
  73.   ForEach-Object
  74.  
  75.     if($_.Interfaces) { 
  76.       $ht='#text' 
  77.       $_.interfaces.interface.unicastIPaddresses.ipaddress.$ht = $IPAddr 
  78.   } 
  79.  
  80. #    Change DNS Server address 
  81. #    Use obscure way to create the #TEXT node 
  82. Write-Verbose "Setting VM DNS address to: [$DNSSvr]" 
  83. $Xml.Unattend.Settings.Component | Where-Object { $_.Name -eq "Microsoft-Windows-DNS-Client" } | 
  84.   ForEach-Object
  85.       if($_.Interfaces) { 
  86.       $ht='#text' 
  87.       $_.Interfaces.Interface.DNSServerSearchOrder.Ipaddress.$ht = $DNSSvr 
  88.   } 
  89.  
  90. #    Save XML File on Mounted VHDX differencing disk 
  91. $xml.Save("$VHDVolume\Unattend.XML"
  92. Write-Verbose "Unattended XML file saved to vhd [$vhdvolume\unattend.xml]" 
  93.  
  94. #    Dismount VHDX  
  95. Write-Verbose "Dismounting disk image: [$Path]" 
  96. Dismount-DiskImage -ImagePath $path 
  97.  
  98. #    Update additional VM settings 
  99. Write-Verbose 'Setting additional VM settings' 
  100. Set-VM -Name $name -DynamicMemory 
  101. Set-VM -Name $name -MemoryMinimumBytes $VMMemory 
  102. Set-VM -Name $name -AutomaticStartAction Nothing 
  103. Set-Vm -Name $name -AutomaticStopAction ShutDown 
  104.  
  105. #    Show what has been created! 
  106. "VM Created:" 
  107. Get-VM -Name $name | fl * 
  108.  
  109. #    Start VM 
  110. Write-verbose "VM [$Name] being started" 
  111. Start-VM -Name $name 
  112.  
  113. #    Now work out and write how long it took to create the VM 
  114. $Finishtime = Get-Date 
  115. Write-Verbose ("Creating VB ($name) took {0} seconds" -f ($FinishTime - $Starttime).totalseconds) 
  116. # End of Create-VM function 
  117.  
  118.  
  119. ####################################################################################################### 
  120. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
  121. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
  122. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
  123.  
  124. # Location of Server 2012 DVD Iso Image 
  125. $iso   = 'c:\Builds\9200.16384.120725-1247_x64frev_Server_Datacenter_VL_HRM_SSS_X64FREV_EN-US_DVD.iso' 
  126. # Where we put the reference VHDX 
  127. $ref   = 'c:\v3\Ref2012.vhdx' 
  128. # Path were VMs, VHDXs and unattend.txt files live 
  129. $path  = 'c:\V3' 
  130. # Location of Unattend.xml - first for workstation systems, second for domain joined systems  
  131. $una   = 'c:\V3\UnAttend.xml' 
  132. $unadj = 'c:\V3\UnAttend.dj.xml' 
  133.  
  134. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
  135. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
  136. #       CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS     # 
  137. ####################################################################################################### 
  138.  
  139. #   Now run the script to create the VMs as appropriate. 
  140. $Start = Get-Date 
  141. "Create-VM --- Started at: $Start" 
  142.  
  143. #################################################################### 
  144. # Comment out VMs you do NOT want to create then run the entire script 
  145. # To comment out a VM creation, just add a '#" at the start of the line.  
  146. #        Removing the comment line means you want to create that VM.  
  147. #        BE creful!  If you make a mistake, stop the script. Kill any VMs created, then remove the 
  148. #        storage for the VMs.  
  149. ####################################################################################################### 
  150.  
  151. #    Create the DC - NON-domained joined 
  152. # Create-VM -name "DC1"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $una -Verbose -IPAddr '10.0.0.10/24' -DNSSvr 10.0.0.10  -VMMemory 1gb 
  153.  
  154. #    Remaining VMs use the domain-join version of unattend.xml 
  155. # Create-VM -name "Srv1"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.30/24' -DNSSvr 10.0.0.10  -VMMemory 512mb 
  156. # Create-VM -name "Srv2"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.31/24' -DNSSvr 10.0.0.10  -VMMemory 512mb 
  157. # Create-VM -name "Sql1"  -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.20/24' -DNSSvr 10.0.0.10  -VMMemory 768mb 
  158. # Create-VM -name "Exch1" -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.21/24' -DNSSvr 10.0.0.10  -VMMemory 768mb 
  159.  
  160. #    DHCP 1,2 for advanced networking class 
  161. # Create-VM -name "DHCP1" -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.51/24' -DNSSvr 10.0.0.10 -VMMemory 512mb 
  162. # Create-VM -name "DHCP2" -VmPath $path -ReferenceVHD $ref -Network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.52/24' -DNSSvr 10.0.0.10 -VMMemory 512mb 
  163.  
  164. #    Create a second DC for reskit.org for advanced class 
  165. # Create-VM -name "DC2"  -vmPath $path -ReferenceVHD $ref -network "Internal" -UnattendXML $unadj -Verbose -IPAddr '10.0.0.11/24' -DNSSvr 10.0.0.10  -VMMemory 512mb 
  166.  
  167.  
  168. #  script is all done - just say nice things and quit. 
  169. $Finish = Get-Date 
  170. "Create-VM --- Finished at: $Finish" 
  171. "Elapsed Time :  $(($Finish-$Start).totalseconds) seconds" 
  172.   
Technorati Tags: ,,,

Sunday, 20 January 2013

Open-FunctionInISE

  1. Function Open-FunctioninISE {
  2. <#
  3. .SYNOPSIS
  4. Opens a function in ISE
  5. .DESCRIPTION
  6.     This enables you to specify the function to open. The definition
  7.     comes from (Get-Command <command>).definition.
  8.     You specify the name of the function to open, or select it
  9.     in the ISE
  10. .NOTES
  11.     File Name : Open-FunctionInIse.ps1
  12.     Author : Thomas Lee - tfl@psp.co.uk
  13.     Requires : PowerShell Version 3.0
  14.     Based on a technet script published at http://gallery.technet.microsoft.com/scriptcenter/Open-defined-functions-in-22788d0f 
  15. .LINK
  16.     This script posted to:
  17.         http://www.pshscripts.blogspot.com
  18. .PARAMETER Function
  19.     The name of a defined function to open in new PowerShell ISE tab.
  20. .EXAMPLE
  21.     C:\Psh> Open-FunctionInIse Open-FunctioninISE
  22.     Opens Open-FunctionInIse in a new PowerShell ISE tab
  23. .EXAMPLE
  24.     Select a function name in an open edit window, then hit
  25.     Ctrl+Shift+E (or use the Add-ons menu)
  26. #>
  27. # Define parameters
  28. [Cmdletbinding()]
  29. Param(
  30. [Parameter(Position=0)]
  31. [ValidateScript({ Get-Command -commandtype function -name $_ })]
  32. [String] $function
  33. )
  34. # Start of the function.
  35. Process{
  36. # Get the function name (i.e. the selected text) and ensure it's not empty
  37. $fn = $psise.currentfile.Editor.selectedText
  38. # if nothing selected, see if we got called with it
  39. If (!$fn -or ($fn.length -LE 0)) {
  40. if ($function -and ($function.length -GT 0)){
  41. $fn = $function}
  42. Else {
  43. $fn = Read-Host -Prompt "Enter function name to view"
  44. }
  45. }
  46. If (!$Fn) {'No function to edit';return}
  47. # Get the definition, if there is one
  48. $definition = (Get-Command -commandtype function -name $fn).definition
  49. If (!$definition -or ($Definition.Length -le 0)) {return "Function [$fn] not found"}
  50. # Create What to see
  51. $FunctionHeader = "Function $fn {`n"
  52. $comments = "`# Description : $($definition.description)`n"
  53. $comments += "`# Module : $($definition.module)`n`n"
  54. $FunctionTrailer = "`n}"
  55. # Wrap it all up
  56. $definition = $functionHeader + $Comments + $Definition + $FunctionTrailer
  57. "function $fn {" + $definition + "}"
  58. # Add a tab, add text to the tab, set caret position to first character
  59. $tab = $Psise.CurrentPowerShellTab.Files.Add()
  60. $tab.Editor.text = $definition
  61. $tab.Editor.SetCaretPosition(1,1)
  62. # Sleep for a moment. Ran into issues without this.
  63. Start-Sleep -Milliseconds 200
  64. } # End process block
  65. } # End Function
  66. Set-ALias OFISE .\Open-FunctionInISE
  67. # Here we could test the function from the command line.
  68. # Function test123 {'testing 1-2-3'}
  69. # Open-FunctioninISE test123
  70. # I assume you'll just use this function so I've left the following
  71. # Code in place to add this as a menu item
  72. # Here add to the ISE as long as it's not there already!
  73. $x = ($psise.CurrentPowerShellTab.AddOnsMenu.Submenus).displayname
  74. if (! ($x -contains "_Edit Function in ISE")) {
  75. $Psise.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("_Edit Function in ISE", {Open-FunctioninISE},
  76. "Ctrl+Shift+E") | Out-Null
  77. }
  78. Else {
  79. 'Function already added in ISE'
  80. }

Tuesday, 15 January 2013

Create-ReferenceVHDX.ps1

  1. # Create-ReferenceVHDX.ps1
  2. # Script that will create a reference VHDX for later VM Creation
  3. # Version 1.0.0 - 14 Jan 2013
  4. # Define a function to create a reference VHDX.
  5. Function Create-ReferenceVHDX {
  6. [Cmdletbinding()]
  7. Param (
  8. # ISO of OS
  9. [string] $Iso = 'C:\downloads\9200.16384.120725-1247_x64frev_Server_Datacenter_VL_HRM_SSS_X64FREV_EN-US_DVD.iso',
  10. # Path to reference VHD
  11. [string] $RefVHDXPath = "C:\vhd\Ref2012.vhdx"
  12. )
  13. # Get start time
  14. $StartTime = Get-Date
  15. Write-Verbose "Beginning at $StartTime"
  16. #--------------------------------------------------+
  17. # Mount an ISO and check out available OS versions!
  18. #--------------------------------------------------+
  19. # Import the DISM module
  20. Write-Verbose 'Loading DISM module' -Verbose:$false
  21. Import-Module -Name DISM -Verbose:$False
  22. # Mount the OS ISO image onto the local machine
  23. Write-Verbose "Mounting ISO image [$iso]"
  24. Mount-DiskImage -ImagePath $iso
  25. # Get the Volume the Image is mounted to
  26. Write-Verbose 'Getting disk image of the ISO'
  27. $ISOImage = Get-DiskImage -ImagePath $ISO | Get-Volume
  28. Write-Verbose "Got disk image [$($ISOImage.DriveLetter)]"
  29. # And get the drive Letter of the dirve where the image is mounted
  30. # add the drive letter separator (:)
  31. $ISODrive = [string]$ISOImage.DriveLetter+":"
  32. Write-Verbose "OS ISO mounted on drive letter [$ISODrive]"
  33. # Next we will get the installation versions from the install.wim.
  34. # $Indexlist is the index of WIMs on the DVD - display the versions
  35. # available in the DVD and let user select the one to serve as the base
  36. # image - probably DataCentre Full Install
  37. $IndexList = Get-WindowsImage -ImagePath $ISODrive\sources\install.wim
  38. Write-Verbose 'Got Index list - displaying it now!'
  39. # Display the list and return the index
  40. $item = $IndexList | Out-GridView -OutputMode Single
  41. $index = $item.ImageIndex
  42. Write-Verbose "Selected image index [$index]"
  43. #---------------------------------+
  44. # Create a Reference Image !
  45. #---------------------------------+
  46. # Create the VHDX for the reference image
  47. $VMDisk01 = New-VHD –Path $RefVHDXPath -SizeBytes 15GB
  48. Write-Verbose "Created VHDX File [$($vmdisk01.path)]"
  49. # Get the disk number
  50. Mount-DiskImage -ImagePath $RefVHDXPath
  51. $VHDDisk = Get-DiskImage -ImagePath $RefVHDXPath | Get-Disk
  52. $VHDDiskNumber = [string]$VHDDisk.Number
  53. Write-Verbose "IReference image is on disk number [$VhddiskNumber]"
  54. # Create a New Partition
  55. Initialize-Disk -Number $VHDDiskNumber -PartitionStyle MBR
  56. $VHDDrive = New-Partition -DiskNumber $VHDDiskNumber -UseMaximumSize -AssignDriveLetter -IsActive | Format-Volume -Confirm:$false
  57. $VHDVolume = [string]$VHDDrive.DriveLetter+":"
  58. Write-Verbose "VHD drive [$vhddrive], Vhd volume [$vhdvolume]"
  59. # Execute DISM to apply image to base disk
  60. Write-Verbose 'Using DISM to apply image to the volume'
  61. Write-Verbose 'This will take some time'
  62. Dism.exe /apply-Image /ImageFile:$ISODrive\Sources\install.wim /index:$Index /ApplyDir:$VHDVolume\
  63. # Execute BCDBoot so volume will boot
  64. Write-Verbose 'Setting BCDBoot'
  65. BCDBoot.exe $VHDVolume\Windows /s $VHDVolume /f BIOS
  66. # Dismount the Images
  67. Write-Verbose "Dismounting ISO and new disk"
  68. Dismount-DiskImage -ImagePath $ISO
  69. Dismount-DiskImage -ImagePath $RefVHDXPath
  70. Write-Verbose "Created Reference Disk [$RefVHDXPath]"
  71. Get-ChildItem $RefVHDXPath
  72. $FinishTime = Get-Date
  73. $tt= $FinishTime - $StartTime
  74. Write-Verbose "Finishing at $FinishTime"
  75. Write-verbose "Creating base image took [$($tt.totalminutes)] minutes"
  76. } # End of Create-ReferenceVHDX
  77. ################################################################################################################
  78. # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
  79. # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
  80. # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
  81. # Path to Server 2012 DVD
  82. $iso = 'C:\Builds\9200.16384.120725-1247_x64frev_Server_Datacenter_VL_HRM_SSS_X64FREV_EN-US_DVD.iso'
  83. # PathTo the reference VDHX is to go
  84. $refvhdxpath = 'C:\V3\ref2012.vhdx'
  85. # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
  86. # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
  87. # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
  88. #################################################################################################################
  89. Create-ReferenceVHDX -iso $iso -RefVHDXPath $RefVHDXPath -Verbose

Wednesday, 3 October 2012

Get-GuiMode.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script gets the current GUI mode of a Windows 
  4.     Server 2012 system, including current display resolution. 
  5. .DESCRIPTION 
  6.     This script creates a custom object, then populates it 
  7.     with the current mode (Server Core, MinShell, Full Shell) 
  8.     and with the current resolution (resolution plus h/w). The 
  9.     display information object is then returned. 
  10. .NOTES 
  11.     File Name  : Get-GuiMode.ps1 
  12.     Author     : Thomas Lee - tfl@psp.co.uk 
  13.     Requires   : PowerShell Version 3.0  
  14.                  Windows Server 2012 
  15. .LINK 
  16.     This script posted to: 
  17.         http://www.pshscripts.blogspot.com 
  18. .EXAMPLE 
  19.     Psh>  ./Get-GuiMode 
  20.     ComputerName : S1 
  21.     ServerCore   : True 
  22.     FullServer   : False 
  23.     MinShell     : False 
  24.     Resolution   : 1024x768 
  25.     Height       : 768 
  26.     Width        : 1024 
  27.  
  28. #> 
  29.  
  30.  
  31. Function Get-GUIMode { 
  32.  
  33. # Create a new object to return 
  34. $guimode = new-object psobject 
  35.  
  36. # Add ComputerName to the object 
  37. $guimode |Add-Member -MemberType NoteProperty -Name ComputerName -Value $(hostname) 
  38.  
  39.  
  40. # now determine what's installed 
  41. $sgs  = (Get-WindowsFeature Server-Gui-Shell).Installed 
  42. $mif  = (Get-WindowsFeature Server-Gui-Mgmt-Infra).Installed 
  43.  
  44. If (!$sgs -and !$mif# True Server Core  
  45.   { 
  46.     $guimode |Add-Member -MemberType NoteProperty -Name ServerCore -Value $True 
  47.     $guimode |Add-Member -MemberType NoteProperty -Name FullServer -Value $False 
  48.     $guimode |Add-Member -MemberType NoteProperty -Name MinShell   -Value $False 
  49.   } 
  50. Elseif ($sgs -and !$mif) # MinShell 
  51.   { 
  52.     $guimode |Add-Member -MemberType NoteProperty -Name ServerCore -Value $False 
  53.     $guimode |Add-Member -MemberType NoteProperty -Name FullServer -Value $False 
  54.     $guimode |Add-Member -MemberType NoteProperty -Name MinShell   -Value $True 
  55.   } 
  56. Elseif ($sgs -and $mif
  57.   { 
  58.     $guimode |Add-Member -MemberType NoteProperty -Name ServerCore -Value $False 
  59.     $guimode |Add-Member -MemberType NoteProperty -Name FullServer -Value $True 
  60.     $guimode |Add-Member -MemberType NoteProperty -Name MinShell   -Value $False 
  61.   } 
  62.  
  63. # now resolution 
  64. If ($rx=get-command Get-DisplayResolution) { 
  65.   $res  = (Get-DisplayResolution)[0] 
  66.   $reslen = $res.length 
  67.   $r = [string]"" 
  68.   for ($i = 0; $i -lt $reslen; $i++) 
  69.    {  
  70.      If ($res.substring($i,1) -ne "") { $r += $res.substring($i,1) } 
  71.    } 
  72.  
  73.     
  74.   $guimode |Add-Member -MemberType NoteProperty -Name Resolution -Value $r 
  75.  
  76.   $h = $r.split("x")[1]  # height 
  77.   $w = $r.split("x")[0]  #  
  78.    
  79.   $guimode |Add-Member -MemberType NoteProperty -Name Height -Value $h 
  80.   $guimode |Add-Member -MemberType NoteProperty -Name Width  -Value $w 
  81.  
  82. # Ok - squirt out what we have! 
  83. $guimode 
  84.  
  85. # Here Test it out 
  86. Get-GUiMode 

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, 7 August 2012

Show-Formatting1.ps1

  1. <#
  2. .SYNOPSIS
  3. MSDN Sample Recoded in PowerShell demonstrating formatting
  4. .DESCRIPTION
  5. This sample recodes an MSDN Sample into PowerShell that
  6. shows some of the options of formatting using ToString() and
  7. various .NET formatting strings
  8. .NOTES
  9. File Name : Show-Formatting1.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. MSDN sample posted to:
  16. http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
  17. .EXAMPLE
  18. Psh> .\Show-Formatting1.ps1\
  19. 00123
  20. 1.20
  21. 01.20
  22. 01,20
  23. 0.6
  24. 1,234,567,890
  25. 1.234.567.890
  26. 1,234,567,890.1
  27. 1,234.57
  28. #>
  29. ## Start script
  30. [double] $value = 123;
  31. $value.ToString("00000")
  32. # Displays 00123
  33. $value = 1.2;
  34. $value.ToString("0.00", [System.Globalization.CultureInfo]::InvariantCulture)
  35. # Displays 1.20
  36. $value.ToString("00.00",[System.Globalization.CultureInfo]::InvariantCulture)
  37. # Displays 01.20
  38. $value.ToString("00.00",
  39. [System.Globalization.CultureInfo]::CreateSpecificCulture("da-DK"))
  40. # Displays 01,20
  41. $value = .56
  42. $value.ToString("0.0", [System.Globalization.CultureInfo]::InvariantCulture)
  43. # Displays 0.6
  44. $value = 1234567890
  45. $value.ToString("0,0", [System.Globalization.CultureInfo]::InvariantCulture)
  46. # Displays 1,234,567,890
  47. $value.ToString("0,0",
  48. [System.Globalization.CultureInfo]::CreateSpecificCulture("el-GR"))
  49. # Displays 1.234.567.890
  50. $value = 1234567890.123456;
  51. $value.ToString("0,0.0", [System.Globalization.CultureInfo]::InvariantCulture)
  52. # Displays 1,234,567,890.1
  53. $value = 1234.567890;
  54. $value.ToString("0,0.00", [System.Globalization.CultureInfo]::InvariantCulture)
  55. # Displays 1,234.57