- <#
- .SYNOPSIS
- This script displays all the WMI namespaces within a Windows system
- .DESCRIPTION
- This script uses Get-WMIObject to retrieve the names of all the namespaces
- within a system.
- .NOTES
- File Name : Get-WMINameSpace.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://pshscripts.blogspot.com/2010/10/get-wminamespaceps1.html
- .EXAMPLE
- PSH [C:\foo]: .\Get-WMINameSpace.ps1
- 37 Namespaces on: Cookham8
- Namespace
- ---------
- ROOT
- ROOT\aspnet
- ROOT\CIMV2
- ROOT\CIMV2\Security
- ROOT\CIMV2\Security\MicrosoftTpm
- ... {Remainder of list snipped to save space on this page}
- #>
- # Set computer name
- $comp = "."
- # Get the name spaces on the local computer, and the local computer name
- $Namespace = get-wmiobject __namespace -namespace 'root' -list -recurse -computer $comp
- $hostname = hostname
- # Display number of and names of the namespaces
- "{0} Namespaces on: {1}" -f $namespace.count, $hostname
- $NameSpace| sort __namespace | Format-Table @{Expression = "__Namespace"; Label = "Namespace"}
This blog contains PowerShell scripts, more PowerShell scripts and still more PowerShell scripts. Occasionally you may see some organisational posts.
Thursday, 7 October 2010
Get-WMINameSpace.ps1
Labels:
namespace,
powershell,
PowerShell scripts,
PowerShell V2,
wmi
Wednesday, 6 October 2010
Get-LoopBack.ps1
- <#
- .SYNOPSIS
- This script checks whether a parameter is a Loopback Address
- .DESCRIPTION
- This script checks to see if the passsed string is an IPV4
- or an IPv6 loopback address and if so, displays details.
- .NOTES
- File Name : Get-LoopBack.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/system.net.ipaddress.isloopback.aspx
- .EXAMPLE
- PSH [C:\foo]: .\Get-LoopBack.ps1
- Your input address: \127.0.0.1\ is an IPv4 loopback address whose internal format is: 127.0.0.1.
- .EXAMPLE
- PSH [C:\foo]: .\Get-LoopBack.ps1 ::1
- Your input address: \::1\ is an IPv6 loopback address whose internal format is: ::1.
- .EXAMPLE
- PSH [C:\foo]: .\Get-LoopBack.ps1 131.107.2.200
- Your input address: \131.107.2.200\ is not a loopback address.
- .PARAM
- $IPAddress - Address to look up to see if it's Loopback
- #>
- param (
- [String] $IpAddress = "127.0.0.1"
- )
- # Setup Default answer!
- $loopBack=" is not a loopback address.";
- # Perform syntax check by parsing the address string entered by the user.
- $Address = [System.Net.IPAddress]::Parse($IpAddress);
- # Perform semantic check by verifying that the address is a valid IPv4
- # or IPv6 loopback address.
- if([System.Net.IPAddress]::IsLoopback($Address) -and ($address.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6) ) {
- $loopBack = " is an IPv6 loopback address " +
- "whose internal format is: " + $Address.ToString() + ".";
- }
Labels:
powershell,
PowerShell scripts,
system.net.ipaddress
Tuesday, 5 October 2010
Get-HostByName.ps1
- <#
- .SYNOPSIS
- This script gets and displays basic DNS Information about a host.
- .DESCRIPTION
- This script just gets and displays host details returnd by GetHostByName.
- .NOTES
- File Name : Get-ByName.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/system.net.dns.aspx
- .EXAMPLE
- PSH [C:\foo]: .\Get-HostByName.ps1
- HostName : contoso.com
- Aliases : {www.contoso.com}
- AddressList : {207.46.197.32, 207.46.232.182}
- #>
- $hostInfo = [system.net.Dns]::GetHostByName("www.contoso.com");
- $hostinfo | fl * -force
Labels:
powershell,
PowerShell scripts,
System.Net.Dns
Monday, 4 October 2010
Remove-FtpFile.ps1
- <#
- .SYNOPSIS
- This script deletes a file from an FTP Server
- .DESCRIPTION
- This script is a rewrite of an MSDN Sample
- .NOTES
- File Name : Remove-FtpFile.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/system.net.ftpwebrequest.aspx
- .EXAMPLE
- PSH [C:\foo]: .\Remove-FtpFile.ps1
- Delete status: 250 DELE command successful.
- #>
- $ServerUri = New-Object System.Uri "ftp://www.reskit.net/powershell/foo.txt"
- # The serverUri parameter should use the ftp:// scheme.
- # It contains the name of the server file that is to be deleted.
- # Example: ftp://contoso.com/someFile.txt.
- if ($ServerUri.Scheme -ne [system.Uri]::UriSchemeFtp) {
- " Bad URI"; return
- }
- # Get the object used to communicate with the server.
- $request = [system.Net.FtpWebRequest]::Create($serverUri)
- $request.Method = [System.Net.WebRequestMethods+ftp]::Deletefile
- $Request.Credentials = New-Object System.Net.NetworkCredential "anonymous","tfl@psp.co.uk"
- $response = $request.GetResponse()
- "Delete status: {0}" -f $response.StatusDescription
- $response.Close();
Sunday, 3 October 2010
Copy-FileToFtp.ps1
- <#
- .SYNOPSIS
- This script Uploads a text file to an FTP Server using PowerShell.
- .DESCRIPTION
- This script first creates an FTP 'web' request to upload a file. Then the
- source file is read from disk and written up to the FTP Server. A response
- is then displayed. This is a rewrite of an MSDN Sample.
- .NOTES
- File Name : Copy-FileToFtp.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://pshscripts.blogspot.com/2010/10/copy-filetoftpps1.html
- MSDN sample posted tot:
- http://msdn.microsoft.com/en-us/library/ms229715.aspx
- .EXAMPLE
- PSH [C:\foo]: .Copy-FileToFtp.ps1
- Upload File Complete, status 226
- 226 Transfer complete.
- #>
- # Get the object used to communicate with the server.
- $Request = [System.Net.FtpWebRequest]::Create("ftp://www.reskit.net/powershell/Greetings.Txt")
- $Request.Method = $Request.Method = [System.Net.WebRequestMethods+ftp]::UploadFile
- # This example assumes the FTP site uses anonymous logon.
- $Request.Credentials = New-Object System.Net.NetworkCredential "anonymous","tfl@psp.co.uk"
- # Copy the contents of the file to the request stream.
- $FileContents = [System.IO.File]::ReadAllBytes("C:\foo\scriptlib.zip")
- $Request.ContentLength = $fileContents.Length
- $RequestStream = $request.GetRequestStream()
- $RequestStream.Write($FileContents, 0, $FileContents.Length)
- $RequestStream.Close()
- $Response = $Request.GetResponse()
- "Upload File Complete, status {0}" -f $Response.StatusDescription
- $Response.Close()
Monday, 27 September 2010
Show-HtmlCoding.ps1
- <#
- .SYNOPSIS
- This script encodes and decodes an HTML String
- .DESCRIPTION
- This script used
- .NOTES
- File Name : Show-HtmlCoding.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/ee388364.aspx
- .EXAMPLE
- PSH [C:\foo]: .\Show-HtmlCoding.ps1
- Original String: <this is a string123> & so is this one??
- Encoded String : <this is a string123> & so is this one??
- Decoded String : <this is a string123> & so is this one??
- Original string = Decoded string?: True
- #>
- # Create string to encode/decode
- $Str = "<this is a string123> & so is this one??"
- # Encode String
- $Encstr = [System.Net.WebUtility]::HtmlEncode($str)
- # Decode String
- $Decstr = [System.Net.WebUtility]::HtmlDecode($EncStr)
- # Display strings
- "Original String: {0}" -f $Str
- "Encoded String : {0}" -f $Encstr
- "Decoded String : {0}" -f $Decstr
- $eq = ($str -eq $Decstr)
- "Original string = Decoded string?: {0}" -f $eq
Sunday, 26 September 2010
Get-FTPDirectory.ps1
- <#
- .SYNOPSIS
- This script used FTP to get and display the root of an FTP site.
- .DESCRIPTION
- This script re-implements an MSDN sample.
- .NOTESW
- File Name : Get-FtpDirectory.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- htthttp://pshscripts.blogspot.com/2010/09/get-ftpdirectoryps1.html
- MSDN sample posted tot:
- http://msdn.microsoft.com/en-us/library/ms229716.aspx
- .EXAMPLE
- PSH [C:\foo]: .\Get-FtpDirectory.ps1
- drwxrwxrwx 1 user group 0 Dec 4 2005 pcpro
- drwxrwxrwx 1 user group 0 Sep 23 15:18 PowerShell
- ... {Listing truncated}
- Download Complete, status:
- 226-Maximum disk quota limited to 100000 Kbytes
- Used disk quota 78232 Kbytes, available 21767 Kbytes
- 226 Transfer complete.
- #>
- # Get the object used to communicate with the server.
- $Request = [System.Net.WebRequest]::Create("ftp://www.reskit.net")
- $Request.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
- # This example assumes the FTP site uses anonymous logon.
- # Username/password not real
- $Request.Credentials = New-Object System.Net.NetworkCredential "Anonymous",tfl@psp.co.uk
- $Response = $Request.GetResponse()
- $ResponseStream = $Response.GetResponseStream()
- # Read and display the text in the file
- $Reader = new-object System.Io.StreamReader $Responsestream
- [System.Console]::Writeline($Reader.ReadToEnd())
- # Display Status
- "Download Complete, status:"
- $response.StatusDescription
- # Close Reader and Response objects
- $Reader.Close()
- $Response.Close()
Labels:
powershell,
PowerShell scripts,
scripts,
System.Net.WebRequest
Get-FtpFile.ps1
- #
- .SYNOPSIS
- This script used FTP to get and display a text file.
- .DESCRIPTION
- This script re-implements an MSDN Sample
- .NOTESW
- File Name : Get-FtpFile.ps1
- Author : Thomas Lee - tfl@psp.co.uk
- Requires : PowerShell Version 2.0
- .LINK
- This script posted to:
- http://pshscripts.blogspot.com/2010/09/get-ftpfileps1.html
- MSDN sample posted to:
- http://msdn.microsoft.com/en-us/library/ms229711.aspx
- .EXAMPLE
- PSH [C:\foo]: .\Get-FtpFile.ps1'
- This is Hello.Txt from www.reskit.net
- Have a great day!
- Download Complete, status:
- 226-Maximum disk quota limited to 100000 Kbytes
- Used disk quota 78232 Kbytes, available 21767 Kbytes
- 226 Transfer complete.
- #>
- # Get the object used to communicate with the server.
- $Request = [System.Net.WebRequest]::Create("ftp://www.reskit.net/hello.txt");
- $Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
- # This example assumes the FTP site uses anonymous logon.
- # Username/password not real
- $Request.Credentials = New-Object System.Net.NetworkCredential "Anonymous","tfl@psp.co.uk"
- $ResponseStream = $Response.GetResponseStream()
- # Read and display the text in the file
- $Reader = new-object System.Io.StreamReader $ResponseStream
- [System.Console]::Writeline($Reader.ReadToEnd())
- # Display Status
- "Download Complete, status:"
- $response.StatusDescription
- # Close Reader and Response objects
- $Reader.Close()
- $Response.Close()
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."
Labels:
COM,
powershell,
PowerShell V2,
Schedule.Service
Monday, 20 September 2010
Get-VirtualMachine.ps1
- <#
- .SYNOPSIS
- This script gets the list of Virtual Machines on a Hyper-V Host
- .DESCRIPTION
- This script uses WMI to get the VMs defined on a Hyper-V host
- then displays them.
- .NOTES
- File Name : Get-VirtualMachine.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/cc136822%28VS.85%29.aspx
- .EXAMPLE
- PSH [c:\foo\: Get-VirtualMachine
- 5 Virtual Machines on: COOKHAM2
- PSMC-DC1
- PSMC-EXCH1
- PSMC-SQL
- PSMC-SRV1
- PSMC-SRV2
- #>
- # Get list of VMs from WMI
- $vmbase = get-wmiobject Msvm_ComputerSystem -namespace root\virtualization -ComputerName Cookham2
- # Get hosting computer System Name
- $HostName = $vmbase | ? {$_.Caption -eq "Hosting Computer System"} | select name
- # Print results
- "{0} Virtual Machines on: {1}" -f $($vmbase.count-1),$Hostname.name
- $vmbase | where {$_.Caption -ne "Hosting Computer System"} | sort elementname | ft elementname -HideTableHeaders
Subscribe to:
Posts (Atom)