Win OS / Preparing Public Key from command Line

Batch

Sample DOS Batch file for importing partner public key, creating self public key, and exporting created key

Code


setlocal

	set "_folderBin=F:\PGP Corporation\PGP Command Line"
	set "_fileBin=pgp.exe"

	set "_folderKeyPublic=pgpkeys"
	set "%_fileKeyPublicPartner=Partner PGP key_PROD_public.asc"
	set "%_fileKeyPublicSelf=Self_PGP_Keys_Prod_public.asc"

	set "_privateKeyRealID=Self_PGP_Keys_Prod "
	set "_privateKeyType=RSA"
	set "_privateKeySize=2048"
	set "_privateKeyPassphrase=lovejones"

	REM Import Public Key Partner
	"%_folderBin%"\%_fileBin% --import "%_folderKeyPublic%\%_fileKeyPublicPartner%"

	REM List Keys
	"%_folderBin%"\%_fileBin%  --list-keys

	REM Generate Key
	"%_folderBin%"\%_fileBin% --gen-key "%_privateKeyRealID%" --key-type %_privateKeyType% --bits %_privateKeySize% --passphrase %_privateKeyPassphrase%

	REM Export Public Key Self
	"%_folderBin%"\%_fileBin% --export "%_privateKeyRealID%" --output "%_folderKeyPublic%\%_fileKeyPublicSelf%"

endlocal

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 )
>

DOS – Batch – Process Files But Skip Selected Files

Objective

We are using ScriptDB to generate SQL files from a live Production system.

Before applying the files to a new system, we need to exclude some of the files and apply batch changes to the remaining files.

So here is what we did:

  1. Issue ScriptDB to generate SQL files for each DB Object
  2. Prepare an exclusion list; listing files we will like to skip
  3. Ran our batch file

Here is what the batch file does

  1. It reads an exception file; that lists the objects to be skipped
  2. If the entry should be skipped it makes a copy of it.
    • The copy file has the same name as the original file with .bak appended
    • The Original file is then removed

And, so what we end up is a folder that has the files we need and the files we want to skipped delineated by the .bak extention

Code


@ECHO OFF

@REM Please make sure to keep the EnableDelayedExpansion
Setlocal EnableDelayedExpansion

IF %1.==. (
    Echo Please specify Source Folder as the first argument
	Goto End
 ) 

set folderSource=%1

set folderBase=%folderSource%
echo FolderBase is !folderBase!

@REM The Full Location of the except text file
set "exceptSourceFolder=."
set "exceptSourceFile=skippedFiles.txt"
set "exceptSourceFileFull=%exceptSourceFolder%\%exceptSourceFile%"

echo Exception Source File is !exceptSourceFileFull!

set /p DUMMY=Hit ENTER to Start Processing Skipped Files

set "BAKEXT=.bak"

echo %exceptSourceFileFull%

for /f %%f in (%exceptSourceFileFull%)  do (

	ECHO Processing Except entry %%f ...
	
	set _filename=%folderBase%\%%f

	ECHO Processing File !_filename!
	
	@REM Get full file name by adding except file name to base folder
	set _fullFileTest=!_filename!
	ECHO "Full Name of File !_fullFileTest!"

	@REM Get Backup file name
	@REM set "fullFileTestBak=%fullFileTest%%BAKEXT%"
	set "_fullFileTestBak=!_filename!%BAKEXT%"
	ECHO "Test File (BAK) !_fullFileTestBak!"


	@REM Copy file to backup file
	if exist !_fullFileTest! (

	  @REM If Backup file alreay exists, please delete	it
	  if exist "!_fullFileTestBak!" (
	  
		echo "Removing backup file !_fullFileTestBak_! ..."
		
		del !_fullFileTestBak!
		
		echo "Removed backup file !_fullFileTestBak!
		
	) 
	
		echo "Copy file !_fullFileTest! as backup file !_fullFileTestBak! ..."
		copy !_fullFileTest! !_fullFileTestBak! 1>NUL
	 
		echo "Del file !_fullFileTest! ..."
		del !_fullFileTest!

	) else ( 
	
			@REM Echo Skipped File not found - !_fullFileTest! 
	)
	
	echo.
	echo.
	
)

set /p DUMMY=Hit ENTER to Exit Processing Skipped Files

Goto End

:End



Explanation

  1. Please keep in mind that you need the “Setlocal EnableDelayedExpansion
  2. And, that instead of using % to access local variables , we use !

 

Folder

Here is the folder tree that ScriptDB generates for us.

FolderExplorer

Sample Exclusion File


Programmability\StoredProcedures\CRM.GetCSRAppointmentsLog.sql
Programmability\StoredProcedures\CRM.GetPaymentsLog.sql

 

Credits

Jeff Mercado

JeffM

 

Listening

Looking for something else, but felt like Leanne Rimes.

Here she sings Reba McEntire’s The Greatest Man I Never Knew.

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