Pages

Showing posts with label script. Show all posts
Showing posts with label script. Show all posts

10/09/2014

Don't pad number strings, use modular arithmetic to calculate each digit

Example in Python:
// = integer division
% = remainder

# given t in tenths of seconds, 
# return a string of format string A:BC.D
# A = minutes, BC = seconds, with leading zero if needed, D = tenths of seconds
def format(t):
    tenths = t % 10
    t = t // 10
    sec = t % 60
    min = t // 60
    sec_ones = sec % 10
    sec_tens = sec // 10
    display = str(min) + ":" + str(sec_tens) + str(sec_ones) + "." + str(tenths)
    return display

9/30/2014

Test time to open Word documents of various sizes

Goal: Test to gather the time to open and save various size documents

function sleep(milliseconds) {
 var start = new Date().getTime();
 for (var i = 0; i < 1e7; i++) {
  if ((new Date().getTime() - start) > milliseconds){
   break;
   }
  }
 }

var myApp = new ActiveXObject("Word.Application");
myApp.Visible = true;

// Open 200K
var smopenstart = new Date().getTime();
  myApp.Documents.Open("Z:\\200K.doc");
var smopenend = new Date().getTime();

//wait 10 s
sleep(10000);

// Save 200K
var smsavestart = new Date().getTime();
  myApp.ActiveDocument.SaveAs("Z:\\NEW\\200K.doc");
var smsaveend = new Date().getTime();

// Close 200K
myApp.Documents.Close();

//quit Word
myApp.Application.Quit();

//wait 10 s
sleep(10000);

var myApp = new ActiveXObject("Word.Application");
myApp.Visible = true;

// Open 1MB
var medopenstart = new Date().getTime();
  myApp.Documents.Open("Z:\\1M.doc");
var medopenend = new Date().getTime();

//wait 10 s
sleep(10000);

// Save 1MB
var medsavestart = new Date().getTime();
  myApp.ActiveDocument.SaveAs("Z:\\NEW\\1M.doc");
var medsaveend = new Date().getTime();

// Close 1MB
myApp.Documents.Close();

//quit Word
myApp.Application.Quit();


//wait 10 s
sleep(10000);

var myApp = new ActiveXObject("Word.Application");
myApp.Visible = true;

// Open 5MB
var lrgopenstart = new Date().getTime();
  myApp.Documents.Open("Z:\\5M.doc");
var lrgopenend = new Date().getTime();

//wait 10 s
sleep(10000);

// Save 5MB
var lrgsavestart = new Date().getTime();
  myApp.ActiveDocument.SaveAs("Z:\\NEW\\5M.doc");
var lrgsaveend = new Date().getTime();

// Close 5MB
myApp.Documents.Close();

//quit Word
myApp.Application.Quit();

//define date string
var mo = new Date().getMonth()+1;
if (mo < 10) { mo = "0" + mo };
var day = new Date().getDate();
if (day < 10) {day = "0" + day};
var year = new Date().getFullYear();
var hrs = new Date().getHours();
if (hrs < 10) {hrs = "0" + hrs};
var m = new Date().getMinutes();
if (m < 10) {m = "0" + m};
var s = new Date().getSeconds();
if (s < 10) {s = "0" + s};
var dt = mo + "/" + day + "/" + year + " " + hrs + ":" + m + ":" + s

//Calculate times
var smopentime = (smopenend - smopenstart)/1000
var smsavetime = (smsaveend - smsavestart)/1000
var medopentime = (medopenend - medopenstart)/1000
var medsavetime = (medsaveend - medsavestart)/1000
var lrgopentime = (lrgopenend - lrgopenstart)/1000
var lrgsavetime = (lrgsaveend - lrgsavestart)/1000

//output results
WScript.Echo(dt, ",", smopentime, ",", smsavetime, ",", medopentime, ",", medsavetime, ",", lrgopentime, ",", lrgsavetime);
Save above as "openword.js" and call with the following BAT file

net use Z: \\SHARE\TEST\ATL
c:
cd\temp
cscript //NoLogo c:\temp\openword.js >> CHI.log
echo y | del z:\new\*.*
net use z: /delete

9/29/2014

Script: Time To Open Word Document

I want to time how long it takes to open a Word document over the WAN.

var myApp = new ActiveXObject("Word.Application");
myApp.Visible = true;
// Remember when we started
var start = new Date().getTime();
  myApp.Documents.Open("Z:\\openword\\1M.doc");
  //myApp.ActiveDocument.SaveAs("Z:\\openword\\1M.doc");
  myApp.Documents.Close();
// Remember when we finished
myApp.Application.Quit();
var end = new Date().getTime();
// Now calculate and output the difference
var time = end - start;
var mo = new Date().getMonth()+1;
if (mo < 10) { mo = "0" + mo };
var day = new Date().getDate();
if (day < 10) {day = "0" + day};
var year = new Date().getFullYear();
var hrs = new Date().getHours();
if (hrs < 10) {hrs = "0" + hrs};
var m = new Date().getMinutes();
if (m < 10) {m = "0" + m};
var s = new Date().getSeconds();
if (s < 10) {s = "0" + s};
var dt = mo + "/" + day + "/" + year + " " + hrs + ":" + m + ":" + s
WScript.Echo(dt, time / 1000);
save as c:\temp\testword.js run from CMD.EXE: cscript c:\temp\testword.js Will output something like: 9/29/2014 22:43:25 , 3.252

9/26/2014

Test Word Open & Save Repeatedly

From: OpLocks.net

var i;
var myApp = new ActiveXObject("Word.Application");
myApp.Visible = true;
for (i = 0; i < 1234; i++)
 {
  myApp.Documents.Open("C:\\TEMP\\testword.doc");
  //myApp.ActiveDocument.SaveAs("C:\\TEST\\testword.doc");
  myApp.Documents.Close();
 }
myApp.Application.Quit();
paste in editor and save as "test.js" for example. to run: cscript test.js

11/07/2013

Simple Host Time Information

Simple Host Time Information

Get-VMHost | Sort Name | Select Name, `
  @{N="NTPServer";E={$_ |Get-VMHostNtpServer}}, `Timezone, `
  @{N="CurrentTime";E={(Get-View $_.ExtensionData.ConfigManager.DateTimeSystem) | Foreach {$_.QueryDateTime().ToLocalTime()}}}, `
  @{N="ServiceRunning";E={(Get-VmHostService -VMHost $_ |Where-Object {$_.key-eq "ntpd"}).Running}} `
 | Format-Table -AutoSize

1/25/2012

Script to push config changes to switches and routers.

Perl::Cisco::Script to push config changes to switches and routers.


#reconfig.pl
#
#############
use Net::Telnet;
#
my $list = "./list.txt";
my $cmd = "./cmds.txt";
my $login = "config";
my $password = "XXXXXXXXXX";
open HOSTS, "<", $list or die "$list not found!";
    my @all = ;
close HOSTS;
open CMDS, "<", $cmd or die "$cmd not found!";
    my @todo = ;
close CMDS;
###############
foreach $host (@all) {
$host =~ s/^\s+//;
$host =~ s/\s+$//;
my $outfile = "./$host-log.txt";
open OUT, ">", $outfile or die "Unable to create $outfile!";
print $host;
 if ($host =~ m/#/i) { #skip
  next;
 }
 print OUT "HOST=$host\n";
 $telnet = new Net::Telnet ( 
     Timeout=>15,
  Errmode=> sub{&ConnErr},
  Prompt => '/.*#$/');
 $telnet->open($host);
 $telnet->login($login, $password);
 foreach $task (@todo) {
  if ($task =~ m/#/i) { #skip
   next;
   }
  print OUT " -> $task  <-\t";
  @result = $telnet->cmd(String =>$task, Prompt => '/.*#$/');
  $telnet->waitfor('/#/');
  print OUT @result;
  print OUT "\r\n";
  foreach $line (@result) {
   if (($line =~ m/%/i)or($line =~ m/Translating/i)) { #Woah there!
    print OUT "ERROR:  Terminating\r\n";
    print "ERROR:  Check Log\r\n";
    exit;
   }
  }
  $telnet->waitfor('/#/');
 } #foreach task
print OUT "----------------------------------------\r\n";
#$telnet->waitfor('/#/');
close OUT;
} #foreach host

#END MAIN

################
sub ConnErr {
    print OUT "ERROR:  Connection Failed to $host\r\n";
    print OUT "----------------------------------------\r\n";
    next;
}
################

1/24/2011

WSUS: Microsoft Windows Server Update Service

The MMC for WSUS leaves much to be desired for reporting. It'd be nice to be able to print or at least export the view that lists the clients and their status. So it can be used to figure out which clients are missing or what servers might be configured there still that no longer exist.
The script below will help. It generates a list of server machine accounts from AD and then exports the list from WSUS and then generates lists for review.
#LIST-AUDIT.PS1
#Export list of server accounts from AD, export WSUS clients, compare
#
#Define variables
$WSUSserver = 'PRIWSUS02'
$serverlist = 'c:\audit\data\servers.txt'
$WSUSList = 'c:\audit\data\WSUS.txt'
$InWSUS = 'c:\audit\data\OK-Servers-on-WSUS-list.txt'
$NotInWSUS = 'c:\audit\report\REVIEW-Servers-not-on-WSUS-list.txt'
$allservers = 'c:\audit\data\allservers.txt'
$WSUSorphans = 'c:\audit\report\REVIEW-WSUS-item-not-on-Servers-list.txt'
#Initialize files
New-Item $serverlist -Type file -Force >$nul
New-Item $WSUSList -Type file -Force >$nul
New-Item $InWSUS -Type file -Force >$nul
New-Item $NotInWSUS -Type file -Force >$nul
New-Item $allservers -Type file -Force >$nul
New-Item $WSUSorphans -Type file -Force >$nul
#Get list of servers from AD
$strCategory = "computer" 
$strOS = "Windows*Server*"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry 
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher 
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = ("OperatingSystem=$strOS")
$colProplist = "dnshostname"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
$colResults = $objSearcher.FindAll()
foreach ($objResult in $colResults) 
{$objComputer = $objResult.Properties;  
$objComputer.dnshostname >> $serverlist}
#Get WSUS list
function Get-WSUSComputers()
{
[void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($WSUSserver,$false)
$wsus.GetComputerTargets()
}
Get-WSUSComputers | Sort FullDomainName |`
Select FullDomainName | `
Out-File -FilePath $WSUSList -Force
$Servers = get-content $ServerList
$WSUS = get-content $WSUSList
#compare lists
Foreach ($Server in $Servers)
{$Server = $Server.tolower()
$Server = $Server + (" " * (79 - $Server.Length))
Add-content $allservers $Server
If ($WSUS -contains $Server)
{ Add-content $InWSUS $Server }
Else
{ Add-content $NotInWSUS $Server }
}
$ADList = get-content $allservers
Foreach ($Server in $WSUS)
{
If ($ADList -contains $Server)
{ write-host "ok" >$nul }
Else
{ Add-content $WSUSorphans $Server }
}

10/08/2007

VBS::Parsing CSV


This is a great ongoing series:
Hey Scripting Guy!


Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Scripts\Test.txt", ForReading)

Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
arrFields = Split(strLine, ",")

If InStr(arrFields(1), "Everyone") Then
strContents = strContents & arrFields(5) & vbCrlf
End If
Loop

objFile.Close

Set objFile = objFSO.CreateTextFile("C:\Scripts\Everyone.txt")
objFile.Write strContents

objFile.Close

9/07/2007

Perl::Script::Cleanup Old Files


The following script will accept a list of folders and recursively look through each one for files older than a specified number of days.
A parameter file is used to provide input so it can be flexible after packaging with PerlPackager.

#cleanup.pl
use File::Find;
#get parameters
open (PRM, ";
close (PRM);
my $folder = $prm[0];
chomp $folder;
my @folder = split(/,/,$folder);
my $limit = $prm[1];
chomp $limit;
#Create log folder if it does not exist
if (not(-e "cleanup\\.")) {
mkdir ("cleanup");
}
#Name Log File
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime();
$m = sprintf("%0.2i", $mon+1);
$d = sprintf("%0.2i", $mday);
$y = $year + 1900 ;
$yy = substr($y, -2, 2);
$yy = sprintf("%0.2i", $yy);
$hh = sprintf("%0.2i", $hour);
$mm = sprintf("%0.2i", $min);
$ss = sprintf("%0.2i", $sec);
$T = "$y$m$d$hh$mm$ss" ;
$logfile=".\\cleanup\\$T.log";
open(LOG, ">$logfile");
print LOG "Cleanup run: $m\/$d\/$y $hh:$mm:$ss\n Folders: @folder\n Delete older than: $limit days\n";
print LOG "The following files, if any, have been deleted:\n";
find(\&CheckFile, @folder);
sub CheckFile {
if (not(-d $_)) {
if ($limit < (-M $_)) { $current = $File::Find::name; $current =~ tr/\//\\\\/; unlink $_; print LOG " $current\n"; } } } close (LOG);

The parameter file is below. It is setup to purge it's own log folder (.\cleanup) after the same number of days.

.\cleanup,c:\dev\purge\test\bak\1,c:\dev\purge\test\bak\2
10
#line 1 = comma separated list of folders to recursively search for old files.
#line 2 = number of days after which to delete files.

Perl::File Testing



# -o $file true if owned by EUID
# -e $file exists
# -z $file zero file
# -s $file non-zero file, returns size
# -r $file readable
# -w $file writeable
# -x $file executable
# -f $file plain file
# -d $file directory
# -l $file symbolic link
# -p $file named pipe or FIFO
# -S $file socket
# -b $file block special file
# -c $file character special file
# -T $file text file
# -B $file binary file
# -u $file setuid
# -g $file setgid
# -k $file sticky
# -t $file true if opened to a tty
# -M $file age in days since modified
# -A $file age in days since last accessed
# -C $file age in days since inode changed

8/31/2007

Windows::Inventory::Report files of particular extension::UPDATE


I seem to make this mistake a lot. My initial goal was to create a csv format file and import to excel or someplace. But I did not account for the case where a comma is in the data. It is never in the front of my mind that a comma is a valid character in a filename.
The corrected script is below.

'==========================================================================
' NAME: Script to search for files with listed extensions
'
'
'==========================================================================

Option Explicit

Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20

Const PATH_TO_INPUT = "in.txt"
Const PATH_TO_OUTPUT = "out.txt"

Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")

Dim shl
Set shl = WScript.CreateObject("WScript.Shell")

Dim input
Set input = fso.OpenTextFile(PATH_TO_INPUT)

Dim output
Set output = fso.CreateTextFile(PATH_TO_OUTPUT, True)

Dim wmiService
Dim wmiResults
Dim objwMIService
Dim colFiles
Dim objFile

Dim hostname

Dim line
Dim exec
Dim pingResults
Dim strFileName


While Not input.AtEndOfStream
line = input.ReadLine
hostname = ""
Set exec = shl.Exec("ping -n 2 -w 500 " & line)
pingResults = LCase(exec.StdOut.ReadAll)

If InStr(pingResults, "reply from") Then

WScript.Echo "Reply From: " & line
hostname = line

Set objWMIService = GetObject("winmgmts:\\" & hostname & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("Select * from CIM_Datafile Where Extension = 'pst' OR Extension = 'pdf' OR Extension = 'doc' OR Extension = 'xls'")

For Each objFile in colFiles
strFileName = Replace(objFile.Name, "," , " ")
output.WriteLine hostname & "," & strFileName & "," & objFile.FileSize
Next

Else
WScript.Echo line & " no response"
End If
Wend

output.Close
input.Close

Set wmiService = Nothing
Set wmiresults = Nothing

8/29/2007

Batch Processes


I recently have found myself running batch processes scanning inventory on long lists of machines. To have more control I usually generate a list of IP's or machine names and use it as an input file to my process.
It is obvious after the fact, but I often don't think of it until I've wasted time on something taking too long -- things go faster if they are broken up into groups and processed in parallel.
I need to spend some time to make up a script to automate this, but what I do is:
- Create folders 0 - 9 beneath a process folder.
- Copy the script to each folder.
- Break up my input file of items to process into 10 equal in.txt files and put one in each folder.
- I generally have the script create an output file such as out.txt
- Run the script redirecting output to stdout.txt
- Tile them all on my second monitor and watch each for errors or a Complete! message.
- Run a script like the one below to consolidate the logs.

REM collectLOG.cmd
del temp\*.* /y
For /d %%p in (*) do copy "%%p\stdout.txt" "temp\%%p.log"
copy temp\*.log final\discovery.log

- Run a script like the one below to consolidate the output.

REM collectCSV.cmd
For /d %%p in (*) do copy "%%p\out.txt" "final\%%p.csv"

Windows::Inventory::Report files of particular extension


For desired file extensions this script will report the filename and file size for all machines listed in input file.

'==========================================================================
' Script to search for files with listed extensions
'==========================================================================

Option Explicit

Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20

Const PATH_TO_INPUT = "in.txt"
Const PATH_TO_OUTPUT = "out.txt"

Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")

Dim shl
Set shl = WScript.CreateObject("WScript.Shell")

Dim input
Set input = fso.OpenTextFile(PATH_TO_INPUT)

Dim output
Set output = fso.CreateTextFile(PATH_TO_OUTPUT, True)

Dim wmiService
Dim wmiResults
Dim objwMIService
Dim colFiles
Dim objFile
Dim hostname
Dim line
Dim exec
Dim pingResults

While Not input.AtEndOfStream
line = input.ReadLine
hostname = ""
Set exec = shl.Exec("ping -n 2 -w 500 " & line)
pingResults = LCase(exec.StdOut.ReadAll)

If InStr(pingResults, "reply from") Then

WScript.Echo "Reply From: " & line
hostname = line

Set objWMIService = GetObject("winmgmts:\\" & hostname & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery _
("Select * from CIM_Datafile Where Extension = 'pst' OR Extension = 'pdf' OR Extension = 'doc' OR Extension = 'xls'")

For Each objFile in colFiles
output.WriteLine hostname & "," & objFile.Name & "," & objFile.FileSize
Next

Else
WScript.Echo line & " no response"
End If
Wend

output.Close
input.Close

Set wmiService = Nothing
Set wmiresults = Nothing

12/04/2006

Hey, Scripting Guy! How Can I Delete All the .BAK Files in a Folder That Are More Than 7 Days Old?:
"dtmDate = Date - 7

strDay = Day(dtmDate)

If Len(strDay) < 2 Then
strDay = '0' & strDay
End If

strMonth = Month(dtmDate)

If Len(strMonth) < 2 Then
strMonth = '0' & strMonth
End If

strYear = Year(dtmDate)

strTargetDate = strYear & strMonth & strDay

strComputer = '.'

Set objWMIService = GetObject('winmgmts:\\' & strComputer & '\root\cimv2')

Set FileList = objWMIService.ExecQuery _
('ASSOCIATORS OF {Win32_Directory.Name='C:\Scripts'} Where ' _
& 'ResultClass = CIM_DataFile')

For Each objFile In FileList
strDate = Left(objFile.CreationDate, 8)
If strDate < strTargetDate Then
If objFile.Extension = 'bak' Then
objFile.Delete
End If
End If
Next"

9/29/2006

Windows::Management


Find how long since you last restarted:
systeminfo | find "Up Time"