- <#
- .SYNOPSIS
- This script opens a word document using PowerShell
- .DESCRIPTION
- This script re-implments a simple MSDN script to open
- a word document using VBA. IT Pros using PowerShell
- might also make use of to create rich documents as
- output from a script.
- .NOTES
- File Name : Open-WordDocument.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- MSDN sample posted to:
- http://msdn.microsoft.com/en-us/library/bb148369%28office.12%29.aspx
- .EXAMPLE
- Running this sample opens the file c:\foo\doc1.docx in Word. The
- COM object referring to the document is returned for later use.
- #>
- # Create Word Object
- $wrd = new-object -com word.application
- # Make Word Visible
- $wrd.visible = $true
- # Open a document
- $doc = $wrd.documents.open("C:\foo\doc1.docx")
This blog contains PowerShell scripts, more PowerShell scripts and still more PowerShell scripts. Occasionally you may see some organisational posts.
Wednesday, 9 November 2011
Open-WordDocument.ps1
Friday, 24 September 2010
New-Task.ps1
- <#
- .SYNOPSIS
- This script creates a scheduled task object.
- .DESCRIPTION
- This script re-implements an MSDN sample using PowerShell
- .NOTES
- File Name : New-Task.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- MSDN sample posted tot:
- http://msdn.microsoft.com/en-us/library/aa383665%28VS.85%29.aspx
- .EXAMPLE
- PSH [C:\foo]: .\New-Task.ps1
- Time Now : 9/24/2010 12:43:47 PM
- Task startTime : 2010-09-24T12:44:17
- Task endTime : 2010-09-24T12:48:47
- Task definition created. About to submit the task...
- Name : Test TimeTrigger
- Path : Test TimeTrigger
- State : 3
- Enabled : True
- LastRunTime : 12/30/1899 12:00:00 AM
- LastTaskResult : 1
- NumberOfMissedRuns : 0
- NextRunTime : 9/24/2010 12:44:17 PM
- Definition : System.__ComObject
- Xml : <?xml version="1.0" encoding="UTF-16"?>
- <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
- <RegistrationInfo>
- <Author>Thomas Lee</Author>
- <Description>Start notepad at a certain time</Description>
- </RegistrationInfo>
- <Triggers>
- <TimeTrigger id="TimeTriggerId">
- <StartBoundary>2010-09-24T12:44:17</StartBoundary>
- <EndBoundary>2010-09-24T12:48:47</EndBoundary>
- <ExecutionTimeLimit>PT5M</ExecutionTimeLimit>
- <Enabled>true</Enabled>
- </TimeTrigger>
- </Triggers>
- <Settings>
- <IdleSettings>
- <Duration>PT10M</Duration>
- <WaitTimeout>PT1H</WaitTimeout>
- <StopOnIdleEnd>true</StopOnIdleEnd>
- <RestartOnIdle>false</RestartOnIdle>
- </IdleSettings>
- <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
- <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
- <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
- <AllowHardTerminate>true</AllowHardTerminate>
- <StartWhenAvailable>true</StartWhenAvailable>
- <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
- <AllowStartOnDemand>true</AllowStartOnDemand>
- <Enabled>true</Enabled>
- <Hidden>false</Hidden>
- <RunOnlyIfIdle>false</RunOnlyIfIdle>
- <WakeToRun>false</WakeToRun>
- <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
- <Priority>7</Priority>
- </Settings>
- <Actions Context="Author">
- <Exec>
- <Command>C:\Windows\System32\notepad.exe</Command>
- </Exec>
- </Actions>
- <Principals>
- <Principal id="Author">
- <UserId>COOKHAM\tfl</UserId>
- <LogonType>InteractiveToken</LogonType>
- </Principal>
- </Principals>
- </Task>
- Task submitted.
- #>
- # Helper Function
- function XMLTIME{
- Param ( $T)
- $csecond = $t.Second.ToString()
- $cminute = $t.minute.ToString()
- $chour = $t.hour.ToString()
- $cday = $t.day.ToString()
- $cmonth = $t.month.ToString()
- $cyear = $t.year.ToString()
- $date = $cyear + "-"
- if ($cmonth.Length -eq 1) { $date += "0" + $cmonth + "-"}
- else { $date += $cmonth + "-"}
- if ($cday.length -eq 1) { $date += "0" + $cday + "T"}
- else { $date += $cday + "T"}
- if ($chour.length -eq 1) { $date += "0" + $chour + ":"}
- else { $date += $chour + ":"}
- if ($cminute.length -eq 1){ $date += "0" + $cminute + ":"}
- else { $date += $cminute + ":"}
- if ($csecond.length -eq 1){ $date += "0" + $csecond}
- else { $date += $csecond}
- # return
- $date
- }
- ## Script starts here
- # A constant that specifies a time-based trigger.
- $TriggerTypeTime = 1
- # A constant that specifies an executable action.
- $ActionTypeExec = 0
- # Create and connect to the service
- $service = New-Object -com schedule.service
- $service.Connect()
- # Get a folder to create a task definition in.
- $rootFolder = $service.GetFolder("\")
- # The taskDefinition variable is the TaskDefinition object.
- # The flags parameter is 0 because it is not supported.
- $taskDefinition = $service.NewTask(0)
- # Define information about the task.
- # Set the registration info for the task by
- # creating the RegistrationInfo object.
- $regInfo = $taskDefinition.RegistrationInfo
- $regInfo.Description = "Start notepad at a certain time"
- $regInfo.Author = "Thomas Lee"
- # Set the principal for the task
- $principal = $taskDefinition.Principal
- # Set the logon type to interactive logon
- $principal.LogonType = 3
- # Set the task setting info for the Task Scheduler by
- # creating a TaskSettings object.
- $settings = $taskDefinition.Settings
- $settings.Enabled = $True
- $settings.StartWhenAvailable = $True
- $settings.Hidden = $False
- # Create a time-based trigger.
- $triggers = $taskDefinition.Triggers
- $trigger = $triggers.Create($TriggerTypeTime)
- # Trigger variables that define when the trigger is active.
- $time = ([system.datetime]::now).addseconds(30)
- $startTime = XmlTime($time)
- $time = ([system.datetime]::now).addminutes(5)
- $endTime = XmlTime($time)
- "Time Now : {0}" -f (Get-Date -display time)
- "Task startTime : {0}" -f $startTime
- "Task endTime : {0}" -f $endTime
- $trigger.StartBoundary = $startTime
- $trigger.EndBoundary = $endTime
- $trigger.ExecutionTimeLimit = "PT5M" #Five minutes
- $trigger.Id = "TimeTriggerId"
- $trigger.Enabled = $True
- # Create the action for the task to execute.
- # Add an action to the task to run notepad.exe.
- $Action = $taskDefinition.Actions.Create( $ActionTypeExec )
- $Action.Path = "C:\Windows\System32\notepad.exe"
- "Task definition created. About to submit the task..."
- # Register (create) the task.
- $rootFolder.RegisterTaskDefinition("Test TimeTrigger", $taskDefinition, 6,"" ,"" , 3)
- # all done!
- "Task submitted."
Thursday, 18 March 2010
Enable-ICMP.ps1
- <#
- .SYNOPSIS
- This script Enables ICMP on the Standard Firewall profile.
- .DESCRIPTION
- This script creates a Firewall object then configures it.
- .NOTES
- File Name : Enable-ICMP.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- MSDN Sample posted at:
- http://
- .EXAMPLE
- PSH [C:\foo]: . 'E:\PowerShellScriptLib\COM\HNetCfg.FwMgr\Enable-ICMP.ps1'
- AllowOutboundDestinationUnreachable : False
- AllowRedirect : False
- AllowInboundEchoRequest : False
- AllowOutboundTimeExceeded : False
- AllowOutboundParameterProblem : False
- AllowOutboundSourceQuench : False
- AllowInboundRouterRequest : False
- AllowInboundTimestampRequest : False
- AllowInboundMaskRequest : False
- AllowOutboundPacketTooBig : True
- After Script ran:
- AllowOutboundDestinationUnreachable : False
- AllowRedirect : False
- AllowInboundEchoRequest : True
- AllowOutboundTimeExceeded : False
- AllowOutboundParameterProblem : False
- AllowOutboundSourceQuench : False
- AllowInboundRouterRequest : False
- AllowInboundTimestampRequest : False
- AllowInboundMaskRequest : False
- AllowOutboundPacketTooBig : True
- #>
- ##
- # Start of script
- ##
- # Set strict mode
- Set-StrictMode -Version 2.0
- # Set Constants
- $NET_FW_PROFILE_DOMAIN = 0
- $NET_FW_PROFILE_STANDARD = 1
- # Create the firewall manager object.
- $fwMgr = New-Object -com HNetCfg.FwMgr
- # Get the current profile for the local firewall policy.
- $profile = $fwMgr.LocalPolicy.GetProfileByType($NET_FW_PROFILE_STANDARD)
- # Display current ICMP settings
- $Profile.IcmpSettings
- # Now set it to True
- $profile.IcmpSettings.AllowInboundEchoRequest = $True
- # Use this line if you want to disable the setting.
- #profile.IcmpSettings.AllowInboundEchoRequest = $FALSE
- # Display it again
- "After Script ran: "
- $Profile.IcmpSettings
- # End Script
Wednesday, 17 March 2010
Enable-FirewallPort2.ps1
- <#
- .SYNOPSIS
- This script creates a rule in the Windows Host Firewall.
- .DESCRIPTION
- This script creates a new firewall rule for
- port 80 over tcp (i.e. 80).
- .NOTES
- File Name : Enable-FirewallPort.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://pshscripts.blogspot.com/2010/03/enable-firewallport2ps1.html
- MSDN Sample posted at:
- http://msdn.microsoft.com/en-us/library/aa366423%28VS.85%29.aspx
- .EXAMPLE
- PSH [C:\foo]: .\Enable-FirewallPort.ps1
- Before Script Runs:
- Name IpVersion Protocol Port Scope RemoteAddresses Enabled
- ---- --------- -------- ---- ----- --------------- -------
- HTTPS 2 6 443 0 * True
- driver 2 6 8085 0 * True
- driver 2 6 8085 0 * True
- After Script Runs:
- Name IpVersion Protocol Port Scope RemoteAddresses Enabled
- ---- --------- -------- ---- ----- --------------- -------
- HTTP 2 6 80 0 * True
- HTTPS 2 6 443 0 * True
- driver 2 6 8085 0 * True
- driver 2 6 8085 0 * True
- #>
- ##
- # Start Script
- ##
- # Set Strict Mode
- Set-Strictmode -Version 2.0
- # Set Constants
- $NET_FW_IP_PROTOCOL_UDP = 17
- $NET_FW_IP_PROTOCOL_TCP = 6
- # Create the firewall manager object.
- $fwMgr = New-Object -COM HNetCfg.FwMgr
- # Get the current profile for the local firewall policy.
- $profile = $fwMgr.LocalPolicy.CurrentProfile
- # Display it
- "Before Script Runs:"
- $profile.GloballyOpenPorts | `
- ft name, ipversion, protocol, port, scope, remoteaddresses, enabled -auto
- # Now add Port 80
- $port = New-Object -COM HNetCfg.FWOpenPort
- $port.Name = "HTTP"
- $port.Protocol = $NET_FW_IP_PROTOCOL_TCP
- $port.Port = 80
- # If using RemoteAddresses, don't use Scope
- # "*" means Scope of Any. Other entries are ignored if this is specified.
- # "LocalSubnet" means Scope of Local Subnet. Can be used with other addresses as well.
- $port.RemoteAddresses = "*"
- # Use this line to scope the port to Local Subnet only
- #$port.RemoteAddresses = "LocalSubnet"
- #Use this line to scope the port to the specific IP 10.1.1.1, the specific subnet 12.5.0.0, and Local Subnet. Don't put spaces.
- #port.RemoteAddresses = "LocalSubnet,10.1.1.1/255.255.255.255,12.5.0.0/255.255.0.0"
- $port.Enabled = $TRUE
- #Use this line instead if you want to add the port, but disabled
- #port.Enabled = FALSE
- # Now add the port
- $profile.GloballyOpenPorts.Add($port)
- # Print Results
- " After Script Runs:"
- $profile = $fwMgr.LocalPolicy.CurrentProfile
- $profile.GloballyOpenPorts | `
- ft name, ipversion, protocol, port, scope, remoteaddresses, enabled -auto
- # End of script
Friday, 5 March 2010
Enable-FWPort.ps1
- <#
- .SYNOPSIS
- This script enables then disables the SMTP port on a local system
- .DESCRIPTION
- This script first creates a FW object, then creates a port. The
- script then addes that port to the firewall rules. The script
- finally removes the port. The script also prints before/after
- results.
- .NOTES
- File Name : Enable-FWPort.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://www.pshscripts.blogspot.com
- MSDN Sample posted at:
- http://msdn.microsoft.com/en-us/library/aa366425(VS.85).aspx
- #>
- ##
- # Start of Script
- ##
- # Define Constants
- $NET_FW_IP_PROTOCOL_UDP = 17
- $NET_FW_IP_PROTOCOL_TCP = 6
- $NET_FW_SCOPE_ALL = 0
- # Create FW objecct
- $fwMgr = new-object -com HNetCfg.FwMgr
- # Get current profile
- $profile = $fwMgr.LocalPolicy.CurrentProfile
- # Display ports open:
- $profile.GloballyOpenPorts | ft name,port,enabled -auto
- # Create Port object
- $port = New-Object -com HNetCfg.FWOpenPort
- $port.Name = "SMTP"
- $port.Port = 25
- $port.Protocol = $NET_FW_IP_PROTOCOL_TCP
- $port.Scope = $NET_FW_SCOPE_ALL
- # Enable the port
- $port.Enabled = $True
- $profile.GloballyOpenPorts.Add($port)
- # Display results
- $profile.GloballyOpenPorts | ft name,port,enabled -auto
- # now remove the port
- $profile.GloballyOpenPorts.remove($port.port,$NET_FW_IP_PROTOCOL_TCP)
- # Display results
- $profile.GloballyOpenPorts | ft name,port,enabled -auto
- # End of script
Saturday, 24 October 2009
Get-CARolesOfCaller.ps1
- <#
- .SYNOPSIS
- This script displays the CA roles of the caller
- .DESCRIPTION
- This script instantiates the CA COM object, gets
- the allowed roles, and displays them. This script
- also shows use of Bitwise And operations, typical
- when using output from API calls. Based on an earlier
- script by Vadims Podans.
- .NOTES
- File Name : Get-CARolesofCaller.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell V2
- .LINK
- This script posted to:
- http://pshscripts.blogspot.com/2009/10/get-carolesofcallerps1.html
- MSDN Sample posted at:
- http://msdn.microsoft.com/en-us/library/aa383243%28VS.85%29.aspx
- .EXAMPLE
- PSH [C:\foo]: .\Get-CARolesOfCaller.ps1'
- You have the following rights on this CA: Cookham11\Cookham-CookhamCA
- CA administrator
- CA officer
- CA auditor
- CA backup
- Enrollment access
- #>
- # Instantiate the COM object
- $CertAdmin = New-Object -com "CertificateAuthority.Admin.1"
- # Now get the roles assigned to me
- $CA = "Cookham11\Cookham-CookhamCA"
- $MyRoles = $CertAdmin.GetMyRoles([string] $CA)
- #Display Granular Rights
- "You have the following rights on this CA: {0}" -f $CA
- switch ($MyRoles){
- {$MyRoles -band 1} {" CA administrator"}
- {$MyRoles -band 2} {" CA officer"}
- {$MyRoles -band 4} {" CA auditor"}
- {$MyRoles -band 8} {" CA backup"}
- {$MyRoles -band 256} {" CA Read access"}
- {$MyRoles -band 512} {" Enrollment access"}
- default {" No CA Access"}
- }
Tuesday, 23 December 2008
Get-FileCount.ps1
- # Get-FileCount.ps1
- # Uses shell.application to get a count of files in a folder
- # Thomas Lee - tfl@psp.co.uk
- # First get shell object
- $Shell = new-object -com Shell.Application
- # Now get folder details and item counts for a folder
- $foldername = "D:\Foo"
- $folder = $shell.namespace($foldername)
- if (!$folder) {
- "Folder: {0} does not exist" -f $foldername
- return
- }
- # Now output the count of folders
- if ($folder) {
- $folderitems = $folder.items()
- $count = $folderitems.count
- $folderps1items = $folderitems | where {$_.type -eq "PS1 File"}
- $countps1items=$folderps1items.count
- "Folder `"{0}`" contains {1} files" -f $foldername, $count
- "Folder `"{0}`" contains {1} PS1 files" -f $foldername, $countps1items
- }
This script produces the following output:
PSH [D:\foo]: .\shell.application\Get-FileCount.PS1'
Folder "D:\Foo" contains 38 files
Folder "D:\Foo" contains 22 PS1 files
Saturday, 20 December 2008
Get-FirewallDetails.ps1
- # Get-FirewallDetails.ps1
- # Gets details of Windows Firewall (on Vista and Server 2008 or later)
- # Runs on the local machine
- # Thomas Lee - tfl@psp.co.uk
- # First create COM object for policy profile and get host name
- $profile = (new-object -com HNetCfg.FwMgr).LocalPolicy.CurrentProfile
- $Hostname=hostname
- # Is firewall enabled?
- if ($profile.FirewallEnabled) {
- "Firewall is enabled on system {0}" -f $Hostname
- }
- else {
- "Firewall is NOT enabled on system {0}" -f $Hostname
- }
- # Exceptions allowed?
- if ($profile.ExceptionsNotAllowed) {"Exceptions NOT allowed"}
- else {"Exceptions are allowed"}
- # Notifications?
- if ($profile.NotificationsDisabled) {"Notifications are disabled"}
- else {"Notifications are not disabled"}
- # Display determine global open ports
- $ports = $profile.GloballyOpenPorts
- if (!$ports -or $ports.count -eq 0) {
- "There are no global open ports"
- }
- else {
- "There are {0} open ports as follows:" -f $ports.count
- $ports
- }
- ""
- # Display ICMP settings
- "ICMP Settings:"
- $profile.IcmpSettings
- # Display authorised applications
- $apps = $profile.AuthorizedApplications
- #
- if (!$apps) {
- "There are no authorised applications"
- }
- else {
- "There are {0} global applications as follows:" -f $apps.count
- $apps
- }
- # Display authorised services
- $services = $profile.services
- #
- if (!$services) {
- "There are no authorised services"
- }
- else {
- "There are {0} authorised services as follows:" -f $services.count
- $services
- }
This script produces the following output:
PS C:\foo> .\Get-FirewallDetails.ps1
Firewall is enabled on system Cookham8
Exceptions are allowed
Notifications are disabled
There are no global open portsICMP Settings:
AllowOutboundDestinationUnreachable : False
AllowRedirect : False
AllowInboundEchoRequest : True
AllowOutboundTimeExceeded : False
AllowOutboundParameterProblem : False
AllowOutboundSourceQuench : False
AllowInboundRouterRequest : False
AllowInboundTimestampRequest : False
AllowInboundMaskRequest : False
AllowOutboundPacketTooBig : TrueThere are 4 global applications as follows:
Name : BitTorrent
ProcessImageFileName : C:\Program Files (x86)\BitTorrent\bittorrent.exe
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : TrueName : DNA
ProcessImageFileName : C:\Program Files (x86)\DNA\btdna.exe
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : TrueName : Microsoft Office OneNote
ProcessImageFileName : C:\Program Files (x86)\Microsoft Office\Office12\ONENOTE.EXE
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : TrueName : Microsoft Office Groove
ProcessImageFileName : C:\Program Files (x86)\Microsoft Office\Office12\GROOVE.EXE
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : TrueThere are 3 authorised services as follows:
Name : File and Printer Sharing
Type : 0
Customized : False
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : True
GloballyOpenPorts : System.__ComObjectName : Network Discovery
Type : 1
Customized : True
IpVersion : 2
Scope : 1
RemoteAddresses : LocalSubnet
Enabled : True
GloballyOpenPorts : System.__ComObjectName : Remote Desktop
Type : 2
Customized : False
IpVersion : 2
Scope : 0
RemoteAddresses : *
Enabled : False
GloballyOpenPorts : System.__ComObject