Win OS :- Remove Temporary Internet Files

Background

Wanted to remove left behind temporary Internet files.

Folder Stats

C:\Users

WinDirStat

Images

Image – WinDirStat

winDirStat.20181218.0249PM.PNG

Explanation
  1. 16 GB

Windows Explorer

Images

Image – Windows Explorer

folderExplorer.TemporaryInternetFiles.20181218.0228PM.PNG

Explanation
  1. 15.9 GB

Script

Script- Dos/Batch

@echo off

rem *************************************************************************************************

    rem https://community.f-secure.com/t5/Common-topics/Cleaning-temporary-Internet/ta-p/18280

    rem In Windows XP, the folder is located here:

        rem C:\Documents and Settings\\Local Settings\Temporary Internet Files\Content.IE5
        rem Note: If you only have one user account on Windows XP, use Administrator as the username.

    rem In Windows Vista and 7, the folder is located here:

        rem C:\Users\\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5
        rem C:\Users\\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low\Content.IE5

    rem In Windows 8 and 8.1, the folder is located here:
        rem C:\Users\\AppData\Local\Microsoft\Windows\INetCache

    rem *************************************************************************************************

setlocal enabledelayedexpansion

IF "%OS%"=="" GOTO WIN9X

REM Clear Local Variables
rem set "_folderSuffix="
rem set "_folderLowSuffix="

set _folderSuffix=
set _folderLowSuffix=

if exist "%SystemDrive%\Users\%username%\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5"  (

	set "_folderSuffix=AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5"
	set "_folderLowSuffix=AppData\Local\Microsoft\Windows\Temporary Internet Files\Low\Content.IE5"

)

if exist "%SystemDrive%\Users\%username%\AppData\Local\Microsoft\Windows\INetCache"  (

	set "_folderSuffix=AppData\Local\Microsoft\Windows\INetCache"

)

set "_users=%SystemDrive%\Users"

FOR /D %%F in ("%_users%\*") do (

     set _folder=%%F

     set "_folderContent=%%F\%_folderSuffix%"    

	 if not "%_folderLowSuffix%"=="" (
		set "_folderLowContent=%%F\%_folderLowSuffix%"

		)

     echo Folder Base is !_folder!

     echo Folder Content Regular is !_folderContent!

     dir "!_folderContent!"\* /s 2>nul | find /v /c "::"

     if exist "!%_folderLowContent%" (

		echo Folder Content Low is !_folderLowContent!

		dir "!_folderLowContent!"\* /s 2>nul | find /v /c "::"

	)		

     echo *******************************************************************

     rem dir
     if "%1"=="dir" dir "!_folderContent!"\* /s /Q 2>nul 

     if exist "%%F\%_folderLowSuffix%" (

		if "%1"=="dir" dir "!_folderLowContent!"\* /s /Q 2>nul      

	 )		

     rem del
     if "%1"=="del" del "!_folderContent!"\* /s /Q 2>nul 

     if exist "%%F\%_folderLowSuffix%" (

		if "%1"=="del" del "!_folderLowContent!"\* /s /Q 2>nul      

	)	

)

:GOTO END

:WIN9X

REM - WIN9X systems are currently not supported.

:END

endlocal

Source Code Control

GitHub

DanielAdeniji/winOSInternetTempfilesCleanup
Link

 

Scheduled Task – Xcopy does not copy file

Background

We have a scheduled script that was not working as new files were not being copied over.

But, also there were no errors logged.

 

Script – Backup

Here is what the original script looks like.

Script – Backup ( Original )


set "app=xcopy"

set "_HOME_DIR=%CD%"

set "_DATABASE=DBBackup"
set "_srcFolder=\\DBPROD\SQLBackups\%_DATABASE%\%_DATABASE%.bak"
set "_destFolder=F:\Microsoft\SQLServer\SQLRestore"

@rem if Folder Log does not exist, please create it
if not exist log mkdir log

@rem Initiate xcopy
%app% %_srcFolder% %_destFolder% /D /Y /J


Script – Backup ( Revision )

Added code to capture and expose ERRORLEVEL.


set "app=xcopy"
set "_DATABASE=HRDB"
set "_srcFolder=\\DBPROD\SQLBackups\%_DATABASE%\%_DATABASE%.bak"
set "_destFolder=F:\Microsoft\SQLServer\SQLRestore"

@rem if Folder Log does not exist, please create it
if not exist log mkdir log

@rem Initiate xcopy
%app% %_srcFolder% %_destFolder% /D /Y /J

set _errLevel=%errorlevel%

if _errLevel neq 0 (
	echo _errLevel %_errLevel% 
	echo ErrorLevel %errorLevel% 
	exit /b %_errLevel%		 
)	

Output

Image

xcopyDoesNotCopyNewFiles

Text


D:\Scripts\RestoreDB>xcopy \\DBPROD\SQLBackups\HRDB\HRDB.bak F:\Microsoft\SQLServer\SQLRestore /D /Y /J
\\DBPROD\SQLBackups\HRDB\HRDB.bak
Sharing violation

D:\Scripts\RestoreDB>set _errLevel=4

D:\Scripts\RestoreDB>if _errLevel NEQ 0 (
echo _errLevel 4
 echo ErrorLevel 0
 exit /b 4
)
_errLevel 4
ErrorLevel 0

D:\Scripts\RestoreDB>set _errLevel=4

D:\Scripts\RestoreDB>if _errLevel NEQ 0 (
echo restoreDB_DBBackup::_errLevel 4
 echo restoreDB_DBBackup::ErrorLevel 0
 exit /b 4
)


Image

We are experiencing a sharing violation.

Diagnostics

Who is using the file?

Resource Monitor

In use files

RestoreMonitor-InuseFiles

 

SQL Server

sp_whoIsActive

sp_whoIsActive

 

sys.dm_exec_requests

Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?
Answered By – Veldmuis
Link

Code


SELECT 
		 r.session_id
		,r.command
		,[Percent Complete]
			= CONVERT(NUMERIC(6,2),r.percent_complete)
		, [ETA Completion Time]
			= CONVERT(VARCHAR(20),DATEADD(ms,r.estimated_completion_time,GetDate()),20) 
		, [Elapsed Min]
			= CONVERT(NUMERIC(10,2),r.total_elapsed_time/1000.0/60.0) 
		, [ETA Min]
			= CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0) 
		, [ETA Hours]
			= CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0/60.0) 
		, [sqlText]
			= CONVERT(VARCHAR(1000)
				,(
					SELECT SUBSTRING(text,r.statement_start_offset/2,
						CASE WHEN r.statement_end_offset = -1 THEN 1000 ELSE (r.statement_end_offset-r.statement_start_offset)/2 END)
						FROM sys.dm_exec_sql_text(sql_handle))
				  )
FROM sys.dm_exec_requests r 
WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')

 

Output

sys-dm-exec-requests

Summary

Our problem is that a prior run has the file we are trying to copy via xcopy locked.

We can wait for the database restore to complete, or terminate it.

Also, xcopy with /D works fine … just make sure that you check the ERRORLEVEL.

 

DOS – Batch File – Error – The Syntax of the command is incorrect.

Background

Sometimes when running batch file, one will get the error pasted below.

The syntax of the command is incorrect.

Code

Acknowledgement

Here is stolen code for getting timestamp.

Code


@ECHO OFF
REM http://snipplr.com/view/21573/print-datetime-in-dos-batch-file/
set _LOGFILE_DATE=%DATE:~10,4%_%DATE:~4,2%_%DATE:~7,2%
set _LOGFILE_TIME=%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%
set _LOGFILE=log-%_LOGFILE_DATE%-%_LOGFILE_TIME%.log

set _currentFolder=%cd%
set _logFolder=%_currentFolder%\log
set _logFileFull="%_logFolder%\%_LOGFILE%"
set _logApp="D:\Program Files (x86)\GnuWin32\bin\tee.exe"

if not exist %_logFolder%(
	mkdir %_logFolder%
)

 

Diagnosis

To determine the erroring line, we need to set “ECHO ON“.

 

Code – Turn Echo ON


@ECHO ON
REM http://snipplr.com/view/21573/print-datetime-in-dos-batch-file/
set _LOGFILE_DATE=%DATE:~10,4%_%DATE:~4,2%_%DATE:~7,2%
set _LOGFILE_TIME=%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%
set _LOGFILE=log-%_LOGFILE_DATE%-%_LOGFILE_TIME%.log

set _currentFolder=%cd%
set _logFolder=%_currentFolder%\log
set _logFileFull="%_logFolder%\%_LOGFILE%"
set _logApp="D:\Program Files (x86)\GnuWin32\bin\tee.exe"

if not exist %_logFolder%(
	mkdir %_logFolder%
)

Output


>REM http://snipplr.com/view/21573/print-datetime-in-dos-batch-file/

>set _LOGFILE_DATE=2016_03_31

>set _LOGFILE_TIME=14_56_59

>set _LOGFILE=log-2016_03_31-14_56_59.log

>set _currentFolder=D:\\Script\SynchData\TableDiff

>set _logFolder=D:\\Script\SynchData\TableDiff\log

>set _logFileFull="D:\\Script\SynchData\TableDiff\log\log-2016_03_31-14_56_59.log"

>set _logApp="D:\Program Files (x86)\GnuWin32\bin\tee.exe"
The syntax of the command is incorrect.
>if not exist D:\\Script\SynchData\TableDiff\log(
>

Explanation

The erroring line is the one that follows “The syntax of the command is incorrect.”

In our case, if not exist …

 

Code – On the If statement, add space before (


@ECHO ON
REM http://snipplr.com/view/21573/print-datetime-in-dos-batch-file/
set _LOGFILE_DATE=%DATE:~10,4%_%DATE:~4,2%_%DATE:~7,2%
set _LOGFILE_TIME=%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%
set _LOGFILE=log-%_LOGFILE_DATE%-%_LOGFILE_TIME%.log

set _currentFolder=%cd%
set _logFolder=%_currentFolder%\log
set _logFileFull="%_logFolder%\%_LOGFILE%"
set _logApp="D:\Program Files (x86)\GnuWin32\bin\tee.exe"

if not exist %_logFolder%   (
	mkdir %_logFolder%
)

Output:


>REM REM http://snipplr.com/view/21573/print-datetime-in-dos-batch-file/

>set _LOGFILE_DATE=2016_03_31

>set _LOGFILE_TIME=15_01_43

>set _LOGFILE=log-2016_03_31-15_01_43.log

>set _currentFolder=D:\\Script\SynchData\TableDiff

>set _logFolder=D:\\Script\SynchData\TableDiff\log

>set _logFileFull="D:\\Script\SynchData\TableDiff\log\log-2016_03_31-15_01_43.log"

>set _logApp="D:\Program Files (x86)\GnuWin32\bin\tee.exe"

>if not exist D:\\Script\SynchData\TableDiff\log (mkdir D:\\Script\SynchData\TableDiff\log )
>

Windows – Windows Script Host/VBScript – Getting Full Name of Network User

Background

Here I am with a Network Logon, but no corresponding Fullname.

 

Windows AD Tools

Depending on the version of Windows, we can quickly put together a script for getting the information.


      dsquery user -name joe | dsget user -display

 

If invalid username, you will get :


    dsget failed:'Target object for this command' is missing

 

If valid user, you will get something such as :


  display
  Adeniji, Daniel

 

Code

VBScript

Here is a VBscript for doing same:

 

 

Option Explicit
Dim strADDomain
Dim strUserName
Dim strUserNameCurrent
Dim objWshShell
Dim strObjectData
Dim strNameNotFound
Dim iCommandLineArgCount
Dim objUser

Const CommandLineArgCountExpected = 1
Const ERR_InvalidProcedureCallORArgument = 5

Const OBJECT_REF_SYNTAX = "WinNT://{0}/{1}"
Const ERR_NAME_NOT_FOUND = "Not not found Domain {0} / User {1}"

rem SQL string formatting in VBScript
rem PEOPLE AREN'T LOOKING FOR WEBSITES, THEY'RE LOOKING FOR ANSWERS.
rem http://lutrov.com/blog/sql-string-formatting-in-vbscript
function fmt(str, args())
   dim res, i
   res = str
   for i = 0 to ubound(args)
      res = replace(res, chr(123) & cstr(i) & chr(125), cstr(args(i)))
   next
   fmt = res
end function

REM *******************************************************************
Rem MS Windows Shell Environment Variables
REM *******************************************************************
Set objWshShell = WScript.CreateObject( "WScript.Shell" )

	strADDomain = objWshShell.ExpandEnvironmentStrings( "%USERDOMAIN%" )

	strUserNameCurrent = objWshShell.ExpandEnvironmentStrings( "%USERNAME%" )

set objWSHShell = Nothing

REM *******************************************************************
Rem Get Command Line Arguments
REM *******************************************************************
iCommandLineArgCount = WScript.Arguments.Count

if (iCommandLineArgCount = CommandLineArgCountExpected) Then

	strUserName = WScript.Arguments.Item(0)

else

	Err.Raise ERR_InvalidProcedureCallORArgument ' Invalid procedure call or argument

end if

REM *******************************************************************
Rem If arguments not passed in, then assume for current user
REM *******************************************************************
if (strUserName = "") Then

	strUserName = strUserNameCurrent

end if

rem strObjectData = "WinNT://" & strADDomain & "/" & strUserName
strObjectData = fmt(OBJECT_REF_SYNTAX, array(strADDomain, strUserName))

rem (null): The network path was not found.
on error resume next

	Set objUser = GetObject(strObjectData)

on error goto 0

rem display full name
if IsObject(objUser) Then

	Wscript.Echo objUser.FullName

else

	strNameNotFound = fmt(ERR_NAME_NOT_FOUND, array(strADDomain, strUserName))

	Wscript.Echo strNameNotFound

end if	

rem free object
if IsObject(objUser) Then

	Set objUser = Nothing

end if

 

 

To try things out:

 


    cscript getUserFullName.vbs dadeniji

 

 

References

VBScript

 

 

 

Summary

How poetic justice is that?

I bemoaned “On error resume next”, Microsoft – Classic ASP – Error Suppressed, barely a week gone by.  And, now I need it to avoid a missing AD Entry warning.

But, nevertheless when used, quickly close it out with an “on error goto 0“.

 

Technical: Microsoft – OS – Command Shell – Which.exe

Technical: Microsoft – OS – Command Shell – Which.exe

Introduction

Back in terminal mode, running some DOS Command Shell scripts and seeing an error I am not quite familiar with; specifically I am seeing “INFO: Could not find files for the given pattern(s)”

It is bugging me a bit and so I keep shredding the file to hopefully pinpoint the offending line.

The where.exe

Finally tamed \ traced it back to the where.exe command.  It is a Microsoft take on the Unix\Linux which command.


Description:
Displays the location of files that match the search pattern.
By default, the search is done along the current directory and
in the paths specified by the PATH environment variable.

Where.exe – How does it work

If I need to determine how it works, I will issue something like


where sqlcmd.exe

And, I will get back, something like:


c:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE
C:\Program Files\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE

If I look for a file (sqlcmdNoop.exe) that does not likely exist:


where sqlcmdNoop.exe

And, I will get back, something like:


INFO: Could not find files for the given pattern(s).

My little fix towards silencing the error

I am not really interested in seeing and reviewing the list of file matches.  All I need to know is whether sql server client app (sqlcmd.exe) exists or not.

And, so I can the change the code snippet a bit.



@ECHO OFF
@ECHO Is sqlcmd.exe installed?
@WHERE SQLCMD.EXE /Q
if %errorlevel%==0 (
	echo "file (sqlcmd.exe) found"
) else (
	echo "file (sqlcmd.exe) not found"
)

@WHERE SQLCMDNOOP.EXE /Q
if %errorlevel%==0 (
	echo "file (sqlcmdNOOP.exe) found"
) else (
	echo "file (sqlcmdNOOP.exe) not found"
)

Output:



Is sqlcmd.exe installed?

"file (sqlcmd.exe) found"

"file (sqlcmdNOOP.exe) not found"


Explanation:

  • Passing in the /Q argument to the where.exe utility says do not list out the files you find nor display “INFO: Could not find files for the given pattern(s)” if there are no matches
  • For our specific use case, we partake of the nice ERRORLEVEL exit code

References

Microsoft – Command Shell – Run Set of SQL Commands against set of SQLServer Instances

Microsoft – Command Shell – Run Set of SQL Commands against set of SQLServer Instances

In our little demo below, the files are:

a] ListofSQLServerInstances.txt (text file that contains list of SQL Server Instances)

b] setSQLServerMemory.sql (sql file that contains Set of SQL Commands to invoke against each SQL Server Instance)

c] deploySQLScript.cmd (deployment Agent – Get each Server name from ListofSQLServerInstances.txt and invoke sqlcmd against each SQL Server Instance)

ListofSQLServerInstances.txt

DBSales
DBFinance

setSQLServerMemory.sql

  exec sp_configure 'show advanced options', 1
   reconfigure with override;

   -- set max memory to 16 GB 
   exec sp_configure 'max server memory (MB)', 16000
   go

   reconfigure with override;

   exec sp_configure 'show advanced options', 0
   reconfigure with override;</pre>

deploySQLScript.cmd


   echo off
   for /f %%s in (type listofSQLServerInstances.txt) do (

        echo Server-name %%s
        sqlcmd -S %%s -E -i setSQLServerMemory.sql
   )

References:

  1. Dos – For Command
    http://www.computing.net/answers/programming/dos-for-command/14596.html 
  2. How to write a DOS Batch file to loop through files http://www.jamesewelch.com/2008/05/01/how-to-write-a-dos-batch-file-to-loop-through-files/

Microsoft – MS Dos – Commands (Do you know your echo[ing])

Last week, while trying to develop a little Application install script ran into a vexing problem with xcopy not working on a Windows 2008 box

if not exist “C:\Program files (x86)\Common Files\” set _OS=32
if exist “C:\Program files (x86)\Common Files\” set _OS=64
set _OS
ECHO %_OS%
— Problem line — without spoon-feeding the xcopy with an echo f, it kept prompting whether destination is a file or directory
–While /i allows one to specify that destination is a directory, a corresponding option does not exist to specify that destination is a file
— —/i : If Source is a directory or contains wildcards and Destination does not exist, xcopy assumes destination specifies a — —   directory name and creates a new directory. Then, xcopy copies all specified files into the new directory. By
— default, xcopy prompts you to specify whether Destination is a file or a directory.

if “%_OS%”==”64” if exist “C:\ProgramData\Quest Software\LiteSpeed\Engine\”   echo f | xcopy “\\InstallServer\LSBackFilter.ini” “C:\ProgramData\Quest Software\LiteSpeed\Engine\” /Y
References:
____________________________________________________________________________________________
1] TechNet \ TechNet Library \ Windows \ Windows XP \ Command-line reference A-Z \ Xcopy
http://technet.microsoft.com/en-us/library/bb491035.aspx

____________________________________________________________________________________________

2] Xcopy To File Without Extension

http://www.computing.net/answers/windows-xp/xcopy-to-file-without-extension/181159.html

Judago December 4, 2009 at 05:27:00 Pacific
What about plain old copy? Sure the directory has to exist but it won’t ask.
Xcopy seems to have been created to deal with directory names and/or multiple files, while copy still exists it doesn’t make much sense to have a single file option.
If you insist on using xcopy simply echo “f” to select the option file without user input.
echo f|xcopy test test2
____________________________________________________________________________________________