IP calculator. Decimal to binary - vbscript

I have ploblem with converting decimal numbers to binary. I want to have space between 8b, but i dont know how to do that in the code.
Function str2bin(strAddress)
'special decimal to binary function
'input 4 octet ip address
'output 32bit binary number
objAddress = Split(strAddress, ".")
For Each strOctet In objAddress
intOctet = CInt (strOctet)
strOctBin = ""
For x = 1 To 8
If intOctet Mod 2 > 0 Then
strOctBin = "1" & strOctBin
Else
strOctBin = "0" & strOctBin
End If
intOctet = Int(intOctet / 2)
Next
str2bin = str2bin & strOctBin
Next
End Function
'-----------------------------------------------------------

Quick and very dirty:
Append a space after each octet:
str2bin = str2bin & strOctBin & " "
and Trim() the return value in the calling code to get rid of the trailing space.
Evidence:
type 28139908.vbs & cscript 28139908.vbs
Option Explicit
Function str2bin(strAddress)
'special decimal to binary function
'input 4 octet ip address
'output 32bit binary number
Dim objAddress, strOctet, intOctet, strOctBin, x
objAddress = Split(strAddress, ".")
For Each strOctet In objAddress
intOctet = CInt (strOctet)
strOctBin = ""
For x = 1 To 8
If intOctet Mod 2 > 0 Then
strOctBin = "1" & strOctBin
Else
strOctBin = "0" & strOctBin
End If
intOctet = Int(intOctet / 2)
Next
str2bin = str2bin & strOctBin & " "
Next
End Function
Dim sIP : sIP = "127.15.32.255"
WScript.Echo sIP, ">" & str2bin(sIP) & "<", ">" & Trim(str2bin(sIP)) & "<"
127.15.32.255 >01111111 00001111 00100000 11111111 < >01111111 00001111 00100000 11111111<

'Subnet Calculator V1
'Script by Chavdarova
'usage cscript VBScriptSubnetCalcV2 > output.txt
'force script to run in cscript mode
Set objShell = CreateObject("WScript.Shell")
If Instr(1, WScript.FullName, "CScript", vbTextCompare) = 0 Then
objShell.Run "%comspec% /k cscript //nologo """ & WScript.ScriptFullName & """", 1, False
WScript.Quit
End If
'a bit of test code to feed a range of addresses into script for testing
' snm="255.255.192.0"
' for iCount=0 to 255
' ip="172.16.17."&iCount
' CalcSubnet ip, snm
' next
strIP=inputbox("Vnesite IP", "Chavdarova Subnet Calc", "172.16.98.53")
strSN=inputbox("Vnesite Subnet Mask", "Chavdarova Subnet Calc", "255.255.224.0")
CalcSubnet strIP, strSN
wscript.quit
----------
function CalcSubnet(strIP,strSNM)
binSNM=str2bin(strSNM)
binIP=str2bin(strIP)
'IP <AND> SN to find Network addresses
for c=32 to 1 step -1
temp=(cint(mid(binIP,c, 1)) and cint(mid(binSNM,c, 1))) & temp
next
netwAdd=temp : temp=""
'IP <OR> SN to find blocks of all "ones" - these addresss are broadcast addresses
for c=32 to 1 step -1
temp=(cint(mid(binIP,c, 1)) or cint(mid(binSNM,c, 1))) & temp
next
bcCheck=temp : temp=""
'Calc 1st. host address in range (Network Address + 1)
ist=binAdd(netwAdd,string(31, "0")&"1")
'Calc Last host address in range (111111...1 - bcCheck + IP - 0...000001)
lst=binSub(string(32,"1"),bcCheck)
lst=binadd(lst,binIP)
lst=binsub(lst,string(31, "0")&"1" )
wscript.echo "IP "&binIP&" "&bin2str(binIP)&vbcrlf&_
"Subnet Mask "&binSNM&" "&bin2str(binSNM)&vbcrlf&_
"Subnet Network "&netwAdd&" "&bin2str(netwAdd)&vbcrlf&_
"Host min "&ist &" "& bin2str(ist) &vbcrlf&_
"Host max "&lst &" "& bin2str(lst) &vbcrlf&_
"Hosts "&binsub(lst,ist) &" "& Bin2Dec(binsub(lst,ist)) &vbcrlf
end function
----------
Function Bin2Dec(strBin)
'Plain old binary to decimal function
result = 0
for intIndex = len(strBin) to 1 step -1
strDigit = mid(strBin, intIndex, 1)
if strDigit = "0" then
'do nothing
elseif strDigit = "1" then
result = result + (2 ^ (len(strBin)-intIndex))
else
Bin2Dec = 0
exit for
end if
next
Bin2Dec = result
End Function
----------
Function bin2str(strBinary)
'special binary to decimal function
'input 32bit binary number
'output 4 octet ip address
For iPosOct = 1 To 4
strOctBin = Right(Left(strBinary, iPosOct * 8), 8)
intOctet = 0
intValue = 1
For iPosBin = 1 To Len(strOctBin)
If Left(Right(strOctBin, iPosBin), 1) = "1" Then
intOctet = intOctet + intValue
end if
intValue = intValue * 2
Next
If bin2str = Empty Then
bin2str = CStr(intOctet)
Else
bin2str = bin2str & "." & CStr(intOctet)
end if
Next
End Function
----------
Function str2bin(strAddress)
'special decimal to binary function
'input 4 octet ip address
'output 32bit binary number
objAddress = Split(strAddress, ".")
For Each strOctet In objAddress
intOctet = CInt (strOctet)
strOctBin = ""
For x = 1 To 8
If intOctet Mod 2 > 0 Then
strOctBin = "1" & strOctBin
Else
strOctBin = "0" & strOctBin
End If
intOctet = Int(intOctet / 2)
Next
str2bin = str2bin & strOctBin & " "
Next
End Function
----------
function binSub(binA,binB)
'subtract one 32bit binary number from another
'binA must be biggest
c=0
for i=32 to 1 step-1
a=cint(mid(binA,i,1))
b=cint(mid(binB,i,1))
if a=0 and b=0 and c=0 then
subt=0 : c=0
elseif a=1 and b=0 and c=0 then
subt=1 : c=0
elseif a=0 and b=1 and c=0 then
subt=1 : c=1
elseif a=1 and b=1 and c=0 then
subt=0 : c=0
elseif a=1 and b=1 and c=1 then
subt=1 : c=1
elseif a=1 and b=0 and c=1 then
subt=0 : c=0
elseif a=0 and b=1 and c=1 then
subt=0 : c=0
elseif a=0 and b=0 and c=1 then
subt=1 : c=1
else
msgbox "This function is only for subtracting 2 32bit binary numbers"
binSub=0 : exit function
end if
total=subt&total
'wscript.echo "a-"&BinA&" "&a&vbcrlf&"b-"&BinB&" "&b&vbcrlf&"subtraction "&subt&vbcrlf&"carry "&
c&vbcrlf&"x-"&total&vbcrlf&cvcrlf
next
if c=1 then
msgbox "Error you are subtracting a larger number from a smaller number"&vbcrlf&binA&vbcrlf&binB
end if
binsub=total
end function
----------
function binAdd(binA,binB)
'add two 32bit binary numbers together
c=0
for i=32 to 1 step-1
a=cint(mid(binA,i,1))
b=cint(mid(binB,i,1))
if a=0 and b=0 and c=0 then
add=0 : c=0
elseif a=1 and b=0 and c=0 then
add=1 : c=0
elseif a=0 and b=1 and c=0 then
add=1 : c=0
elseif a=1 and b=1 and c=0 then
add=0 : c=1
elseif a=1 and b=1 and c=1 then
add=1 : c=1
elseif a=1 and b=0 and c=1 then
add=0 : c=1
elseif a=0 and b=1 and c=1 then
add=0 : c=1
elseif a=0 and b=0 and c=1 then
add=1 : c=0
else
msgbox "Error this function is only for adding 2 32bit binary numbers together"
binAdd=0 : exit function
end if
total=add&total
'wscript.echo "a-"&BinA&" "&a&vbcrlf&"b-"&BinB&" "&b&vbcrlf&"addition "&add&vbcrlf&"carry "& c&vbcrlf&"x-"&total
next
binAdd=total
end function

Related

How to test for function return false?

Can someone tell me what
if(!IsNumeric(aNumber))
{
do something
}
is in valid VBScript? I've tried
!IsNumeric(aNumber)
already.
The logical negation operator is called Not in VBScript:
>> b = 1 = 1
>> WScript.Echo TypeName(b), CStr(b), CStr(Not b)
>>
Boolean True False
>>
2nd sample:
>> For Each e In Split("1 a 2")
>> If Not IsNumeric(e) Then
>> WScript.Echo e, "not a number"
>> Else
>> WScript.Echo e, "a numerical string"
>> End If
>> Next
>>
1 a numerical string
a not a number
2 a numerical string
>>

How to get the modified time of a remote file in batch script

I am trying to get the last modified date of a log file on a remote Windows server 2008/2012 with a batch script.
I am connecting to the machine using "net use", and able to see if the file exists.
net use \\X.X.X.X /user:%USERNAME% %PASSWORD%
if exist "\\X.X.X.X\\C$\\Temp\\LogFiles\\abcd" (
echo ABCD file exists on the server
) else (
echo ABCD file does NOT exist on the server
)
Also, I am able to get the last updated time of a local file using forfiles:
for /f "delims=" %%i in ('"forfiles /m MyLocalAbcd /c "cmd /c echo #file was last modified at #ftime" "') do set modif_time=%%i
echo %modif_time%
However, I am not able to get the modified time of the remote file. I tried to provide the complete path - forfiles /M "\X.X.X.X\C$\Temp\LogFiles\abcd" - or even providing the path to the option P of forfiles, but it is not finding the file.
Is there an easy way to get the modified date/time of the remote file?
Also, I am wondering if there is a way to tail the last n lines of the same file with a Windows built-in command.
Any help is appreciated!
Thanks!
Try a dir.
Or use a for loop differently.
for %%A in (\\server\C$\Temp\LogFiles\abcd) do echo %%~tA
A working example if pasted into a command prompt.
for %A in (\\127.0.0.1\C$\windows\win.ini) do echo %~tA
To the other question you sneeked in
more +50 skips first 50 lines.
This VBScript does what you want.
Set Arg = WScript.Arguments
Set WshShell = createObject("Wscript.Shell")
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout
Set rs = CreateObject("ADODB.Recordset")
With rs
.Fields.Append "LineNumber", 4
.Fields.Append "Txt", 201, 5000
.Open
LineCount = 0
Do Until Inp.AtEndOfStream
LineCount = LineCount + 1
.AddNew
.Fields("LineNumber").value = LineCount
.Fields("Txt").value = Inp.readline
.UpDate
Loop
.Sort = "LineNumber ASC"
If LCase(Arg(1)) = "t" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber < " & LCase(Arg(3)) + 1
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber > " & LCase(Arg(3))
End If
ElseIf LCase(Arg(1)) = "b" then
If LCase(Arg(2)) = "i" then
.filter = "LineNumber > " & LineCount - LCase(Arg(3))
ElseIf LCase(Arg(2)) = "x" then
.filter = "LineNumber < " & LineCount - LCase(Arg(3)) + 1
End If
End If
Do While not .EOF
Outp.writeline .Fields("Txt").Value
.MoveNext
Loop
End With
To use
Filter reads and writes standard in and standard out only. These are only available in a command prompt.
filter <inputfile >outputfile
filter <inputfile | other_command
other_command | filter >outputfile
other_command | filter | other_command
Cut
filter cut {t|b} {i|x} NumOfLines
Cuts the number of lines from the top or bottom of file.
t - top of the file
b - bottom of the file
i - include n lines
x - exclude n lines
Example
filter cut t i 5 < "%systemroot%\win.ini"

VBScript Error code 800A0409, Unterminated string constant, on line 1

I'm getting Error code 800A0409, Unterminated string constant, on line 1, 54 with the code below.
Option Explicit
Dim ObjProgressMsg
Dim fso,objText,strVstup,strVystup,f,dtmVyt,dtmF,dDiff,fName,fExt,fShort,dtmAkt,tx,msgText
Dim strMessage,strWindowTitle,strTemp,wshShell,objTempMessage,strTempVBS
Set fso = CreateObject("Scripting.FileSystemObject")
Set objText = fso.GetFile("l:\bat\posledni.den")
strVstup = "l:\filefolder\"
strVystup = "l:\backup"
dtmVyt = objText.DateLastModified
msgText = "Some text about copying and renaming" & VbCrLf & "files, please wait..."
ProgressMsg msgText
For Each f In fso.GetFolder(strVstup).Files
dtmF = f.DateLastModified
dDiff = DateDiff("s", dtmF, dtmVyt)
If dDiff < 0 Then
ProgressMsg ""
WScript.Echo f
End If
Next
WScript.Echo "Some text about the task being finished."
Function ProgressMsg( strMessage )
' Written by Denis St-Pierre
' Displays a progress message box that the originating script can kill in both 2k and XP
' If StrMessage is blank, take down previous progress message box
' Using 4096 in Msgbox below makes the progress message float on top of things
' CAVEAT: You must have Dim ObjProgressMsg at the top of your script for this to work as described
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strTEMP = wshShell.ExpandEnvironmentStrings( "%TEMP%" )
If strMessage = "" Then
' Disable Error Checking in case objProgressMsg doesn't exists yet
On Error Resume Next
' Kill ProgressMsg
objProgressMsg.Terminate( )
' Re-enable Error Checking
On Error Goto 0
Exit Function
End If
strTempVBS = strTEMP + "\" & "Message.vbs" 'Control File for reboot
' Create Message.vbs, True=overwrite
Set objTempMessage = fso.CreateTextFile( strTempVBS, True )
objTempMessage.WriteLine( "MsgBox""" & strMessage & """, 4096, """ & "a_sp_rano" & """" )
objTempMessage.Close
' Disable Error Checking in case objProgressMsg doesn't exists yet
On Error Resume Next
' Kills the Previous ProgressMsg
objProgressMsg.Terminate( )
' Re-enable Error Checking
On Error Goto 0
' Trigger objProgressMsg and keep an object on it
Set objProgressMsg = WshShell.Exec( "%windir%\system32\wscript.exe " & strTempVBS )
End Function
The script should show a msgbox while searching for files newer than last modified date of posledni.den file. Then once it finds a file it should close msgbox and echo the file it found.
It works just fine if I change this:
msgText = "Some text about copying and renaming" & VbCrLf & "files, please wait..."
to this:
msgText = "Some text about copying and renaming" & "files, please wait..."
Removal of VbCrLf seems to fix that error, just no line break is obviously happening. I can't figure out why it's behaving like that, what am I doing wrong. Every kind of insight on the problem would be much appreciated.
Thank you in advance. :)
The error occurs in the execution of the generated .vbs. What you do is:
>> msg1 = "A" & vbCrLf & "B"
>> code = "MsgBox """ & msg1 & """"
>> WScript.Echo code
>>
MsgBox "A
B"
>> Execute code
>>
Error Number: 1033
Error Description: Unterminated string constant
What you should do:
>> msg1 = """A"" & vbCrLf & ""B"""
>> WScript.Echo msg1
>>
"A" & vbCrLf & "B"
>> code = "MsgBox " & msg1 & ", 4096"
>> WScript.Echo code
>>
MsgBox "A" & vbCrLf & "B", 4096
>> Execute code
>>
>> <-- no news are good news; message displayed

VBScript cut off end of filename after space but keep extension

I've been searching online. Is there a way to cut off the space and the rest of the filename but leave the extension with VBScript.
Say I have a filename like this:
filename this is a file.txt
Could VBScript cut off the space and everything afterwards but leave the extension like this:
filename.txt
Sure, you can do some surgery with the string functions available in vbscript.
dim s
dim s2
s = "filename this is a file.txt"
s2 = Left(s, Instr(s, " ")-1) & Right(s, Len(s) - InstrRev(s, ".") + 1)
msgbox s2
There are several ways to achieve what you want:
Using a regular expression:
Set fso = CreateObject("Scripting.FileSystemObject")
Set re = New RegExp
re.Pattern = "^(\S*).*(\..*?)$"
Set f = fso.GetFile("filename this is a file.txt")
f.Name = re.Replace(f.Name, "$1$2")
Using Split:
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile("filename this is a file.txt")
f.Name = Split(fso.GetBaseName(f))(0) & "." & fso.GetExtensionName(f)
Using string functions: see answer provided by KekuSemau.
Use a RegExp to cut the first 'word' and the extension from your input:
>> Set r = New RegExp
>> r.Pattern = "^(\w+)(.*)(\..*)$"
>> For Each s In Array("filename this is a file.txt", "a.txt", "1a nix ...txt")
>> WScript.Echo s, """" & r.Replace(s, "$1$3") & """"
>> Next
>>
filename this is a file.txt "filename.txt"
a.txt "a.txt"
1a nix ...txt "1a.txt"
If you insist on staying with String ops, use Mid() instead of Right():
>> s = "filename this is a file.txt"
>> a = Left(s, InStr(s, " ") - 1)
>> b = Mid(s, InStrRev(s, "."))
>> WScript.Echo a, b, a & b
>>
filename .txt filename.txt

How to check if Now time lies between a given time in AutoIt

I am trying to check if Now time is between, let's say, 13:00 and 17:00. I don't think the _Datediff function (using _dateadd() and _NowTimeCalc()) will work.
Is there some library function in AutoIt that I am missing? Or do I have to write a manual function comparing #Hour and #min?
I am doing something like this:
Func CheckTime($sStart, $sEnd)
$s = StringSplit($sStart, ":")
$e = StringSplit($sEnd, ":")
$s[1] = Int($s[1])
$s[2] = Int($s[2])
$e[1] = Int($e[1])
$e[2] = Int($e[2])
$result = False
If $s[0] <= 0 And $e <= 0 Then
ConsoleWrite("Wrong Time Format")
Exit
EndIf
If $s[1] <= #HOUR And $e[1] >= #HOUR Then
If #HOUR >= $s[1] And #MIN > $s[2] Then
If #HOUR <= $e[1] And #MIN < $e[2] Then
$result = True
EndIf
EndIf
EndIf
Return $result
EndFunc ; ==>CheckTime
For now works fine when start time < end time, but what I am looking for is some good method instead of manual checks.
Using standard user defined functions (UDFs), you can try using something like this:
#region ;************ Includes ************
#include <Array.au3>
#include <Date.au3>
#endregion ;************ Includes ************
ConsoleWrite(_timeBetween(#HOUR & ':' & #MIN, '10:05', '12:09'))
Func _timeBetween($cTime, $sTime, $eTime)
If Not _DateIsValid('2000/01/01 ' & $cTime) Then Return -1
If Not _DateIsValid('2000/01/01 ' & $sTime) Then Return -2
If Not _DateIsValid('2000/01/01 ' & $eTime) Then Return -3
;~ ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') & #CRLF)
;~ ConsoleWrite(_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') & #CRLF)
If _DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $sTime & ':00') < 0 And _
_DateDiff('s', '2000/01/01 ' & $cTime & ':00', '2000/01/01 ' & $eTime & ':00') > 0 Then
Return 1
Else
Return 0
EndIf
EndFunc ; ==>_timeBetween
A simpler version that works for me - just using string compare in hh:mm format
#include <Date.au3>
Func _timeBetween( $sTime, $eTime)
Return (_NowTime(4) < $eTime) And (_NowTime(4) > $eTime)
EndFunc ; ==>_timeBetween
MsgBox(0, "daytime","is day = " & _timeBetween("08:00"."23:00") )

Resources