Solved

Powershell - detecting file name

Posted on 2013-06-03
9
453 Views
Last Modified: 2013-06-11
Converting an old VBS from SELECT... CASE to a SWITCH for Powershell..

Does not seem to want to work as I would expect..

## -- hourly logs
$files = Get-ChildItem $Logs
foreach ($file in $files)
{
	$FLName = $file.Name
	$FLDate = $file.lastwritetime
	$DT = $file.lastwritetime.ToString("yyyy-MM-dd")
	if (!($DT -eq $nToday))
	{
		$FLName = $file.name
		$FLPath = $file.FullName
		if ($FLName.Contains("-"))
		{
			##$ArrCount = $FLName.Split("-").count
			##$CharacterCount = $FLName.getupperbound($arrCount)
			##if ($CharacterCount -gt 1)
			##{
			switch($FLName)
			{
				HOURLY {
					(!($FLName.contains("server")))
					$HourVar = ""
					Write-Host $FLName
					#aa_server.log.2013-06-02-23
					$DTStart = $FLName.lastindexofany(".log.") + 1
					Write-Host $DTStart
					$DateVar = $FLName.Substring($DTStart, 10)
					Write-Host $DateVar
			} 
				HOURLY {
					(!($FLName.contains("engine")))
					$HourVar = ""
					Write-Host $FLName
					$DTStart = $FLName.lastindexofany(".log.") + 1
					Write-Host $DTStart
					$DateVar = $FLName.Substring($DTStart, 10)
					Write-Host $DateVar
			} 
}

Open in new window


Thanks,

Kent
0
Comment
Question by:Kent Dyer
9 Comments
 
LVL 7

Expert Comment

by:BT15
Comment Utility
just at a glance, your switch statement is looking for the same values both times:

it should be:

switch($FLName)
	{
                  HOURLY { do something}

                  SOMETHINGELSE { do something else}

        }

Open in new window


if you need more information than that, would you mind providing the scope of your project and what the expected results should be?
0
 
LVL 78

Assisted Solution

by:David Johnson, CD, MVP
David Johnson, CD, MVP earned 125 total points
Comment Utility
The second case will not work .. it will find the first HOURLY and then execute it and then exit the switch statement. you were also missing a bunch of close braces

Perhaps changing the switch to engine and server and then inside of each test for hourly


## -- hourly logs
$files = Get-ChildItem $Logs
foreach ($file in $files) {
	$FLName = $file.Name
	$FLDate = $file.lastwritetime
	$DT = $file.lastwritetime.ToString("yyyy-MM-dd")
	if (!($DT -eq $nToday))	{
		$FLName = $file.name
		$FLPath = $file.FullName
		if ($FLName.Contains("-")) {
			##$ArrCount = $FLName.Split("-").count
			##$CharacterCount = $FLName.getupperbound($arrCount)
			##if ($CharacterCount -gt 1)
			##
            {
			switch($FLName) {
				HOURLY {
					(!($FLName.contains("server")))
					$HourVar = ""
					Write-Host $FLName
					#aa_server.log.2013-06-02-23
					$DTStart = $FLName.lastindexofany(".log.") + 1
					Write-Host $DTStart
					$DateVar = $FLName.Substring($DTStart, 10)
					Write-Host $DateVar
			    } 
				HOURLY {
## Filename must contain HOURLY and engine
## this is the second occurance of HOURLY and will never execute
					(!($FLName.contains("engine")))
					$HourVar = ""
					Write-Host $FLName
					$DTStart = $FLName.lastindexofany(".log.") + 1
					Write-Host $DTStart
					$DateVar = $FLName.Substring($DTStart, 10)
					Write-Host $DateVar
		        	} 
                }
            }         
        }  
    }
}    

Open in new window

0
 
LVL 17

Author Comment

by:Kent Dyer
Comment Utility
Basically..  I am trying to convert the following VBS to Powershell..  This works great in VBS..

I have the TomcatLog, Compress, Touch all converted to PowerShell..

Set fso = CreateObject("Scripting.FileSystemObject")
Set WshNetwork = CreateObject("Wscript.Network")
Set objWS = CreateObject("WScript.Shell")
strMachineName = WshNetwork.ComputerName
ScriptDir = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
LogDir = ScriptDir & "logs\"
ZipFolder = "D:\logs\ArchiveTemp\"
ZipFolder2 = "D:\logs\ArchiveTemp\AudForen\"
ZipFolder3 = "D:\logs\ArchiveTemp\Tomcat\"

FolderCheck LogDir
FolderCheck ZipFolder
FolderCheck ZipFolder2
FolderCheck ZipFolder3

FL = ScriptDir & "settings.txt"
Set f1 = fso.OpenTextFile(FL, ForReading, True)
Do Until f1.AtEndOfStream
	line = f1.Readline
	If Split(line, "=") (0)="smtpserver" Then
		smtpserver = Split(line, "=") (1)
	End If
	If Split(line, "=") (0)="FTPLocation" Then
		FTPLocation = Split(line, "=") (1)
	End If
	If Split(line, "=") (0)="DataCenter" Then
		DataCenter = Split(line, "=") (1)
	End If
	If Split(line, "=") (0)="LSFTPAccount" Then
		LSFTPAccount = Split(line, "=") (1)
	End If
	If Split(line, "=") (0)="LSFTPDomain" Then
		LSFTPDomain = Split(line, "=") (1)
	End If
	If Split(line, "=") (0)="AdminRecipient" Then
		AdminRecipient = Split(line, "=") (1)
	End If
Loop
f1.close

' -- Calculate today
MonthStr = Right(100 + Month(Date()), 2)
DayStr = Right(100 + Day(Date()), 2)
YearStr = Year(Date())
nToday = YearStr & "-" & MonthStr & "-" & DayStr

' -- Calculate yesterday
yMonth = Right(100 + Month(Date() - 1), 2)
yDay = Right(100 + Day(Date() - 1), 2)
yYear = Year(Date() - 1)
Yesterday = yMonth & "-" & yDay & "-" & yYear

ResultFile = LogDir & "File_Log_Fix_" & nToday & ".csv"
''LoggerFile = LogDir & nToday & "_result_file.txt"
Set fileOutput = fso.CreateTextFile(ResultFile, True)

nToday = Year(Date()) & "-" & Right(100 + Month(Date()), 2) & "-" & Right(100 + Day(Date()), 2)

TomcatLog TomCatPath,LogLocation,False

' -- TOMCAT LOGS
If fso.folderexists(TomCatPath & "\logs\") Then
	Set objFolder = fso.GetFolder(TomCatPath & "\logs\")
	Set colFiles = objFolder.Files
	For Each objFile In colFiles
		FLName = objFile.Name
		FLDate = objFile.DateLastModified
		DT = Left(Split(FLDate,"/")(2),4) & "-" & Right(100 + Split(FLDate,"/")(0), 2) & "-" & Right(100 + Split(FLDate,"/")(1), 2)
		If DT <> nToday Then
			'If InStr(FLName, "localhost") > 0 Or InStr(FLName, "catalina") > 0 Or InStr(FLName, "manager") > 0 Then
				FLPath = objFile.Path
				FlSize = objFile.Size
				'DT = Split(Split(FLName, ".") (1), "-") (1) & "-" & Split(Split(FLName, ".") (1), "-") (2) & "-" & Split(Split(FLName, ".") (1), "-") (0)
				Logger FLName, DT, FLSize, TtlSize
				compress ZipFolder3 & strMachineName & "-Tomcat-" & DT & "-compressed.zip", FLPath
				Call Touch(ZipFolder3, strMachineName & "-Tomcat-" & DT & "-compressed.zip", DT)
			'End If
		End If
	Next
'Else
'	Mailer server, "The folder: " & TomCatPath & "\logs\ on " & strMachineName & " does not appear to exist"
End If

If fso.folderexists(LogLocation) Then
	' -- HOULRLY LOGS AND AUDIT/FORENSIC LOGS
	' -- ALSO TO SFTP TO VENDOR NIGHTLY
	Set objFolder = fso.GetFolder(LogLocation)
	Set colFiles = objFolder.Files
	For Each objFile In colFiles
		FLName = objFile.Name
		If InStr(FLName, "-") Then
			ArrCount = Split(FLName, "-", -1, 1)
			CharacterCount = UBound(arrCount)
			If CharacterCount > 1 Then
				HourVar=""
				DateVar = Right(FLName,Len(FLName)-InStrRev(FLName,".log.")-4)
				' -- Determine Hourly..
				If Len(DateVar)>10 And InStr(DateVar,".")=0 Then
					HourVar = Right(DateVar,2)
				End If
				DateVar = Left(DateVar,10)
				DTStr = Mid(DateVar,6,2) & "-" & Right(DateVar,2) & "-" & Left(DateVar,4)
				If DateVar <> nToday Then
					FLPath = objFile.Path
					FlSize = objFile.Size
					TtlSize = TtlSize + objFile.Size
					Select Case True
						Case InStr(FLName, "forensic") > 0 Or InStr(FLName, "audit") > 0
							Customer = "COMPANY"
							DateAd = Split(DateAdd("d",1,DTStr),"/")(2) & Right(100 + Split(DateAdd("d",1,DTStr),"/")(0), 2) & Right(100 + Split(DateAdd("d",1,DTStr),"/")(1), 2)
							AuditLogZip = DateAd & "_" & Customer & "_" & strMachineName & "@" & DataCenter & ".zip"
							Logger FLName, DateStr, FLSize, TtlSize
							compress ZipFolder2 & AuditLogZip, FLPath
							Call Touch(ZipFolder2, AuditLogZip, Split(DateAdd("d",1,DTStr),"/")(2) & "-" & Right(100 + Split(DateAdd("d",1,DTStr),"/")(0), 2) & "-" & Right(100 + Split(DateAdd("d",1,DTStr),"/")(1), 2))
						Case InStr(FLName, "re") > 0
							Logger FLName, DateStr, FLSize, TtlSize
							HourlyZip = strMachineName & "-" & DTStr & "-" & HourVar & "-00-00-compressed.zip"
							compress ZipFolder & HourlyZip, FLPath
							Call Touch(ZipFolder, HourlyZip, DateVar)
						Case InStr(FLName, "re")=0 'and HourVar<>""
							If HourVar <> "" Then
								If HourVar > 11 Then
									HourVar = Right(100 + HourVar - 12, 2)
								End If
								Logger FLName, DateStr, FLSize, TtlSize
								HourlyZip = strMachineName & "-" & DTStr & "-" & HourVar & "-00-00-compressed.zip"
								compress ZipFolder & HourlyZip, FLPath
								Call Touch(ZipFolder, HourlyZip, DateVar)
							Else
								Logger FLName, DateStr, FLSize, TtlSize
								TomCatZip = strMachineName & "-Tomcat-" & DTStr & "-compressed.zip"
								compress ZipFolder3 & TomCatZip, FLPath
								Call Touch(ZipFolder3, TomCatZip, DateVar)
							End If
					End Select
				End If
			End If
		End If
	Next
	If fso.fileexists(ZipFolder2 & AuditLogZip) Then
		FTPFile ZipFolder2 & AuditLogZip
	End If
Else
	Mailer smtpserver, "The folder: " & LogLocation & " on " & strMachineName & " does not appear to exist"
End If

Sub compress(ZipFile, FileToCompress)
	Dim strZip, intReturn, strCommand
	'strZip = ScriptDir & "7za.exe"
	strZip = "C:\Program Files\WinZip\WZZip.exe"
	If InStr(strZip,"WinZip") Then
		strCommand = fso.GetFile(strZip).ShortPath & " -m """ & ZipFile & """ """ & FileToCompress & """"
		intReturn = objWS.Run(strCommand, 0, True)
	End If
	If InStr(strZip,"7z") Then
		strCommand = fso.GetFile(strZip).ShortPath & " """ & ZipFile & """ """ & FileToCompress & """"
		intReturn = objWS.Run(strCommand, 0, True)
		If intReturn = 0 Then
		    fso.deleteFile FileToCompress
		End If
	End If
End Sub

Sub FolderCheck(folder)
	If Not fso.FolderExists(folder) Then
		fso.CreateFolder(folder)
	End If
End Sub

Sub Logger(FLName, DateStr, FLSize, TtlSize)
	Dim strToWrite
	strToWrite = objFolder & "," & Chr(34) & FLName & Chr(34)
	strToWrite = strToWrite & "," & Chr(34) & DateStr & Chr(34)
	strToWrite = strToWrite & "," & Chr(34) & FormatNumber(FLSize, 0) & Chr(34)
	strToWrite = strToWrite & "," & Chr(34) & FormatNumber(TtlSize, 0) & Chr(34)
	'strToWrite = strToWrite & "," & Date - CDate(MonthVar & "/" & DayVar & "/" & YearVar)
	fileOutput.WriteLine strToWrite
End Sub

Sub Mailer(mailresulttxt, subject)
	Dim recipient, from, body, strCommand, oExec
	recipient = AdminRecipient
	from = AdminRecipient
	strCommand = ScriptDir & "Blat.exe"
	strCommand = strCommand & " -log " & ScriptDir & "resultlog.txt"
	strCommand = strCommand & " -f " & Chr(34) & from & Chr(34) & ""
	strCommand = strCommand & " -to " & Chr(34) & recipient & Chr(34) & ""
	strCommand = strCommand & " -server " & Chr(34) & smtpserver & Chr(34) & ""
	strCommand = strCommand & " -subject " & Chr(34) & subject & Chr(34) & ""
	If fso.fileexists(mailresulttxt) Then
		strCommand = strCommand & " -bodyF " & Chr(34) & mailresulttxt & Chr(34) & ""
	Else
		strCommand = strCommand & " -body ""Transmission Log does not exist"""
	End If
	strCommand = strCommand & " -q"
	Set oExec = objWS.Exec(strCommand)
	While Not oExec.Status = 0
		WScript.Sleep 10
	Wend
End Sub

Sub TomcatLog(TomcatPath,LogLocation,file)
	Dim f1
	Dim FL
	Dim iRC
	Dim iRC2
	Dim line
	Dim LogPath
	Dim oReg
	Dim objWMIService
	Dim strQuery
	Dim colServices
	Dim objService
	Dim colServicesTest
	Dim objServiceTest
	Dim sBaseKey
	Dim sComp
	Dim Separator
	Dim Service
	Dim Serverxml
	Dim sxml
	Dim sValue
	Dim sValue2
	Dim TomcatVer
	
	sComp = "."
	Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
	sComp & "/root/default:StdRegProv")
	sBaseKey = "SYSTEM\CurrentControlSet\services\"
	Set objWMIService = GetObject("winmgmts:\\" & sComp & "\root\CIMV2")
	strQuery = "SELECT * FROM Win32_Service  where name like '%Tomcat%'"
	Set colServices = objWMIService.ExecQuery(strQuery, "WQL", 48)
	For Each objService In colServices
		Set colServicesTest = objWMIService.ExecQuery(strQuery, "WQL", 48)
		For Each objServiceTest In colServicesTest
			Service = objServiceTest.Name
		Next
	Next

	iRC = oReg.GetStringValue(HKLM, sBaseKey & Service, "Description", sValue)
	iRC2 = oReg.GetExpandedStringValue(HKLM, sBaseKey & Service, "ImagePath", sValue2)
	TomcatVer = Left(Split(sValue," ")(2),3)
	TomcatPath = Replace(Left(sValue2,InStr(sValue2,"\bin\")-1),Chr(34),"")

	Serverxml = TomcatPath & "\conf\server.xml"
	Set sxml = fso.OpenTextFile(Serverxml, ForReading, True)
	Do Until sxml.AtEndOfStream
		line = sxml.Readline
		If InStr(line, "appBase") Then
			LogPath = Split(line, "=") (1)
			LogPath = Replace(Split(LogPath, " ") (0), Chr(34), "")
			FL = LogPath & "\pmws_server\WEB-INF\classes\log4j.properties"
			If TomCatVer = "6.0" Then
				LogPath = TomcatPath & "\webapps\AppServer"
				FL = LogPath & "\WEB-INF\classes\log4j.properties"
			End If
		End If
	Loop

	Set f1 = fso.OpenTextFile(FL, ForReading, True)
	Do Until f1.AtEndOfStream
		line = f1.Readline
		If InStr(line, "log4j.appender.LOGFILE.File") Then
			LogPath = Split(line, "=") (1)
			Select Case True
				Case InStrRev(LogPath, "\\") > 0
				Separator = "\\"
			Case InStrRev(LogPath, "/") > 0
				Separator = "/"
			End Select
			If file Then
				'To Show: D:\logs\aa_server.log
				LogLocation = Trim(Replace(LogPath ,Separator,"\"))
			Else
				'To Show: D:\logs\
				LogLocation = Trim(Replace(Left(LogPath, InStrRev(LogPath, Separator)),Separator,"\"))
			End If
		End If
	Loop
	f1.close
End Sub

' -- Re-date files
'    Call Touch(Server.MapPath("/"), "somefile.htm", "2005-09-01") 
'    Call Touch("C:\", "somefile.txt", "2012-01-01") 
Sub Touch(strDir, strFileName, NewDate)
	Dim objShell, objFolder, objFile
	Set objShell = CreateObject("Shell.Application") 
	Set objFolder = objShell.NameSpace(strDir) 
	Set objFile = objFolder.ParseName(strFileName) 
	If fso.FileExists(strDir & strFileName) Then
		objFile.ModifyDate = NewDate 
	End If
End Sub

Open in new window


Thanks,

Kent
0
 
LVL 39

Assisted Solution

by:footech
footech earned 375 total points
Comment Utility
Actually with a switch statement you can have multiple matches (even the same match listed multiple times), and the scriptblock associated with each one will run unless you have a break statement in the scriptblock.  Take a look at the output from running a couple simple examples.
$FLName = "hourly"
switch($FLName)
{
	HOURLY {"case1"}
	HOURLY {"case2"}
}

Open in new window

$FLName = "hourly"
switch($FLName)
{
	HOURLY {"case1";break}
	HOURLY {"case2";break}
}

Open in new window


Perhaps someone else here can just glance at your VBScript and know what section you're talking about and what it's supposed to do, but I'm not not that good with VBScript.  Can you explain it in words?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 17

Author Comment

by:Kent Dyer
Comment Utility
OK..  Let's focus on the troublesome area..  All of these are being generated by Apache Tomcat web services.
Apache Tomcat logs are OK..

Detection part is:
We have some Audit/Forensic logs that need to be detected and archived to be both stored and sent to a vendor via SFTP..
files to contain in the audit/forensic file are the following two files:
server.audit.log.2013-05-28
server.forensic.log.2013-05-28

Note: in the vbs, I have the DateAd varable that takes this date: 2013-05-28 and adds one day to it..
File name to be transmitted is: 20130529_COMPANY_SERVER@DATACENTER.zip
Where:
20130529 Date of the file
COMPANY Name of the company this coming from
SERVER - Server Name
DATACENTER - Which data center is this coming from?
zip - zip file

To do and I can come back to this: We have some Billing logs that need to be detected and archived to be both stored and sent to a vendor via SFTP..

We have hourly logs that are needing to be detected (note: the greater than 10 Hour detection in the VBS file), archived (zipped), and stored if they are not today's logs.
Files to be stored are:
server.log.2013-05-29-02
server.log.2013-05-29-14

In the VBS file, it stores these  log files as for example: SERVER-05-29-2013-02-00-00-compressed.zip where:
SERVER is server name
05-29-2013-02-00-00 is date: 05-29-2013 and 02 is the hour between 00-12
in this example, the files 02 and 14 are stored within

We then have miscellaneous files that needing to be archived and stored as well.  In VBS, you can do this with a CASE ELSE..

HTH,

Kent
0
 
LVL 39

Accepted Solution

by:
footech earned 375 total points
Comment Utility
Sounds like you are asking for how to detect the correct files, and then also how to construct a name for the .ZIP file from the names of the files.  Is that right?

For the detection part something like the below should give you a match.
$somefolder = "d:\folder"
$date = Get-Date -format yyyy-MM-dd
$files = Get-ChildItem $somefolder | Where { $_.Name -match "server\.(audit|forensic)\.log\.$date" }

Open in new window

This matches against the example file names you gave.
server.audit.log.2013-05-28
server.forensic.log.2013-05-28
But I'm unclear as to whether you meant for "server" in the file name to be static, or does this vary?  If the matching above isn't working for you, can explain further what criteria you want to use to find matching files?

For the .ZIP file name construction, does the "SERVER" portion come from the file name, or is it static?
$company = "COMPANY"
$server = "SERVER"
$datacenter = "DATACENTER"
$zipname = "{0:yyyyMMdd}_{1}_{2}@{3}.zip" -f (Get-Date($date)).AddDays(1),$company,$server,$datacenter

Open in new window

0
 
LVL 17

Author Comment

by:Kent Dyer
Comment Utility
OK..  Getting closer..  I need to spend some more time on this..

@footech - I had somewhat figured out the logic you had placed in your response before this.

Please note: This still has remnants of VBS in the script file..  Also, there is a fair-sized portion that is commented out.  I think I am pretty close getting this completed.

# -- SCRIPT TO ZIP UP DAILY, HOURLY LOGS
# -- 2013-06-01
# -- AUTHOR: KENT DYER
# --
# -- PROCESS FLOW
# -- [1] Declare variables
# -- (2) Calculate Today, Yesterday, etc.
# -- (3) Read in settings for smtp server, IP, ftp address
# -- (4) Determine in system registry: HKLM\SOFTWARE\Apache Software Foundation\Tomcat
# --     (a) Tomcat Path/Location
# --     (b) Tomcat Version
# -- (5) Read Location from Tomcat: e.g. "C:\tomcat\conf\server.xml"
# --     (a) Locate: "appBase" and parse out where AdaptiveAuthentication is located
# --     (b) e.g. C:\tomcat\webapps\AdaptiveAuthentication
# -- (6) Read the log4j.properties file: "log4j.appender.LOGFILE.File"
# --     (a) e.g D:\logs\logs
# -- (7) Zip up Tomcat logs: e.g. c:\tomcat\logs
# -- (8) looking at the folder where the hourly logs, Audit, and Forensic files are located
# -- (9) Placing priority on Audit and Forensic files, zip up previous days files
# --     (a) Transmit via SFTP the Audit/Forensic files to be sent to the internal SFTP Server and
# --        ) { to Vendor via SFTP for nightly processing into report files for the respective FIs
# -- (10) Zip up previous days hourly logs
# -- (11) Take remaining files and zip up logs

$strMachineName = gc env:computername

$ScriptDir = Split-Path $MyInvocation.MyCommand.Path

. ( Join-Path $ScriptDir tomcat.ps1 )
##. ( Join-Path $ScriptDir zip.ps1 )
##. ( Join-Path $ScriptDir testlock.ps1 )

$returnvalue = TomcatLog
$tomcatPath = $returnvalue[0]  # TomcatPath e.g. D:\tomcat
$LogLocation = #$returnvalue[2]  # Tomcat LogDir, e.g. d:\logs\

$LogDir = $ScriptDir + "logs\"
$ZipFolder = "D:\logs\ArchiveTemp\"
$ZipFolder2 = "D:\logs\ArchiveTemp\AudForen\"
$ZipFolder3 = "D:\logs\ArchiveTemp\Tomcat\"

function compress($zipfile, $fullname, $DTNew){
	$fileExe = 'D:\WORK\SCRIPTS\7za.exe '
	$switches = 'a'
	& $fileExe $switches $zipfile $fullname
	if (Test-Path $zipfile)
	{
	#	(dir $zipfile).lastwritetime = $DTNew
} 
}

function FolderCheck($folder)
{
	if (!(Test-Path -Path $folder))
	{
		New-Item -ItemType directory -Path $folder
} }
	
function FTPFile($ZipFile)
{
	##1 SFTP the latest.zip from the server
	#$fileExe = 'D:\WORK\SCRIPTS\winscp.exe'
	#$GetFile = 'D:\WORK\SCRIPTS\p1\get_file.txt'
	#& $fileExe / script = $GetFile
											
	#	if (Test-Path -Path $ZipFile) {
	#		$LoggerFile = $LogDir + $nToday + "_result_file.txt"
	#		$fileOutput = $fso.CreateTextFile($LoggerFile, True)
	#		$ResultFileSend = $ScriptDir + "send_file.txt"
	#		$fileOutput2 = fso.CreateTextFile($ResultFileSend, True)
	#		$exeResultFile = $LogDir + $nToday + "_exeresult_file.txt"
	#		$mailresult = $ScriptDir + "mail_result.bat"
	#		$fileOutput3 = fso.CreateTextFile($mailresult, True)
	#		$mailresulttxt = $LogDir + $nToday + "_mailresult.txt"
	#		                                
	#		$fileOutput2.WriteLine "option batch abort"
	#		$fileOutput2.WriteLine "option confirm off"
	#		$fileOutput2.WriteLine "open " + $LSFTPAccount
	#		$fileOutput2.WriteLine "binary"
	#		$fileOutput2.WriteLine "put " + Chr(34) + $ZipFile + Chr(34) + " " + $FTPLocation
	#		$fileOutput2.WriteLine "exit"
	#		$fileOutput2.close
	#		$fileOutput.WriteLine "send_file.txt creation is complete"
	#		$iResult = objWS.Run($ScriptDir + "send_file.bat > " + $exeResultFile, 0, "true")
	#		Start-Sleep -m 300
	#		$fileOutput.WriteLine $iResult
	#		$fileOutput.close
	#		                                
	#		$fileOutput3.WriteLine "echo CONTENTS OF THE FTP " + $ScriptDir + "send_file.txt > " + $mailresulttxt
	#		$fileOutput3.WriteLine "echo.>> " + $mailresulttxt
	#		$fileOutput3.WriteLine "type " + $ScriptDir + "send_file.txt >> " + $mailresulttxt
	#		$fileOutput3.WriteLine "type " + $ScriptDir + "separator.txt >> " + $mailresulttxt
	#		$fileOutput3.WriteLine "echo RUNNING RESULTS OF THE FTP BATCH FILE >> " + $mailresulttxt
	#		$fileOutput3.WriteLine "type " + $exeResultFile + " >> " + $mailresulttxt
	#		$fileOutput3.close
	#		$iResult = objWS.Run($mailresult, 0, "true")
	#		                                
	#		if (Test-Path -Path $exeResultFile) {
	#			$r = fso.OpenTextFile($exeResultFile, $ForReading, True)
	#			do until $r.AtEndOfStream
	#				$line = $line + $r.Readline
	#			Loop
	#			if ($line.contains("KiB")) {
	#                Send-MailMessage -To $AdminRecipient -From $AdminRecipient -subject "Send file to Vendor Report from: " + $strMachineName -smtpServer $server
	#			}
	#		} else {
	#            Send-MailMessage -To $AdminRecipient -From $AdminRecipient -subject "Send file to Vendor Report from: " + $strMachineName -smtpServer $server
	#		}
	#	} else {
	#        Send-MailMessage -To $AdminRecipient -From $AdminRecipient -subject "Cannot SFTP the file: " + $ZipFile + " on " + $strMachineName + " as the file does not appear to exist" -smtpServer $server
	#	}
}
	
$returnvalue = TomcatLog
$tomcatPath = $returnvalue[0]  # TomcatPath
##$returnvalue[1]  # LogPath
$LogLocation = $returnvalue[2]  # LogDir
	
# -- Re-date files
#    Call Touch(Server.MapPath("/"), "somefile.htm", "2005-09-01") 
#    Call Touch("C:\", "somefile.txt", "2012-01-01") 
function Touch($strFileName, $DTNew)
{
	(dir $strFileName).lastwritetime = $DTNew
}

FolderCheck $LogDir
FolderCheck $ZipFolder
FolderCheck $ZipFolder2
FolderCheck $ZipFolder3

$fl = $ScriptDir + "\settings.txt"
$lines = Get-Content $fl -encoding String
foreach ($line in $lines)
{
									
	###="smtpserver"
	if ($line.Split("=")[0] -eq 'smtpserver')
	{
		$server = $line.Split("=")[1]
	}
	if ($line.Split("=")[0] -eq 'FTPLocation')
	{
		$FTPLocation = $line.Split("=")[1]
	}
	if ($line.Split("=")[0] -eq 'DataCenter')
	{
		$DataCenter = $line.Split("=")[1]
	}
	if ($line.Split("=")[0] -eq 'LSFTPAccount')
	{
		$LSFTPAccount = $line.Split("=")[1]
	}
	if ($line.Split("=")[0] -eq 'LSFTPDomain')
	{
		$LSFTPDomain = $line.Split("=")[1]
	}
	if ($line.Split("=")[0] -eq 'AdminRecipient')
	{
		$AdminRecipient = $line.Split("=")[1]
	}
	if ($line.Split("=")[0] -eq "Customer")
	{
		$Customer = $line.Split("=")[1]
	}
}

# -- Calculate today
$FullDate = Get-Date -format u
$nToday = $FullDate.substring(0, 10)
$sysDateVar = $nToday.replace("-", "")

# -- Calculate yesterday
$Yesterday = ((Get-Date).AddDays(-1 )).ToString("yyyy-MM-dd")
$Yesterday = $Yesterday.substring(0, 10)

$ResultFile = $LogDir + "File_Log_Fix_" + $nToday + ".csv"
$BackUpPath = $ScriptDir + "p1\Backup\"
##$ZipFile = $BackUpPath + $sysDateVar + "_" + $Customer + "_" + $strMachineName + "@" + $DataCenter + ".zip"

# -- TOMCAT LOGS
if (Test-Path -Path $tomcatPath\logs\)
{
	$files = Get-ChildItem -Path $tomcatPath\logs | Where { $_.Name -contains "(localhost|catalina|catalina)" }
	foreach ($file in $files)
	{
		$FLName = $file.Name
		$FLPath = $file.FullName
		$FLDate = ($file.lastwritetime).ToString("MM-dd-yyyy")
		$DT = ($file.lastwritetime).ToString("yyyy-MM-dd")
		$zipfile = $ZipFolder3 + $strMachineName + "-Tomcat-" + $DT + "-compressed.zip"
		if ($DT -ne $nToday)
		{
			compress $zipfile, $FLPath, $DT
		}
} }
else
{
	Send-MailMessage -To $AdminRecipient -From $AdminRecipient -subject "The folder: " + $TomCatPath + "\logs\ on " + $strMachineName + " does not appear to exist" -smtpServer $server
}
	
if (Test-Path -Path $LogLocation)
{
	# -- HOULRLY LOGS AND AUDIT/FORENSIC LOGS
	# -- ALSO TO SFTP TO NIGHTLY
	$files = Get-ChildItem $LogLocation
	foreach ($file in $files)
	{
		$FLName = $file.Name
		$FLPath = $file.FullName
		#$strMatch = Select-String -Path $FLPath -pattern "-"
		#if ($strMatch)
		#{
		$CharacterCount = [regex]::matches($FLName, "-").count
		if ($CharacterCount -gt 1)
		{
			$Pos = $FLName.LastIndexofAny(".log.")-4
			$len = $FLName.Length
			$DateVar = $FLName.Substring($pos, $Len-$pos)
			$YearVar = $FLName.Split("-")[0]
			$YearVar = $YearVar.Substring($YearVar.Length-4, 4)
			$MonthVar = $FLName.Split("-")[1]
			$DayVar = $FLName.Split("-")[2]
			$DateVar = $YearVar + "-" + $MonthVar + "-" + $DayVar
			$DTStr = $MonthVar + "-" + $DayVar + "-" + $YearVar
			if ($DateVar -ne $nToday)
			{
				$FlSize = $file.Size
				$TtlSize = $TtlSize + $file.Size
				$Types = 'forensic', 'audit'
				if ($FLName | Where-Object { $_.Name -match $Types })
				{
					$DTStr = $DTStr.ToString("MM-dd-yyyy hh:mm:ss")
					$DAdd = $DTStr.AddDays(1)
					$DateAd = $DAdd.Split("-")[2] + $DAdd.Split("-")[0] + $DAdd.Split("-")[1]
					$AuditLogZip = $ZipFolder2 + $DateAd + "_" + $Customer + "_" + $strMachineName + "@" + $DataCenter + ".zip"
					#Logger $FLName, $DateStr, $FlSize, $TtlSize
					compress $AuditLogZip, $FLPath, $DateAd
				}
				##$HourVar = -null
				if ($CharacterCount -gt 2 -and !{ $_.name -contains "(aa_re)" })
				{
					$HourVar = $FLName.Split("-")[3]
					$HourVar = $HourVar - 12
					##Logger $FLName, $DateStr, $FlSize, $TtlSize
					HourlyZip = $ZipFolder + $strMachineName + "-" + $DTStr + "-" + $HourVar + "-00-00-compressed.zip"
					compress $HourlyZip, $FLPath, $DTStr
					#Touch $HourlyZip, $DateVar
				}
				else
				{
					##$Logger $FLName, $DateStr, $FlSize, $TtlSize
					$TomCatZip = $ZipFolder3 + $strMachineName + "-Tomcat-" + $DTStr + "-compressed.zip"
					compress $TomCatZip, $FLPath, $DTStr
					#Touch $TomCatZip, $DateVar
				} 
			}
			#if (Test-Path -Path $AuditLogZip)
			#{
			#	FTPFile $AuditLogZip
			#}
		}
		#}
	}
}
else
{
	Send-MailMessage -To $AdminRecipient -From $AdminRecipient -subject "The folder: " + $LogLocation + " on " + $strMachineName + " does not appear to exist" -smtpServer $server
}  
	
#strPath = "D:\vendor\bo_logs"
#if (Test-Path -Path strPath) {
#	$DataList = CreateObject("ADODB.Recordset")
#	$DataList.Fields.Append "strFileName", 200, 255 # adVarChar
#	$DataList.Fields.Append "strFileSize", 3, 4 # adInteger
#	$DataList.Fields.Append "strFileDate", 7 # adDate
#	$DataList.Open
#	                                
#	$objFolder = fso.GetFolder(strPath)
#	#For each objFile in objFolder.Files
#		$DataList.AddNew
#		$DataList("strFileName") = objFile.Name
#		$DataList("strFileName") = objFile.Path
#		$DataList("strFileSize") = Int(objFile.Size / 1000)
#		if (DataList("strFileSize") = 0) { DataList("strFileSize") = 1
#		$DataList("strFileDate") = objFile.DateLastModified
#		$DataList.Update
#	#next
#	$DataList.Sort = "strFile" + "Date"
#	$DataList.Sort = "strFileDate"
#	$DataList.MoveFirst
#	Do Until DataList.EOF
#		if (FormatDateTime(DataList.Fields.Item("strFileDate"), 2) <> FormatDateTime(Now(), 2)) {
#			$strFile = DataList.Fields.Item("strFileName")
#			$strFileLG = Len(strFile)
#			$intPadding = 15 - strFileLG
#			$DateStr = Year(DataList.Fields.Item("strFileDate")) _
#			+ "-" + Right(100 + Month(DataList.Fields.Item("strFileDate")), 2) _
#			+ "-" + Right(100 + Day(DataList.Fields.Item("strFileDate")), 2)
#			$ZipName = ZipFolder + "bo_logs_" + DateStr + ".zip"
#			compress $ZipName, $strFile
#			Touch fso.GetParentFolderName($ZipName) + "\", "bo_logs_" + $DateStr + ".zip", $DateStr
#		}
#		$DataList.Move#next
#	Loop
#	$DataList.Close
#	$DataList = $Nothing
#objWS = $Nothing
	
#if (!(Test-Path -Path $ResultFile))
#{
#	Send-MailMessage -To $AdminRecipient -From $AdminRecipient -subject "There has been an issue with file archiving on "$strMachineName -smtpServer $server
#}

Open in new window


Thanks for your help!

Kent
0
 
LVL 39

Assisted Solution

by:footech
footech earned 375 total points
Comment Utility
Thanks for the update.  However if there are answers to the questions I posed or some more explanation of what you're looking for, I'm missing it.  Is there an issue related to your original question that you're still looking for help on?

I haven't gone through your code line by line, but I'm quite sure that line 231 won't do what you want it to. $FLName is already the file name, then you're trying to call the name property (for which there won't be one since it's just a string), and then trying the -match against values in an array (that type of syntax won't work).  Just a couple options - either pipe $Types to a foreach-object to handle each element in the array, or construct the regex pattern to match any of the elements.

Just some general observations - there sure are a lot of variables, and splitting and concatenating of strings.  Using some different methods I think you could optimize quite a bit.
0
 
LVL 17

Author Closing Comment

by:Kent Dyer
Comment Utility
Couple of comments..  I like the two final comments from @footech - I think I need to "take the elephant" and:
* I am a firm believer that PowerShell will trim down the VBS script
* Break it into bite-sized chunks
* Use variables instead of constructing them
*Leverage log4j.properties / server.xml to get system settings

Thanks for the help and feedback.  Awesome stuff!

Kent
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

The article will show you how you can maintain a simple logfile of all Startup and Shutdown events on Windows servers and desktops with PowerShell. The script can be easily adapted into doing more like gracefully silencing/updating your monitoring s…
A procedure for exporting installed hotfix details of remote computers using powershell
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now