Source Code and Samples
Friday, 23 February 2007
Enable or disable Remote Desktop
Enable or disable Remote Desktop
Data Source
$Terminal = Get-WmiObject Win32_Terminal –Computer "ComputerName"
$Terminal.Enable($True)
Thursday, 15 February 2007
Convert or export word documents to PDF
Convert or export word documents to PDF
Data Source
#You need to install "Microsoft Office 2007 Add-in: Microsoft Save as PDF or XPS"
$word = new-object -ComObject "word.application"
$doc = $word.documents.open("C:\document.doc")
$saveaspath = [ref] "c:\document.pdf"
$formatPDF = [ref] 17
$doc.SaveAs($saveaspath,$formatPDF)
$doc.Close()
Convert or export word documents to XPS
Convert or export word documents to XPS
Data Source
#You need to install "Microsoft Office 2007 Add-in: Microsoft Save as PDF or XPS"
$word = new-object -ComObject "word.application"
$doc = $word.documents.open("C:\document.doc")
$saveaspath = [ref] "c:\document.xps"
$formatXPS = [ref] 18
$doc.SaveAs($saveaspath,$formatXPS)
$doc.Close()
Send mails from powershell
Send mails from powershell
Source Code
$smtp = New-Object system.net.mail.smtpclient("smtp.server.com")
$smtp.send("fromuser@hotmail.com","touser@hotmail.com", "PowerShell script sample","You can see more powershell scripts in http://powershellscripts.blogspot.com")
Wednesday, 14 February 2007
Connect to Sql Server and execute SQL statements
Connect to Sql Server and execute SQL statements
Data Source
$Table = new-object System.Data.DataTable
$sqlConn = new-object System.Data.SqlClient.SqlConnection("Data Source=Server\sqlexpress;Initial Catalog=dbProducts;Integrated Security=True")
$adapter = new-object System.Data.SqlClient.SqlDataAdapter("Select * from Products",$sqlConn)
$adapter.Fill($Table)
write-output $table
Search Strings In Word Documents
Search Strings In Word Documents
Data Source
$SearchText = $args[0]
$word = new-object -ComObject "word.application"
$path = pwd
if ($args.length > 1) {
$docs = $args[1]
}
else {
$docs = "*.doc"
}
foreach ($a in $(get-childitem $docs -name)) {
$doc = $word.documents.open("$path\$a")
if ($doc.content.find.execute("$SearchText")) {
write-host $a
}
$doc.close();
}
Archive and pack IIS log files
Archive and pack IIS log files.
Source Code
$WinRar = "C:\Program Files\WinRAR\rar"
$TodaysLogFile = get-date -Uformat %y%m%d
$TodaysLogFile = "ex$TodaysLogFile.log"
$LogFiles = ls *.log
if ($LogFiles) {
foreach ($File in $LogFiles) {
$FileName = $File.Name
if ($FileName -ne $TodaysLogFile) {
echo "Compressing $FileName"
&$WinRar m "$FileName.rar" $FileName
}
}
}
Friday, 9 February 2007
Removing Applications locally or remotelly (PowerShell and WMI)
Removing Applications locally or remotelly
DataSource
(Get-WmiObject -Class Win32_Product -Filter "Name='ILMerge'" - ComputerName PC01).InvokeMethod("Uninstall",$null)
Installing Applications Locally or remotely (PowerShell and WMI)
Installing Applications Locally or remotely.
DataSource
(Get-WMIObject -ComputerName PC01 -List Where-Object -FilterScript {$_.Name -eq "Win32_Product"}).InvokeMethod("Install","\\AppSrv\dsp\NewPackage.msi")
Displaying Service Status and State for local or remote computers (PowerShell and WMI)
Displaying Service Status and State for local or remote computers with powershell.
Source code
Get-WmiObject -Class Win32_Service -ComputerName . Select-Object -Property Status,Name,DisplayName,State
Getting Available Disk Space (PowerShell and WMI)
Getting Available Disk Space. You need to see only instances with a DriveType of 3—the value WMI uses for fixed hard disks.
Source Code
Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName .
Listing Installed Hotfixes (using PowerShell and WMI)
Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName . (You can replace the trailing dot with a remote computer name).
Source Code
Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName .
Listing BIOS Information (using powershell and WMI)
Listing BIOS Information (using powershell and WMI). You can replace the trailing dot with a remote computer name.
Source Code
Get-WmiObject -Class Win32_BIOS -ComputerName .
Stopping, Starting, Suspending, and Restarting Services
Stopping, Starting, Suspending, and Restarting Services with powershell (spooler service in this example)
Source Code
Stop-Service -Name spooler
or
Start-Service -Name spooler
or
Suspend-Service -Name spooler
or
Restart-Service -Name spooler
Stop all nonresponsive applications
You can stop all nonresponsive applications with powershell
Source Code
Get-Process Where-Object -FilterScript {$_.Responding -eq $false} Stop-Process
Thursday, 8 February 2007
Create users in a OU
Here we can see how to create users in a Organizational Unit (OU).
Source Code
$OU= New-Object DirectoryServices.DirectoryEntry "LDAP://OU=SampleMustExists,DC=powershellscripts,DC=blogspot,DC=com"
$User=$OU.Create("user","CN=John")
$User.put("profilepath","\\server\share")
$User.SetInfo()
Create an OU in a domain
Here we can see how to create an OU in a domain.
Source Code
$Domain= New-Object DirectoryServices.DirectoryEntry "LDAP://DC=powershellscripts,DC=blogspot,DC=com"
$OU = $Domain.Create("organizationalUnit", "ou=PowerShell")
$OU.SetInfo()
Map network drives with powershell
Map network drives with powershell
Source Code
$net = $(New-Object -ComObject WScript.Network)
$net.MapNetworkDrive("x:", \\servername\sharedfolder)
List Users from a Organizational Unit (OU)
List Users from a Organizational Unit (OU).
Source Code
$Dom = "LDAP://OU=OfficeUsers,DC=powershellscripts,DC=blogspot,DC=com"
$Root = New-Object DirectoryServices.DirectoryEntry $Dom
# Create a selector and start searching from the Root of AD
$selector = New-Object DirectoryServices.DirectorySearcher
$selector.SearchRoot = $root
# Filter the users with -like "CN=Person*". Note the ForEach loop
$adobj= $selector.findall() where {
$_.properties.objectcategory -like "CN=Person*"
}
foreach ($person in $adobj)
{
$prop=$person.properties
Write-host "First name: $($prop.givenname) Surname: $($prop.sn) User: $($prop.cn)"
}
Write-host "There are $($adobj.count) users in the $($root.name) domain"
Monday, 5 February 2007
Adding New Windows PowerShell Drives (New-PSDrive)
To create a new Windows PowerShell drive, you must supply three parameters:
· A name for the drive (you can use any valid Windows PowerShell name)
· The PSProvider (use "FileSystem" for file system locations and "Registry" for registry locations)
· The root, that is, the path to the root of the new drive
Source Code
New-PSDrive -Name Startup -PSProvider Registry -Root HKLM\Software\Microsoft\Windows\CurrentVersion\Run
Now we can use cd Startup:
Printing Data from Powershell
You can print data by using the Out-Printer cmdlet. The Out-Printer cmdlet will use your default printer if you do not provide a printer name.
Source Code
Get-Command Out-Printer -Name "Microsoft Office Document Image Writer"
Messagebox in powershell
Show Messagebox in powershell. First we need to add a reference to an assembly to out script.
Source Code
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[Windows.Forms.MessageBox]::Show("Hello World!", "PowerShellScripts.blogspot.com", [Windows.Forms.MessageBoxButtons]::YesNo, [Windows.Forms.MessageBoxIcon]::Question)
Navigating the Registry
You can navigate through the Windows registry by using the same techniques that you use to navigate in the file system drive. In Windows PowerShell, the HKEY_LOCAL_MACHINE hive maps to the Windows PowerShell HKLM: drive and the HKEY_CURRENT_USER drive maps to the Windows PowerShell HKCU: drive.
Source Code
cd HKLM:
or
CD HKCU:
Export Mailbox Information to a Text File
Description
Exports information about all mailboxes to a commas-separated values file named Test.csv. This script/command requires Microsoft Exchange Server 2007.
Script Code
get-mailbox export-csv c:\scripts\test.csv
Set Message Size Restrictions
Sets message size restrictions for the distribution group FinanceUsers. This script/command requires Microsoft Exchange Server 2007.
Script Code
set-DistributionGroup FinanceUsers -MaxReceiveSize 50KB
Friday, 2 February 2007
Check for POP3 Messages
A great script from Paul Samways which allows you to check how many POP3 messages are in a mailbox.
Source Code
param ($Server, $Username, $Password);
$UsageScript = "Usage: getMail.msh [Server] [Username] [Password]";
$Port = 110;
if (($Server.length -lt 1) -or ($Username.length -lt 1) -or ($Password.length -lt 1)) {
write-output $UsageScript; break;
}
$TCPConnection = new-object -TypeName System.Net.Sockets.TcpClient($Server, $Port);
$NetStream = $TCPConnection.GetStream();
$Reader = new-object -TypeName System.IO.StreamReader($NetStream);
$Writer = new-object -TypeName System.IO.StreamWriter($NetStream);
$Buffer = $Reader.ReadLine();
$Writer.WriteLine("USER $Username");
$Writer.Flush(); $Buffer = $Reader.ReadLine();
$Writer.WriteLine("PASS $Password");
$Writer.Flush();
if ($Reader.ReadLine() -match "OK")
{
$writer.WriteLine("STAT"); $writer.Flush();
$NumOfMessage = $Reader.ReadLine().SubString(4, 1);
write-output "You Have $NumOfMessage Item(s) on $Server";
}
else
{
write-output "Authentication Error";
}
$Reader.Dispose();
$Writer.Dispose();
$NetStream.Dispose();
$TCPConnection.Close();
Returning Results from SQL as a Table
A great powershell script from "Greg" that shows how to produce tabulated results from a SQL query.
Source Code
function Get-Sql {
param ([string]$conn, [string]$sql)
# setup connection
$connObj = new-object System.Data.SqlClient.SqlConnection
$connObj.ConnectionString = $conn
# setup command $cmdObj = new-object System.Data.SqlClient.SqlCommand $cmdObj.Connection = $connObj
$cmdObj.CommandText = $sql
$connObj.Open()
$reader = $cmdObj.ExecuteReader()
while ($reader.Read()) {
$result = new-object System.Management.Automation.MshObject
for ($i=0;$i -lt ($reader.FieldCount) ;$i++) {
$fld = new-object System.Management.AUtomation.MshNoteProperty $reader.GetName($i), $reader[$i] $result.MshObject.Members.Add($fld); }
$result
}
$reader.Close()
$reader.Dispose()
$connObj.Close();
}
$connectionString = "Server=(local);Database=AdventureWorks;Integrated Security=SSPI"
$sqlText = "select top 10 * from Person.Contact"
Get-Sql $connectionString $sqlText format-table
Read Records from a Database
This powershell script reads records from a SQL Server database and displays them on the screen.
Source Code
$connectionString = "Server=(local);Database=AdventureWorks;Integrated Security=SSPI;"
$selectStatement = "select FirstName, LastName from Person.Contact;"
$connection = new-object System.Data.SqlClient.SqlConnection($connectionString)
$connection.Open()
$command = new-object System.Data.SqlClient.SqlCommand($selectStatement, $connection)
$reader = $command.ExecuteReader()
while ($reader.Read())
{
$firstName = $reader.GetString(0)
$lastName = $reader.GetString(1)
write-output "$firstName $lastName"
}
$connection.Close()
Compute the SHA1 Hash of a File
This powershell script computes the SHA1 hash of a file and displays it in Base64 format on the screen.
Source Code
$fileName = "File1.txt"
$provider = new-object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider
$fileContent = get-content $fileName
$fileContentBytes = [System.Text.Encoding]::UTF8.GetBytes($fileContent)
$hashBytes = $provider.ComputeHash($fileContentBytes)
$hashBytesEncoded = [System.Convert]::ToBase64String($hashBytes)
write-output $hashBytesEncoded
Delete All Files Older Than 10 Days
This powershell script deletes all from current and sub directories that are older than 10 days.
Source Code
$now = get-date
get-childitem . -recurse where-object {($now - $_.LastWriteTime).Days -lt 10} remove-item
Base64 Encode a File
This script will Base64 encode the contents of the file specified and output it to another file called {filename}.b64.
Source Code
$fileName = "File1.txt"
$fileContent = get-content $fileName
$fileContentBytes = [System.Text.Encoding]::UTF8.GetBytes($fileContent)
$fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes)
$fileContentEncoded set-content ($fileName + ".b64")
List Installed Products
This script lists the installed products on a machine by reading the registry. The complexity in the script is to deal with the variations in the way that some scripts store there uninstall data in the registry. This script may work better than some scripts that use WMI.
Source Code
$registryKeys = get-childitem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
foreach ($registryKey in $registryKeys)
{
$displayName = $registryKey.GetValue("DisplayName")
if ($displayName -eq $null)
{
$displayName = $registryKey.MshChildName
}
write-object $displayName
}
List All Running Services
Lists all running services on a Microsoft Exchange server. This script/command requires Microsoft Exchange Server 2007.
Source Code
Get-Service where {$_.Status -eq "Running"}
Move a Mailbox
Moves the mailbox kenmyer@fabrikam.com to a different database. This script/command requires Microsoft Exchange Server 2007.
Source Code
Move-Mailbox kenmyer@fabrikam.com -targetdatabase "Finance Mailbox Database"
Disable a Mailbox
Disables the kenmyer@fabrikam.com mailbox. This script/command requires Microsoft Exchange Server 2007.
Source Code
Disable-Mailbox kenmyer@fabrikam.com
Create a Mailbox for a New User
Creates a new mailbox named kenmyer. This script/command requires Microsoft Exchange Server 2007.
Source Code
new-Mailbox -alias "kenmyer" -name KenMyer –userprincipalname kenmyer@fabrikam.com -database "atl-ms-01\First Storage Group\Mailbox Database" -org users
How to delete all .txt files in a directory and all sub-directories
Description
The one-liners below can be used to recursively delete all .txt files in a given directory and all its sub-directories.
Source Code
Get-ChildItem -include "*.txt" -recur remove-itemor
Get-ChildItem -rec -filter *.txt remove-item
Get the Size of Mailboxes in all databases
Script displays table with mailbox size statistics.
Source Code
get-mailbox get-mailboxstatistics select-object DisplayName,TotalItemSize,StorageLimitStatus,LastLogonTime
Configure a Mailbox to Receive Mail and Forward That Mail to Another Recipient
Enables the kenmyer@fabrikam.com account to both receive mail and to forward that mail to pilarackerman@fabrikam.com. This script/command requires Microsoft Exchange Server 2007.
Script Code
Set-Mailbox kenmyer@fabrikam.com -DeliverToMailboxAndForward:$true -ForwardingAddress pilarackerman@fabrikam.com
Change the Department Name for All Mailboxes
Description
Assigns Finance as the department for all mailboxes. This script/command requires Microsoft Exchange Server 2007.
Script Code
Get-Mailbox Set-User –department Finance
Add a User to a Distribution List
Adds the account kenmyer@fabrikam.com to the FinanceUsers distribution group. This script/command requires Microsoft Exchange Server 2007.
Script Code
Add-DistributionGroupMember FinanceUsers -Member kenmyer@fabrikam.com
Add a New Email Address to a Mailbox
Adds the email address kmyer@fabrikam.com to the mailbox kenmyer@fabrikam.com. This script/command requires Microsoft Exchange Server 2007.
Source Code
set-Mailbox kenmyer@fabrikam.com -EmailAddresses ((get-Mailbox kenmyer@fabrikam.com).EmailAddresses + "kmyer@fabrikam.com")
List Mailboxes Over Quota
This script returns the names of the mailboxes that are over their quota limits.
Source Code
get-MailboxStatistics where {"IssueWarning","ProhibitSend","MailboxDisabled" -contains $_.StorageLimitStatus} format-Table MailboxDisplayName,TotalItemSize
List Service Properties
Retrieves a complete list of services and their associated properties. This script requires both Windows PowerShell and the corresponding version of the .NET Framework.
Source Code
$strComputer = "."
$colItems = get-wmiobject -class "Win32_Service" -namespace "root\CIMV2" `
-computername $strComputer
foreach ($objItem in $colItems) {
write-host "Accept Pause: " $objItem.AcceptPause
write-host "Accept Stop: " $objItem.AcceptStop
write-host "Caption: " $objItem.Caption
write-host "Checkpoint: " $objItem.CheckPoint
write-host "Creation Class Name: " $objItem.CreationClassName
write-host "Description: " $objItem.Description
write-host "Desktop Interact: " $objItem.DesktopInteract
write-host "Display Name: " $objItem.DisplayName
write-host "Error Control: " $objItem.ErrorControl
write-host "Exit Code: " $objItem.ExitCode
write-host "InstallationDate: " $objItem.InstallDate
write-host "Name: " $objItem.Name
write-host "Path Name: " $objItem.PathName
write-host "Process ID: " $objItem.ProcessId
write-host "Service Specific Exit Code: " $objItem.ServiceSpecificExitCode
write-host "Service Type: " $objItem.ServiceType
write-host "Started: " $objItem.Started
write-host "Start Mode: " $objItem.StartMode
write-host "Start Name: " $objItem.StartName
write-host "State: " $objItem.State
write-host "Status: " $objItem.Status
write-host "System Creation Class Name: " $objItem.SystemCreationClassName
write-host "System Name: " $objItem.SystemName
write-host "Tag ID: " $objItem.TagId
write-host "Wait Hint: " $objItem.WaitHint
write-host
}
List the Processes Running on a Computer
Returns information about all the processes running on a computer. This script requires both Windows PowerShell and the corresponding version of the .NET Framework.
Source Code
$strComputer = "."
$colItems = get-wmiobject -class "Win32_Process" -namespace "root\CIMV2" `
-computername $strComputer
foreach ($objItem in $colItems) {
write-host "Caption: " $objItem.Caption
write-host "Command Line: " $objItem.CommandLine
write-host "Creation Class Name: " $objItem.CreationClassName
write-host "Creation Date: " $objItem.CreationDate
write-host "CS Creation Class Name: " $objItem.CSCreationClassName
write-host "CS Name: " $objItem.CSName
write-host "Description: " $objItem.Description
write-host "Executable Path: " $objItem.ExecutablePath
write-host "Execution State: " $objItem.ExecutionState
write-host "Handle: " $objItem.Handle
write-host "Handle Count: " $objItem.HandleCount
write-host "Installation Date: " $objItem.InstallDate
write-host "Kernel-Mode Time: " $objItem.KernelModeTime
write-host "Maximum Working Set Size: " $objItem.MaximumWorkingSetSize
write-host "Minimum Working Set Size: " $objItem.MinimumWorkingSetSize
write-host "Name: " $objItem.Name
write-host "Operating System Creation Class Name: " $objItem.OSCreationClassName
write-host "Operating System Name: " $objItem.OSName
write-host "Other Operation Count: " $objItem.OtherOperationCount
write-host "Other Transfer Count: " $objItem.OtherTransferCount
write-host "Page Faults: " $objItem.PageFaults
write-host "Page File Usage: " $objItem.PageFileUsage
write-host "Parent Process ID: " $objItem.ParentProcessId
write-host "Peak Page File Usage: " $objItem.PeakPageFileUsage
write-host "Peak Virtual Size: " $objItem.PeakVirtualSize
write-host "Peak Working Set Size: " $objItem.PeakWorkingSetSize
write-host "Priority: " $objItem.Priority
write-host "Private Page Count: " $objItem.PrivatePageCount
write-host "Process ID: " $objItem.ProcessId
write-host "Quota Non-Paged Pool Usage: " $objItem.QuotaNonPagedPoolUsage
write-host "Quota Paged Pool Usage: " $objItem.QuotaPagedPoolUsage
write-host "Quota Peak Non-Paged Pool Usage: " $objItem.QuotaPeakNonPagedPoolUsage
write-host "Quota Peak Paged Pool Usage: " $objItem.QuotaPeakPagedPoolUsage
write-host "Read Operation Count: " $objItem.ReadOperationCount
write-host "Read Transfer Count: " $objItem.ReadTransferCount
write-host "Session ID: " $objItem.SessionId
write-host "Status: " $objItem.Status
write-host "Termination Date: " $objItem.TerminationDate
write-host "Thread Count: " $objItem.ThreadCount
write-host "User-Mode Time: " $objItem.UserModeTime
write-host "Virtual Size: " $objItem.VirtualSize
write-host "Windows Version: " $objItem.WindowsVersion
write-host "Working Set Size: " $objItem.WorkingSetSize
write-host "Write Operation Count: " $objItem.WriteOperationCount
write-host "Write Transfer Count: " $objItem.WriteTransferCount
write-host
}
List Events from the Event Logs
Description
Retrieves events from the Application and System event logs. This script requires both Windows PowerShell and the corresponding version of the .NET Framework.
Source Code$strComputer = "."
$colItems = get-wmiobject -class "Win32_NTLogEvent" -namespace "root\CIMV2" `-computername $strComputer
foreach ($objItem in $colItems) {
write-host "Category: " $objItem.Category
write-host "Category String: " $objItem.CategoryString
write-host "Compute rName: " $objItem.ComputerName
write-host "Data: " $objItem.Data
write-host "Event Code: " $objItem.EventCode
write-host "Event Identifier: " $objItem.EventIdentifier
write-host "Event Type: " $objItem.EventType
write-host "Insertion Strings: " $objItem.InsertionStrings
write-host "Logfile: " $objItem.Logfile
write-host "Message: " $objItem.Message
write-host "Record Number: " $objItem.RecordNumber
write-host "Source Name: " $objItem.SourceName
write-host "Time Generated: " $objItem.TimeGenerated
write-host "Time Written: " $objItem.TimeWritten
write-host "Type: " $objItem.Type
write-host "User: " $objItem.User
write-host
}
List Event Log Properties
Description
Retrieves a list of properties for all the event logs on a computer, except the Security event log. This script requires both Windows PowerShell and the corresponding version of the .NET Framework.
Source Code
$strComputer = "."
$colItems = get-wmiobject -class "Win32_NTEventlogFile" -namespace "root\CIMV2" `
-computername $strComputer
foreach ($objItem in $colItems) {
write-host "Access Mask: " $objItem.AccessMask
write-host "Archive: " $objItem.Archive
write-host "Caption: " $objItem.Caption
write-host "Compressed: " $objItem.Compressed
write-host "Compression Method: " $objItem.CompressionMethod
write-host "Creation Class Name: " $objItem.CreationClassName
write-host "Creation Date: " $objItem.CreationDate
write-host "CS Creation Class Name: " $objItem.CSCreationClassName
write-host "CS Name: " $objItem.CSName
write-host "Description: " $objItem.Description
write-host "Drive: " $objItem.Drive
write-host "8.3 File Name: " $objItem.EightDotThreeFileName
write-host "Encrypted: " $objItem.Encrypted
write-host "Encryption Method: " $objItem.EncryptionMethod
write-host "Extension: " $objItem.Extension
write-host "File Name: " $objItem.FileName
write-host "File Size: " $objItem.FileSize
write-host "File Type: " $objItem.FileType
write-host "FS Creation Class Name: " $objItem.FSCreationClassName
write-host "FS Name: " $objItem.FSName
write-host "Hidden: " $objItem.Hidden
write-host "Installation Date: " $objItem.InstallDate
write-host "In Use Count: " $objItem.InUseCount
write-host "Last Accessed: " $objItem.LastAccessed
write-host "Last Modified: " $objItem.LastModified
write-host "Logfile Name: " $objItem.LogfileName
write-host "Manufacturer: " $objItem.Manufacturer
write-host "Maximum File Size: " $objItem.MaxFileSize
write-host "Name: " $objItem.Name
write-host "Number Of Records: " $objItem.NumberOfRecords
write-host "Overwrite Outdated: " $objItem.OverwriteOutDated
write-host "Overwrite Policy: " $objItem.OverWritePolicy
write-host "Path: " $objItem.Path
write-host "Readable: " $objItem.Readable
write-host "Sources: " $objItem.Sources
write-host "Status: " $objItem.Status
write-host "System: " $objItem.System
write-host "Version: " $objItem.Version
write-host "Writeable: " $objItem.Writeable
write-host
}