- Function Open-FunctioninISE {
- <#
- .SYNOPSIS
- Opens a function in ISE
- .DESCRIPTION
- This enables you to specify the function to open. The definition
- comes from (Get-Command <command>).definition.
- You specify the name of the function to open, or select it
- in the ISE
- .NOTES
- File Name : Open-FunctionInIse.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 3.0
- Based on a technet script published at http://gallery.technet.microsoft.com/scriptcenter/Open-defined-functions-in-22788d0f
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- .PARAMETER Function
- The name of a defined function to open in new PowerShell ISE tab.
- .EXAMPLE
- C:\Psh> Open-FunctionInIse Open-FunctioninISE
- Opens Open-FunctionInIse in a new PowerShell ISE tab
- .EXAMPLE
- Select a function name in an open edit window, then hit
- Ctrl+Shift+E (or use the Add-ons menu)
- #>
- # Define parameters
- [Cmdletbinding()]
- Param(
- [Parameter(Position=0)]
- [ValidateScript({ Get-Command -commandtype function -name $_ })]
- [String] $function
- )
- # Start of the function.
- Process{
- # Get the function name (i.e. the selected text) and ensure it's not empty
- $fn = $psise.currentfile.Editor.selectedText
- # if nothing selected, see if we got called with it
- If (!$fn -or ($fn.length -LE 0)) {
- if ($function -and ($function.length -GT 0)){
- $fn = $function}
- Else {
- $fn = Read-Host -Prompt "Enter function name to view"
- }
- }
- If (!$Fn) {'No function to edit';return}
- # Get the definition, if there is one
- $definition = (Get-Command -commandtype function -name $fn).definition
- If (!$definition -or ($Definition.Length -le 0)) {return "Function [$fn] not found"}
- # Create What to see
- $FunctionHeader = "Function $fn {`n"
- $comments = "`# Description : $($definition.description)`n"
- $comments += "`# Module : $($definition.module)`n`n"
- $FunctionTrailer = "`n}"
- # Wrap it all up
- $definition = $functionHeader + $Comments + $Definition + $FunctionTrailer
- "function $fn {" + $definition + "}"
- # Add a tab, add text to the tab, set caret position to first character
- $tab = $Psise.CurrentPowerShellTab.Files.Add()
- $tab.Editor.text = $definition
- $tab.Editor.SetCaretPosition(1,1)
- # Sleep for a moment. Ran into issues without this.
- Start-Sleep -Milliseconds 200
- } # End process block
- } # End Function
- Set-ALias OFISE .\Open-FunctionInISE
- # Here we could test the function from the command line.
- # Function test123 {'testing 1-2-3'}
- # Open-FunctioninISE test123
- # I assume you'll just use this function so I've left the following
- # Code in place to add this as a menu item
- # Here add to the ISE as long as it's not there already!
- $x = ($psise.CurrentPowerShellTab.AddOnsMenu.Submenus).displayname
- if (! ($x -contains "_Edit Function in ISE")) {
- $Psise.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("_Edit Function in ISE", {Open-FunctioninISE},
- "Ctrl+Shift+E") | Out-Null
- }
- Else {
- 'Function already added in ISE'
- }
This blog contains PowerShell scripts, more PowerShell scripts and still more PowerShell scripts. Occasionally you may see some organisational posts.
Sunday, 20 January 2013
Open-FunctionInISE
Labels:
powershell,
Powershell ISE,
PowerShell v3
Tuesday, 15 January 2013
Create-ReferenceVHDX.ps1
- # Create-ReferenceVHDX.ps1
- # Script that will create a reference VHDX for later VM Creation
- # Version 1.0.0 - 14 Jan 2013
- # Define a function to create a reference VHDX.
- Function Create-ReferenceVHDX {
- [Cmdletbinding()]
- Param (
- # ISO of OS
- [string] $Iso = 'C:\downloads\9200.16384.120725-1247_x64frev_Server_Datacenter_VL_HRM_SSS_X64FREV_EN-US_DVD.iso',
- # Path to reference VHD
- [string] $RefVHDXPath = "C:\vhd\Ref2012.vhdx"
- )
- # Get start time
- $StartTime = Get-Date
- Write-Verbose "Beginning at $StartTime"
- #--------------------------------------------------+
- # Mount an ISO and check out available OS versions!
- #--------------------------------------------------+
- # Import the DISM module
- Write-Verbose 'Loading DISM module' -Verbose:$false
- Import-Module -Name DISM -Verbose:$False
- # Mount the OS ISO image onto the local machine
- Write-Verbose "Mounting ISO image [$iso]"
- Mount-DiskImage -ImagePath $iso
- # Get the Volume the Image is mounted to
- Write-Verbose 'Getting disk image of the ISO'
- $ISOImage = Get-DiskImage -ImagePath $ISO | Get-Volume
- Write-Verbose "Got disk image [$($ISOImage.DriveLetter)]"
- # And get the drive Letter of the dirve where the image is mounted
- # add the drive letter separator (:)
- $ISODrive = [string]$ISOImage.DriveLetter+":"
- Write-Verbose "OS ISO mounted on drive letter [$ISODrive]"
- # Next we will get the installation versions from the install.wim.
- # $Indexlist is the index of WIMs on the DVD - display the versions
- # available in the DVD and let user select the one to serve as the base
- # image - probably DataCentre Full Install
- $IndexList = Get-WindowsImage -ImagePath $ISODrive\sources\install.wim
- Write-Verbose 'Got Index list - displaying it now!'
- # Display the list and return the index
- $item = $IndexList | Out-GridView -OutputMode Single
- $index = $item.ImageIndex
- Write-Verbose "Selected image index [$index]"
- #---------------------------------+
- # Create a Reference Image !
- #---------------------------------+
- # Create the VHDX for the reference image
- $VMDisk01 = New-VHD –Path $RefVHDXPath -SizeBytes 15GB
- Write-Verbose "Created VHDX File [$($vmdisk01.path)]"
- # Get the disk number
- Mount-DiskImage -ImagePath $RefVHDXPath
- $VHDDisk = Get-DiskImage -ImagePath $RefVHDXPath | Get-Disk
- $VHDDiskNumber = [string]$VHDDisk.Number
- Write-Verbose "IReference image is on disk number [$VhddiskNumber]"
- # Create a New Partition
- Initialize-Disk -Number $VHDDiskNumber -PartitionStyle MBR
- $VHDDrive = New-Partition -DiskNumber $VHDDiskNumber -UseMaximumSize -AssignDriveLetter -IsActive | Format-Volume -Confirm:$false
- $VHDVolume = [string]$VHDDrive.DriveLetter+":"
- Write-Verbose "VHD drive [$vhddrive], Vhd volume [$vhdvolume]"
- # Execute DISM to apply image to base disk
- Write-Verbose 'Using DISM to apply image to the volume'
- Write-Verbose 'This will take some time'
- Dism.exe /apply-Image /ImageFile:$ISODrive\Sources\install.wim /index:$Index /ApplyDir:$VHDVolume\
- # Execute BCDBoot so volume will boot
- Write-Verbose 'Setting BCDBoot'
- BCDBoot.exe $VHDVolume\Windows /s $VHDVolume /f BIOS
- # Dismount the Images
- Write-Verbose "Dismounting ISO and new disk"
- Dismount-DiskImage -ImagePath $ISO
- Dismount-DiskImage -ImagePath $RefVHDXPath
- Write-Verbose "Created Reference Disk [$RefVHDXPath]"
- Get-ChildItem $RefVHDXPath
- $FinishTime = Get-Date
- $tt= $FinishTime - $StartTime
- Write-Verbose "Finishing at $FinishTime"
- Write-verbose "Creating base image took [$($tt.totalminutes)] minutes"
- } # End of Create-ReferenceVHDX
- ################################################################################################################
- # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
- # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
- # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
- # Path to Server 2012 DVD
- $iso = 'C:\Builds\9200.16384.120725-1247_x64frev_Server_Datacenter_VL_HRM_SSS_X64FREV_EN-US_DVD.iso'
- # PathTo the reference VDHX is to go
- $refvhdxpath = 'C:\V3\ref2012.vhdx'
- # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
- # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
- # CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS ===== CHECK THESE PATHS #
- #################################################################################################################
- Create-ReferenceVHDX -iso $iso -RefVHDXPath $RefVHDXPath -Verbose
Labels:
deployment scripts,
powershell,
PowerShell v3
Saturday, 22 December 2012
Show-Exceptions.ps1
- <#
- .SYNOPSIS
- This script gets all the exceptions you can trap by PowerShell
- .DESCRIPTION
- This script looks at all the loaded assemblies to get all
- the exceptions you can trap/catch using PowerShell. The
- display only covers those parts of the .NET framework are loaded.
- .NOTES
- File Name : Show-Exceptions.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- .EXAMPLE
- Psh> .\Show-Exceptions.ps1 -Summary
- In 69 loaded assemblies, you have 418 exceptions:
- .EXAMPLE
- Psh> .\Show-Exceptions.ps1
- In 69 loaded assemblies, you have 418 exceptions:
- Name FullName
- ---- --------
- _Exception System.Runtime.InteropServices._Exception
- AbandonedMutexException System.Threading.AbandonedMutexException
- AccessViolationException System.AccessViolationException
- ...
- #>
- [CMDLETBINDING()]
- Param (
- [switch] $summary
- )
- # Get all the exceptions
- $assemblies = [System.AppDomain]::CurrentDomain.GetAssemblies()
- $exceptions = $Assemblies | ForEach {
- $_.GetTypes() | where { $_.FullName -Match "System$filter.*Exception$" } }
- # Now display the numbers checking for summary flag
- "In {0} loaded assemblies, you have {1} exceptions:" -f $assemblies.count, $exceptions.count
- If (-not $summary) {
- $Exceptions | sort name | format-table name, fullname
- }
Technorati Tags: Exceptions
Sunday, 9 December 2012
Get-LyncAutoLogonStatus.ps1
- <#
- .SYNOPSIS
- This script reports on whether Lync should
- automatically start on a machine when a user
- logs in.
- .DESCRIPTION
- This script looks in the registry at a chosen machine
- to determine if the Lync client should automatically
- attempt to login when a user logs onto that system.
- .NOTES
- File Name : Get-LyncAutoLogonStatus
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- Lync 2010 or later
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- .EXAMPLE
- Psh> .\Get-LyncAutoLogonStatus
- Automatically start Lync when I log on to Windows: True
- #>
- [Cmdletbinding()]
- Param (
- [string] $computer = "Cookham8.Cookham.net")
- # Get the relevant registry key
- $registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("CurrentUser", $computer)
- $key = $registry.OpenSubKey("SOFTWARE\Microsoft\Communicator", $True)
- # now write to host the details
- Write-Host "Automatically start Lync when I log on to Windows:",`
- ([boolean] $key.GetValue("AutoRunWhenLogonToWindows",$null))
Technorati Tags: Lync,AutoLogon Status
Sunday, 2 December 2012
Set-AdminLogon.ps1
- <#
- .SYNOPSIS
- This script defines a function that sets autologon
- .DESCRIPTION
- Autologon enables the system to logon after a reboot without
- you needing to enter credentials. This is an ideal scenario
- for lab or training room systems. This script defines
- a function that sets a userid/password and autologon.
- .NOTES
- File Name : Set-AdminLogon
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- .EXAMPLE
- Psh> New-AdminLogon -user cookham\tfl -password 'JerryGarciaR0cks!'
- Auto logon created for [Cookham\tfl] with password: [JerryGarciaR0cks]
- #>
- Function New-AdminLogon {
- [cmdletbinding()]
- Param(
- [string] $User = $(Throw 'No user id specified'),
- [string] $Password = $(Throw 'No password specified')
- )
- # Define registry path for autologon
- $RegPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
- # Set autologon
- Set-ItemProperty -Path $RegPath -Name AutoAdminLogon -Value 1
- # Set userid and password
- Set-ItemProperty -Path $RegPath -Name DefaultUserName -Value $User
- Set-ItemProperty -Path $regPath -Name DefaultPassword -Value $Password
- # Say nice things and exit!
- Write-Host ("Auto logon [{0}] set to password: [{1}]" -f $user, $password)
- }
- Set-AdminLogon -User 'Cookham\tfl' -Password 'JerryGarciaR0cks'
Technorati Tags: secuirty,admin logon
Remove-AdminLogon.ps1
- <#
- .SYNOPSIS
- This script defines a function that removes autologon
- .DESCRIPTION
- Autologon enables the system to logon after a reboot without
- you needing to enter credentials. This is an ideal scenario
- for lab or training room systems. This script defines
- a function that removes the autologon registry keys
- .NOTES
- File Name : Remove-AdminLogon
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- .EXAMPLE
- Psh> Remove-AdminLogon
- Auto logon settings removed
- #>
- Function Remove-AdminLogon {
- [Cmdletbinding()]
- Param()
- # Define registry path for autologon
- $RegPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
- # Remove autologon property
- Remove-ItemProperty -Path $RegPath -Name AutoAdminLogon
- # Remove userid and password
- Remove-ItemProperty -Path $RegPath -Name DefaultUserName
- Remove-ItemProperty -Path $RegPath -Name DefaultPassword
- # Say nice things and exit!
- Write-Host ("Auto logon removed")
- }
- Remove-AdminLogon
Technorati Tags: security,admin logon
New-AutoAdminLogon.ps1
- <#
- .SYNOPSIS
- This script defines a function that sets autologon
- .DESCRIPTION
- Autologon enables the system to logon after a reboot without
- you needing to enter credentials. This is an ideal scenario
- for lab or training room systems. This script defines
- a function that sets a userid/password and autologon. It does NOT
- check to see if the value entries already exist.
- .NOTES
- File Name : Set-AutoAdminLogon
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- .EXAMPLE
- Psh> Set-AutoAdminLogon -user cookham\tfl -password 'JerryGarciaR0cks!'
- Auto logon set for [Cookham\tfl] with password: [JerryGarciaR0cks]
- #>
- Function Set-AdminLogon {
- [cmdletbinding()]
- Param(
- [string] $User = $(Throw 'No user id specified'),
- [string] $Password = $(Throw 'No password specified')
- )
- # Define registry path for autologon
- $RegPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
- # Set autologon
- New-ItemProperty -Path $RegPath -Name AutoAdminLogon -Value 1 -EA 0
- # Set userid and password
- New-ItemProperty -Path $RegPath -Name DefaultUserName -Value $User -EA 0
- New-ItemProperty -Path $regPath -Name DefaultPassword -Value $Password -EA 0
- # Say nice things and exit!
- Write-Host ("Auto logon set for [{0}] with password: [{1}]" -f $user, $password)
- }
- Set-AdminLogon -User 'Cookham\tfl' -Password 'JerryGarciaR0cks'
Technorati Tags: secuirty,admin logon
Friday, 23 November 2012
Convert-PptxToPDF.ps1
- <#
- .SYNOPSIS
- This function converts a PPTx file into a PDF file
- .DESCRIPTION
- The Convert-PptxToPDF function first creates an
- instance of PowerPoint, opens the $ifile and saves
- this to $ofile as a PDF file.
- .NOTES
- File Name : Convert-PptxToPDF
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 3.0, Office 2010
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- .EXAMPLE
- There is nothing to see, except a set of new PDF Files in the output folder
- #>
- Function Convert-PptxToPDF {
- [CmdletBinding()]
- Param(
- $IFile,
- $OFile
- )
- # add key assemblies
- Add-type -AssemblyName office -ErrorAction SilentlyContinue
- Add-Type -AssemblyName microsoft.office.interop.powerpoint -ErrorAction SilentlyContinue
- # Open PowerPoint
- $ppt = new-object -com powerpoint.application
- $ppt.visible = [Microsoft.Office.Core.MsoTriState]::msoFalse
- # Open the $Ifile presentation
- $pres = $ppt.Presentations.Open($ifile)
- # Now save it away as PDF
- $opt= [Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType]::ppSaveAsPDF
- $pres.SaveAs($ofile,$opt)
- # and Tidy-up
- $pres.Close()
- $ppt.Quit()
- $ppt=$null
- }
- # Test it
- $ipath = "E:\SkyDrive\PowerShell V3 Geek Week\"
- Foreach ($ifile in $(ls $ipath -Filter "*.pptx")) {
- # Build name of output file
- $pathname = split-path $ifile
- $filename = split-path $ifile -leaf
- $file = $filename.split(".")[0]
- $ofile = $pathname + $file + ".pdf"
- # Convert _this_ file to PDF
- Convert-PptxToPDF -ifile $ifile -OFile $ofile
- }
Labels:
PDF,
PowerPoint,
PowerPoint.Application
Wednesday, 3 October 2012
Get-GuiMode.ps1
- <#
- .SYNOPSIS
- This script gets the current GUI mode of a Windows
- Server 2012 system, including current display resolution.
- .DESCRIPTION
- This script creates a custom object, then populates it
- with the current mode (Server Core, MinShell, Full Shell)
- and with the current resolution (resolution plus h/w). The
- display information object is then returned.
- .NOTES
- File Name : Get-GuiMode.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 3.0
- Windows Server 2012
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- .EXAMPLE
- Psh> ./Get-GuiMode
- ComputerName : S1
- ServerCore : True
- FullServer : False
- MinShell : False
- Resolution : 1024x768
- Height : 768
- Width : 1024
- #>
- Function Get-GUIMode {
- # Create a new object to return
- $guimode = new-object psobject
- # Add ComputerName to the object
- $guimode |Add-Member -MemberType NoteProperty -Name ComputerName -Value $(hostname)
- # now determine what's installed
- $sgs = (Get-WindowsFeature Server-Gui-Shell).Installed
- $mif = (Get-WindowsFeature Server-Gui-Mgmt-Infra).Installed
- If (!$sgs -and !$mif) # True Server Core
- {
- $guimode |Add-Member -MemberType NoteProperty -Name ServerCore -Value $True
- $guimode |Add-Member -MemberType NoteProperty -Name FullServer -Value $False
- $guimode |Add-Member -MemberType NoteProperty -Name MinShell -Value $False
- }
- Elseif ($sgs -and !$mif) # MinShell
- {
- $guimode |Add-Member -MemberType NoteProperty -Name ServerCore -Value $False
- $guimode |Add-Member -MemberType NoteProperty -Name FullServer -Value $False
- $guimode |Add-Member -MemberType NoteProperty -Name MinShell -Value $True
- }
- Elseif ($sgs -and $mif)
- {
- $guimode |Add-Member -MemberType NoteProperty -Name ServerCore -Value $False
- $guimode |Add-Member -MemberType NoteProperty -Name FullServer -Value $True
- $guimode |Add-Member -MemberType NoteProperty -Name MinShell -Value $False
- }
- # now resolution
- If ($rx=get-command Get-DisplayResolution) {
- $res = (Get-DisplayResolution)[0]
- $reslen = $res.length
- $r = [string]""
- for ($i = 0; $i -lt $reslen; $i++)
- {
- If ($res.substring($i,1) -ne "") { $r += $res.substring($i,1) }
- }
- $guimode |Add-Member -MemberType NoteProperty -Name Resolution -Value $r
- $h = $r.split("x")[1] # height
- $w = $r.split("x")[0] #
- $guimode |Add-Member -MemberType NoteProperty -Name Height -Value $h
- $guimode |Add-Member -MemberType NoteProperty -Name Width -Value $w
- }
- # Ok - squirt out what we have!
- $guimode
- }
- # Here Test it out
- Get-GUiMode
Labels:
powershell,
PowerShell v3,
Server2012,
ServerCore
Set-PowerShellAsShell
- <#
- .Synopsis
- Creates a function to set PowerShell as GUI in Server 2012
- .DESCRIPTION
- The function in this script sets PowerShell as the
- default shell in Server 2012. When the server is rebooted,
- it runs PowerShell.exe by default. When PowerShell starts, it
- displays the $PSVersionTable variable.
- .NOTES
- File Name : Set-PowerShellAsGui.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : Server 2012
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- .EXAMPLE
- Left as an exercise to the reader
- #>
- Function Set-PowerShellAsShell {
- [CmdletBinding()]
- Param (
- [switch] $Reboot = $false
- )
- # Create Registry Path variable
- $RegPath = "Microsoft.PowerShell.Core\Registry::"
- $RegPath += "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\"
- $RegPath += "Windows NT\CurrentVersion\winlogon"
- # Create splatted parameter hash table
- $parm = @{Path = $regpath} # key
- $parm += @{Name = 'Shell'} # value name
- $parm += @{Value = 'PowerShell.exe –NoExit
-Command "$psversiontable"'} # value’s value - # Set Registry value entry
- Set-ItemProperty @parm
- # And restart to see PowerShell
- if ($Reboot) {Restart-Computer -confirm}
- }
Labels:
powershell,
PowerShell scripts,
PowerShell V2,
PowerShell v3,
Server,
Server2012,
ServerCore
Subscribe to:
Posts (Atom)