<# .SYNOPSIS Gets and displays the role a computer plays in a domain .DESCRIPTION This script uses WIN32_ComputerSystem to get the rold of a system then displays it. This is a re-write of an MSDN sample. .NOTES File Name : Get-DomainRole.ps1 Author : Thomas Lee - tfl@psp.co.uk Requires : PowerShell V2 .LINK PowerShell script posted to: http://pshscripts.blogspot.com/2008/11/get-domainroleps1.html MSDN sample at: http://pshscripts.blogspot.com/2008/11/get-domainroleps1.html .EXAMPLE PSH [C:\foo]: .\Get-DomainRole.PS1 Computer "COOKHAM8.cookham.net" is a: Member Server #> ## # Start of Script ## # Get Computer info $Computer = Get-WmiObject -Class Win32_ComputerSystem # Print Role: "Computer `"{0}.{1}`" is a: " -f $Computer.Name,$computer.domain switch ($computer.DomainRole) { 0 {"Standalone Workstation"} 1 {"Member Workstation"} 2 {"Standalone Server"} 3 {"Member Server"} 4 {"Backup Domain Controller"} 5 {"Primary Domain Controller"} } #End of script
This blog contains PowerShell scripts, more PowerShell scripts and still more PowerShell scripts. Occasionally you may see some organisational posts.
Monday, 24 November 2008
Get-DomainRole.ps1
Labels:
powershell,
PowerShell scripts,
win32_operatingsystem,
wmi
Sunday, 23 November 2008
Catch-Error.ps1
<# .SYNOPSIS Demonstrates try/catch/finally in V2 .DESCRIPTION Shows a simple example of the try/catch/finally syntax introduced into PowerShell V2 CTP3 . The script divides by zero which creates an exception. The PowerShell parser is smart enough to recognise any attempt to divide by "0" and therefore does not generate the run time error. .NOTES File Name : Show-TryCatchFinally.ps1 Author : Thomas Lee - tfl@psp.co.uk Requires : PowerShell V2 .LINK http://pshscripts.blogspot.com/2008/11/catch-errorps1.html #> ## # Start of script ## # Try something that fails $one=1 $zero=0 Try { $one/$zero } Catch{ 'Caught in a catch block' $Error[0] } Finally {'All done with trying and catching' }
Labels:
catch,
error handling,
finally,
PowerShell V2,
scripts,
try
Saturday, 22 November 2008
Get-DiskDriveToDiskPartition.ps1
<# .SYNOPSIS Shows details from WMI's Win32_DiskDriveToPartition class .DESCRIPTION This script shows details of disk drives on a system using several Win32_* classes .NOTES File Name : Get-DiskDrivetoDiskPartition.ps1 Author : Thomas Lee - tfl@psp.co.uk Requires : PowerShell V2 .LINK http://pshscripts.blogspot.com/2008/11/get-diskdrivetodiskpartitionps1.html .EXAMPLE PSH [C:\foo]: . 'E:\PowerShellScriptLib\WMI\Get-Win32DiskDriveToDiskPartition.ps1' Win32_DiskDriveToDiskPartition Antecedent : \\COOKHAM8\root\cimv2:Win32_DiskDrive.DeviceID="\\\\.\\PHYSICALDRIVE5" Dependent : \\COOKHAM8\root\cimv2:Win32_DiskPartition.DeviceID="Disk #5, Partition #0" Antecedent : \\COOKHAM8\root\cimv2:Win32_DiskDrive.DeviceID="\\\\.\\PHYSICALDRIVE0" Dependent : \\COOKHAM8\root\cimv2:Win32_DiskPartition.DeviceID="Disk #0, Partition #0" Antecedent : \\COOKHAM8\root\cimv2:Win32_DiskDrive.DeviceID="\\\\.\\PHYSICALDRIVE0" Dependent : \\COOKHAM8\root\cimv2:Win32_DiskPartition.DeviceID="Disk #0, Partition #1" Antecedent : \\COOKHAM8\root\cimv2:Win32_DiskDrive.DeviceID="\\\\.\\PHYSICALDRIVE0" Dependent : \\COOKHAM8\root\cimv2:Win32_DiskPartition.DeviceID="Disk #0, Partition #2" Antecedent : \\COOKHAM8\root\cimv2:Win32_DiskDrive.DeviceID="\\\\.\\PHYSICALDRIVE0" Dependent : \\COOKHAM8\root\cimv2:Win32_DiskPartition.DeviceID="Disk #0, Partition #3" Antecedent : \\COOKHAM8\root\cimv2:Win32_DiskDrive.DeviceID="\\\\.\\PHYSICALDRIVE6" Dependent : \\COOKHAM8\root\cimv2:Win32_DiskPartition.DeviceID="Disk #6, Partition #0" Win32_DiskDrive Partitions DeviceID Model Size Caption ---------- -------- ----- ---- ------- 1 \\.\PHYSICALDRIVE5 WD My Book IEEE 1394 SBP2 Device 2000388096000 WD My Book IEEE 1394 SBP2 D... 4 \\.\PHYSICALDRIVE0 ATA Hitachi HDS72107 SCSI Disk Device 750153761280 ATA Hitachi HDS72107 SCSI D... 0 \\.\PHYSICALDRIVE1 TEAC USB HS-CF Card USB Device TEAC USB HS-CF Card USB D... 0 \\.\PHYSICALDRIVE3 TEAC USB HS-MS Card USB Device TEAC USB HS-MS Card USB D... 0 \\.\PHYSICALDRIVE4 TEAC USB HS-SD Card USB Device TEAC USB HS-SD Card USB D... 0 \\.\PHYSICALDRIVE2 TEAC USB HS-xD/SM USB Device TEAC USB HS-xD/SM USB Device 1 \\.\PHYSICALDRIVE6 WD My Book USB Device 2000388096000 WD My Book USB Device Win32_DiskPartition NumberOfBlocks : 144522 BootPartition : False Name : Disk #0, Partition #0 PrimaryPartition : True Size : 73995264 Index : 0 NumberOfBlocks : 4209030 BootPartition : True Name : Disk #0, Partition #1 PrimaryPartition : True Size : 2155023360 Index : 1 NumberOfBlocks : 102400000 BootPartition : False Name : Disk #0, Partition #2 PrimaryPartition : True Size : 52428800000 Index : 2 NumberOfBlocks : 1358391296 BootPartition : False Name : Disk #0, Partition #3 PrimaryPartition : False Size : 695496343552 Index : 3 NumberOfBlocks : 3907012608 BootPartition : False Name : Disk #5, Partition #0 PrimaryPartition : True Size : 2000390455296 Index : 0 NumberOfBlocks : 3907012608 BootPartition : False Name : Disk #6, Partition #0 PrimaryPartition : True Size : 2000390455296 Index : 0 #> ## # Start of Script ## # First, display Win32DiskDriveToDiskPartition class # Only show two key properties "Win32_DiskDriveToDiskPartition" Get-WmiObject Win32_DiskDriveToDiskPartition | fl Antecedent, Dependent # Show the other related classes # First Win32_DiskDrive "";"Win32_DiskDrive" Get-WmiObject Win32_DiskDrive | ft -autosize # And now related Disk Partitions "";"Win32_DiskPartition" Get-WmiObject Win32_DiskPartition | sort name # End of script
Location:
Western Europe
Friday, 21 November 2008
Display-Array1.ps1
<# .SYNOPSIS Display's an Array .DESCRIPTION This script displays the values in an arra .NOTES File Name : Display-Array1.ps1 Author : Thomas Lee - tfl@psp.co.uk Requires : PowerShell V2 .LINK http://www.pshscripts.blogspot.com .EXAMPLE PSH [C:\foo]: .\Display-Array1.ps1' Initially, Integer array: 1 2 3 4 5 Object array: 26 27 28 29 30 After copying the first two elements of the integer array to the Object array, Integer array: 1 2 3 4 5 Object array: 1 2 28 29 30 After copying the last two elements of the Object array to the integer array, integer array: 1 2 3 29 30 Object array: 1 2 28 29 30 #> ## # Start of script ## # Helper function Function PrintValues{ [Cmdletbinding()] Param ($myArr ) ForEach ( $i in $myArr ) { "`t{0}" -f $i } "" } # Start of Sample # Creates and initializes a new integer array and a new Object array. $IntArray = 1, 2, 3, 4, 5 [system.object] $ObjArray = [object] 26, [object] 27, [object] 28,[object] 29,[object] 30 # Prints the initial values of both arrays. "Initially," "Integer array:" PrintValues( $IntArray ) "Object array: " PrintValues( $ObjArray ); # Copies the first two elements from the integer array to the Object array. [System.Array]::Copy( $IntArray, $ObjArray, 2) # Prints the values of the modified arrays. "`nAfter copying the first two elements of the integer array to the Object array," "Integer array:" PrintValues( $IntArray ); "Object array: " PrintValues( $ObjArray ); # Copies the last two elements from the Object array to the integer array. [System.Array]::Copy( $ObjArray, $ObjArray.GetUpperBound(0) - 1, $IntArray, $IntArray.GetUpperBound(0) - 1, 2 ) # Prints the values of the modified arrays. "`nAfter copying the last two elements of the Object array to the integer array," "integer array:" PrintValues( $IntArray ) "Object array: " PrintValues( $ObjArray )
Labels:
powershell,
PowerShell scripts,
system.array
Thursday, 20 November 2008
Display-TimeSpan.ps1
<#
.SYNOPSIS
Creates timespan objects and displays properties for each
.DESCRIPTION
This script creates time span objects then displays
the properties of each one.
.NOTES
File Name : Display-TimeSpan.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell V2
.LINK
http://pshscripts.blogspot.co.uk/2008/11/display-timespanps1.html
.EXAMPLE
PSH [C:\foo]: .\Display-Timespan.ps1
This example of the TimeSpan class properties
generates the following output. It creates
several TimeSpan objects and displays the values
of the TimeSpan properties for each
TimeSpan( 1 )
Interval = 00:00:00.0000001
Days 0 TotalDays 1.15740740740741E-12
Hours 0 TotalHours 2.77777777777778E-11
Minutes 0 TotalMinutes 1.66666666666667E-09
Seconds 0 TotalSeconds 1E-07
Milliseconds 0 TotalMilliseconds 0.0001
Ticks 1
TimeSpan( 111222333444555 )
Interval = 128.17:30:33.3444555
Days 128 TotalDays 128.729552597865
Hours 17 TotalHours 3089.50926234875
Minutes 30 TotalMinutes 185370.555740925
Seconds 33 TotalSeconds 11122233.3444555
Milliseconds 344 TotalMilliseconds 11122233344.4555
Ticks 111222333444555
TimeSpan( 10, 20, 30, 40, 50 )
Interval = 10.20:30:40.0500000
Days 10 TotalDays 10.8546302083333
Hours 20 TotalHours 260.511125
Minutes 30 TotalMinutes 15630.6675
Seconds 40 TotalSeconds 937840.05
Milliseconds 50 TotalMilliseconds 937840050
Ticks 9378400500000
TimeSpan( 1111, 2222, 3333, 4444, 5555 )
Interval = 1205.22:47:09.5550000
Days 1205 TotalDays 1205.94941614583
Hours 22 TotalHours 28942.7859875
Minutes 47 TotalMinutes 1736567.15925
Seconds 9 TotalSeconds 104194029.555
Milliseconds 555 TotalMilliseconds 104194029555
Ticks 1041940295550000
FromDays( 20.84745602 )
Interval = 20.20:20:20.1980000
Days 20 TotalDays 20.8474559953704
Hours 20 TotalHours 500.338943888889
Minutes 20 TotalMinutes 30020.3366333333
Seconds 20 TotalSeconds 1801220.198
Milliseconds 198 TotalMilliseconds 1801220198
Ticks 18012201980000
#>
##
# Start of Script
##
# Constant
$HeaderFmt = "`n{0, -45}"
$DataFmt = "{0,-12}{1,8} {2,-18}{3,21}"
# Helper function
function ShowTimeSpanProperties {
param ([System.TimeSpan] $Interval = 1)
# Display the properties of the TimeSpan parameter.
"Interval = {0,21}" -f $interval
"$DataFmt" -f "Days", $interval.Days, "TotalDays", $interval.TotalDays
"$DataFmt" -f "Hours", $interval.Hours, "TotalHours", $interval.TotalHours
"$dataFmt" -f "Minutes", $interval.Minutes, "TotalMinutes", $interval.TotalMinutes
"$DataFmt" -f "Seconds", $interval.Seconds, "TotalSeconds", $interval.TotalSeconds
"$DataFmt" -f "Milliseconds", $interval.Milliseconds, "TotalMilliseconds", $interval.TotalMilliseconds
"$DataFmt" -f $null, $null, "Ticks", $interval.Ticks
}
# Start of main script
# Create and display a comment
$comment = @"
This example of the TimeSpan class properties
generates the following output. It creates
several TimeSpan objects and displays the values
of the TimeSpan properties for each
"@
$comment
# Create and display a TimeSpan value of 1 tick.
$ts = [system.TimeSpan] 1
"$HeaderFmt" -f "TimeSpan( 1 )"
ShowTimeSpanProperties($ts)
# Create a TimeSpan value with a large number of ticks.
$ts = [System.TimeSpan] 111222333444555
"$HeaderFmt" -f "TimeSpan( 111222333444555 )"
ShowTimeSpanProperties($ts)
# This TimeSpan has all fields specified.
$ts = New-Object System.TimeSpan 10, 20, 30, 40, 50
"$HeaderFmt" -f "TimeSpan( 10, 20, 30, 40, 50 )"
ShowTimeSpanProperties($ts)
# This TimeSpan has all fields overflowing.
$ts = New-Object System.Timespan 1111, 2222, 3333, 4444, 5555
"$HeaderFmt" -f "TimeSpan( 1111, 2222, 3333, 4444, 5555 )"
ShowTimeSpanProperties($ts)
# This TimeSpan is based on a number of days.
$ts = [system.TimeSpan] ([system.TimeSpan]::FromDays(20.8474560))
"$headerFmt" -f "FromDays( 20.84745602 )"
ShowTimeSpanProperties($ts)
# End of script
Wednesday, 19 November 2008
Send-SMTPMessage.ps1
<#
.SYNOPSIS
Creates and sends an SMTP message
.DESCRIPTION
This script uses the system.net.mail class to create and send
an email message using SMTP.
.NOTES
File Name : Send-SMTPMessage.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell V2
.LINK
http://pshscripts.blogspot.co.uk/2008/11/send-smtpmessageps1.html
.EXAMPLE
PSH [C:\foo]: .\Send-SMTPMessage.ps1'
Sending an e-mail message to doctordns@gmail.com by using SMTP host localhost port 25.
Message to: powershell@psp.co.uk, from: doctordns@gmail.com has been successfully sent
#>
##
# Start of Script
##
# Create from/to addresses
$from = New-Object System.Net.Mail.MailAddress "powershell@psp.co.uk"
$to = New-Object System.Net.Mail.MailAddress "doctordns@gmail.com"
# Create Message
$message = new-object System.Net.Mail.MailMessage $from, $to
$message.Subject = "Using the SmtpClient class and PowerShell"
$message.Body = @"
Using this feature, you can send an e-mail message from an application very easily.
"@
# Set SMTP Server and create SMTP Client
$server = "localhost"
$client = new-object system.net.mail.smtpclient $server
# Send the message
"Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port
Try {
$client.Send($message)
"Message to: {0}, from: {1} has been successfully sent" -f $from, $to
}
Catch {
"Exception caught in CreateTestMessage: {0}" -f $Error[0]
}
Tuesday, 18 November 2008
Get-AssemblyVersion.ps1
<# .SYNOPSIS Gets the version number for an assembly .DESCRIPTION .NOTES File Name : Get-AssemblyVersion.ps1 Author : Thomas Lee - tfl@psp.co.uk Requires : PowerShell V4 .LINK http://pshscripts.blogspot.co.uk/2008/07/get-assemblyversionps1.html .EXAMPLE PSH [C:\foo]: .\Get-AssemblyVersion.ps1' Assembly: System.Speech has version number of: 4.0.0.0 #> # Start of script # Define the assembly we want to load - a random reference assembly from SDK 3.0 $Pshfile = "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\system.speech.dll" # Now load the assembly $Myasm = [System.Reflection.Assembly]::Loadfile($Pshfile) # Get name, version and display the results $Aname = $Myasm.GetName() $Aver = $Aname.version # Display results "Assembly: {0} has version number of: {1}" -f $Aname.name, $aver # End of script
Labels:
loadfile,
powershell,
system.reflection.assembly
Monday, 17 November 2008
Get-AssemblyName.ps1
<#
.SYNOPSIS
Gets assembly full name of a loaded assembly
.DESCRIPTION
This script uses reflection to get and assembly, then
gets the assembly's full name
.NOTES
File Name : Get-AssemblyName.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell V2 CTP3
.LINK
http://pshscripts.blogspot.co.uk/2008/11/get-assemblynameps1.html
.EXAMPLE
PSH [C:\foo]: .\Get-AssemblyName.Ps1'
Full name = "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
#>
# Start of script
# Using Reflection to get information from an Assembly:
$o =[System.Reflection.Assembly]::Load("mscorlib.dll")
$name = $o.GetName()
# Display full name
"Full name = `"{0}`"" -f $name
# End of script
Wednesday, 12 November 2008
Get-Extension.ps1
<# .SYNOPSIS Gets file extension .DESCRIPTION This script uses the GetExtension method to get a file extension .NOTES File Name : Get-Extension.ps1 Author : Thomas Lee - tfl@psp.co.uk Requires : PowerShell V2 .LINK http://www.pshscripts.blogspot.com .EXAMPLE PSH [C:\foo]: .\get-extension.ps1' GetExtension('C:\mydir.old\myfile.ext') returns '.ext' GetExtension('C:\mydir.old\') returns '' #> ## # Start of Script ## # Set values $fileName = "C:\mydir.old\myfile.ext" $path = "C:\mydir.old\" # Get filename extension $extension = [System.IO.Path]::GetExtension($fileName) "GetExtension('{0}') returns '{1}'" -f $fileName, $extension # Get Path Extension (hint: there is none!) $extension = [System.IO.Path]::GetExtension($path) "GetExtension('{0}') returns '{1}'" -f $path, $extension # End of Script
Labels:
GetExtension,
powershell,
Script,
System.IO.Path
Tuesday, 11 November 2008
Get-Type.ps1
<# .SYNOPSIS Uses GetType to obtain type information .DESCRIPTION This script creates an object then uses the GetType method to return type info .NOTES File Name : Get-Type.ps1 Author : Thomas Lee - tfl@psp.co.uk Requires : PowerShell V2 .LINK http://www.pshscripts.blogspot.com .EXAMPLE PSH [C:\foo]: .\get-type.ps1' Module : CommonLanguageRuntimeLibrary Assembly : mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 TypeHandle : System.RuntimeTypeHandle DeclaringMethod : BaseType : System.ValueType UnderlyingSystemType : System.Int32 FullName : System.Int32 AssemblyQualifiedName : System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561 34e089 Namespace : System GUID : a310fadd-7c33-377c-9d6b-599b0317d7f2 GenericParameterAttributes : IsGenericTypeDefinition : False IsGenericParameter : False GenericParameterPosition : IsGenericType : False ContainsGenericParameters : False StructLayoutAttribute : System.Runtime.InteropServices.StructLayoutAttribute Name : Int32 MemberType : TypeInfo DeclaringType : ReflectedType : MetadataToken : 33554629 TypeInitializer : IsNested : False Attributes : AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, Serializable, Befo eFieldInit IsVisible : True IsNotPublic : False IsPublic : True IsNestedPublic : False IsNestedPrivate : False IsNestedFamily : False IsNestedAssembly : False IsNestedFamANDAssem : False IsNestedFamORAssem : False IsAutoLayout : False IsLayoutSequential : True IsExplicitLayout : False IsClass : False IsInterface : False IsValueType : True IsAbstract : False IsSealed : True IsEnum : False IsSpecialName : False IsImport : False IsSerializable : True IsAnsiClass : True IsUnicodeClass : False IsAutoClass : False IsArray : False IsByRef : False IsPointer : False IsPrimitive : True IsCOMObject : False HasElementType : False IsContextful : False IsMarshalByRef : False #> ## # Start of script ## [int] $i = 42 $type = $i.GetType() $type | fl * # End of script
Labels:
GetType,
powershell,
PowerShell scripts
Subscribe to:
Posts (Atom)