|
Dump files into a directory. function global:dumpfiles { param($files)
$location = get-location $basePath = $location.Path; foreach ($file in $files) { $newFileName = [System.IO.Path]::Combine($basePath, $file.Name) $file.CopyTo($newFileName) } }
#usage: dumpfiles($someFilesVariable)
|
Delete All Files Older Than 10 DaysUntested - Deletes all from current and sub directories that are older than 10 days
$now = get-date get-childitem . -recurse | where-object {($now - $_.LastWriteTime).Days -lt 10} | remove-item
|
Network BeepHere is a fun little script. Run the script and then telnet into the machine it is running on, on port 1111 then start typing. Its a network beeper! In fact if you type really quickly you get that nice authentic sci-fi movie sound of computers crunching numbers.
$listener = new-object -TypeName System.Net.Sockets.TcpListener 1111 $listener.Start() $client = $listener.AcceptTcpClient() $stream = $client.GetStream() $reader = new-object -TypeName System.IO.StreamReader $stream while (!$reader.EndOfStream) { $character = $reader.Read() [System.Console]::Beep($character * 2, 50) } $client.Close() $listener.Stop()
|
List ProgID's in the HKEY_CLASSES_ROOT HiveThis script lists all the ProgID's found under the HKCR\CLSID registry key. It works be enumerating all the sub-keys and then filtering out the ones that don't have a ProgID sub-key defined.
$originalLocation = get-location $clsidKeys = get-childitem -Path Registry::HKEY_CLASSES_ROOT\CLSID | where { $_.OpenSubKey("ProgID") -is [Microsoft.Win32.RegistryKey] } foreach ($clsidKey in $clsidKeys) { $progID = $clsidKey.OpenSubKey("ProgID").GetValue("") write-object $progID } set-location $originalLocation
|
Stop All BizTalk 2006 Host InstancesThis script enumerates and stops all BizTalk 2006 host instances that are running on the local machine. It works by piping the service details for each service and then filtering all services except those that have the prefix "BTSSvc$".
get-service | where { $_.Name -like “BTSSvc$*” } | stop-service
|
List Installed ProductsThis 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.
$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 }
|
Base64 Encode a FileThis script will Base64 encode the contents of the file specified and output it to another file called {filename}.b64.
$fileName = "File1.txt" $fileContent = get-content $fileName $fileContentBytes = [System.Text.Encoding]::UTF8.GetBytes($fileContent) $fileContentEncoded = [System.Convert]::ToBase64String($fileContentBytes) $fileContentEncoded | set-content ($fileName + ".b64")
|
Compute the SHA1 Hash of a File This script computes the SHA1 hash of a file and displays it in Base64 format on the screen.
$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-object $hashBytesEncoded
|
Replace Redundant Whitespace for ParsingThis script reads in the specified files and trips all multi-space string sequences down to a single space to make parsing easier.
$fileName = "File1.txt" $contents = get-content $fileName while ($contents -like("* *")) { $contents = $contents -replace(" ", " ") } write-object $contents
|
List ProgID's in the HKEY_CLASSES_ROOT HiveThis script lists all the ProgID's found under the HKCR\CLSID registry key. It works be enumerating all the sub-keys and then filtering out the ones that don't have a ProgID sub-key defined.
$originalLocation = get-location $clsidKeys = get-childitem -Path Registry::HKEY_CLASSES_ROOT\CLSID | where { $_.OpenSubKey("ProgID") -is [Microsoft.Win32.RegistryKey] } foreach ($clsidKey in $clsidKeys) { $progID = $clsidKey.OpenSubKey("ProgID").GetValue("") write-object $progID } set-location $originalLocation
|
Export Directory Contents to CSV FileThis script is intended to be saved to a .msh script file and run from there. It will get a list of the contents of the current directory and save it to the CSV file specified in the string parameter that is passed in. It doesnt currently have any parameter validation or error handling.
Param([string] $csvfilepath="$(get-location)/ExportedCSV.csv") $csvfilename = [System.IO.Path]::GetFileName($csvfilepath) $csvdirectory = [System.IO.Path]::GetDirectoryName($csvfilepath) get-childitem | select-object Mode,Name,Length,DirectoryName,DirectoryIsReadOnly,Exists,FullName,Extension,CreationTime,LastAccessTime,LastWriteTime,Attributes | export-csv $csvfilepath write-host `n "$csvfilename written to $csvdirectory" `n
|
Simple Screen ScraperThis script is just a simple screen scraper that will go to a web page (first parameter), retrieve the HTML and save it to a file (second parameter). It can easily be extended to support proxy servers etc.
Param([string] $address = "", [string] $path="$(get-location)/SavedHTML.html") if ($address -eq "") { write-host "Please enter a URL" `n exit } [System.Net.HttpWebRequest] $request = [System.Net.HttpWebRequest]::Create($address) $request.Timeout = 60 [IAsyncResult] $asyncResult = $request.BeginGetResponse($null, $null) write-host "Retrieving contents..." [System.Net.WebResponse] $response = $request.EndGetResponse($asyncResult) [System.IO.StreamReader] $respStreamReader = new-object System.IO.StreamReader $response.GetResponseStream() [string] $responseHTML = $respStreamReader.ReadToEnd() $respStreamReader.Close() $response.Close() $responseHTML | set-content $path write-host "HTML from `"$address`" is written to `"$path`"" trap [System.Exception] { write-host "There was an error while trying to connect to `"$address`"" `n exit }
|
Script to dump out product keyThis script dumps out the Windows Product Key from the machine that it runs on.
#Unsure about an Legal issues with this script, but it is handy for auditing. #Tested on Windows XP, MSH b2 #Original Source Code created by Syntax in VB5 #Ported to MSH (Monad) by Paul Samways $Location = "HKLM:\Software\Microsoft\Windows NT\CurrentVersion"; $BinarySerial = (get-property $Location).DigitalProductId; $PossibleChars = [char[]]('B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9'); $ProductKey = [byte[]]@(); $ProductID = [byte[]]@(); $StringKey = ""; $StringID = ""; for ($i = 8; $i -le 66; $i++) { if($i -lt 31) { $ProductID += $BinarySerial[$i]; } elseif($i -gt 51) { $ProductKey += $BinarySerial[$i]; } } for($i = 0; $i -le 22; $i++) { $StringID += [char]$ProductID[$i] } for ($i = 24; $i -ge 0; $i--) { $ncur = 0; for ($x = 14; $x -ge 0; $x--) { $a = $ncur * 256; $b = $ProductKey[$x]; $ncur = ($a -bor $b) - ($a -band $b); $c = $ncur / 24; if (($c % 1) -gt 0) { $c = $c - ($c % 1); } $ProductKey[$x] = [byte]$c; $ncur %= 24; } $StringKey = [string]$PossibleChars[$ncur] +
|
Read Records from a DatabaseThis script reads records from a SQL Server database and displays them on the screen.
$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-object "$firstName $lastName" } $connection.Close()
|
Returning Results from SQL as a TableA great script from "Greg" that shows how to produce tabulated results from a SQL query in Monad.
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
|
Check for POP3 MessagesA great script from Paul Samways which allows you to check how many POP3 messages are in a mailbox
param ($Server, $Username, $Password); $UsageScript = "Usage:`n`t getMail.msh [Server] [Username] [Password]"; $Port = 110; if (($Server.length -lt 1) -or ($Username.length -lt 1) -or ($Password.length -lt 1)) { write-object $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-object "You Have $NumOfMessage Item(s) on $Server"; } else { write-object "Authentication Error"; } $Reader.Dispose(); $Writer.Dispose(); $NetStream.Dispose(); $TCPConnection.Clos
|