File

PowerShell Check File Modified Time

Script to check is a specific file exists and its modified time is less than 1 day in the past. This script uses some custum functions from a imported module.

# Import DBA modules...
Import-Module 'D:\Path\To\DefaultFunctionsModule.psm1'

# Global config settings...
[string]$sSubject1 = "SBO:CheckLogFiles Errors Found..."
[string]$sSMTPServer1 = "smtp.example.com"
[string]$sToAddress1 = "mail@example.com"
[string]$sEventLogSource = "{eventlogsource}"

# Functions en Procedures...
function fnGetFileModTime([string]$sFileName) {
$vFileInfo = get-childitem $sFileName
return $vFileInfo.lastwritetime
}

# Start Main script...
if ((Test-Path $args[0]) -and ($args[1])) {
# Request file modified time...
[datetime]$dFileModTime = fnGetFileModTime("$($args[0])")
# Alert if file modified time is older than 1 day...
if ((Get-date).AddDays(-1) -gt $dFileModTime) {
$sMessage1 = "ERROR: File modified time is older than 1 day...`r`n`r`nFilename: " + $args[0] + "`r`nService: " + $args[1]
fnWriteEventLog -sNode (fnGetFQDN) -sMessage $sMessage1
fnSendMail -sSMTPSrvrName $sSMTPServer1 -sFrom (fnGetFQDN -swIsEmail) -sTo $sToAddress1 -sSubject $sSubject1 -sBody $sMessage1
}
} else {
if (($args[1])) {
# Alert if file does not exist...
$sMessage1 = "ERROR: File does not exist...`r`n`r`nFilename: " + $args[0] + "`r`nService: " + $args[1]
fnWriteEventLog -sNode (fnGetFQDN) -sMessage $sMessage1
fnSendMail -sSMTPSrvrName $sSMTPServer1 -sFrom (fnGetFQDN -swIsEmail) -sTo $sToAddress1 -sSubject $sSubject1 -sBody $sMessage1
} else {
$sMessage1 = "ERROR: Missing argument... [CheckModTime.ps1 `"c:\path\to\file`" `"service`"]`r`n`r`nFilename: " + $args[0] + "`r`nService: " + $args[1]
echo $sMessage1
}
}

GIT Version Control Basics

Clone a Repository, add files, commit and push to master

 $>git clone ssh://git@gitlab.example.com:22/Project.git
 $>git add [filename|-A]
 $>git commit -a -m "Initial upload..."
 $>git push -u origin master

Create a branch for the new release and check-out to the new branch

 $>git branch release-4.1.11
 $>git checkout release-4.1.11

Make the changes to the files and commit the changes

 $>git commit -a -m "Change description..."

Mark as executable

$>git update-index --chmod=+x build.sh

Push to server

 $>git push -u origin release-4.1.11

Merge changes with master branch

A) Merge with master takes place on server. Pull new master branch from server...
$>git checkout master
$>git pull -a

B) Merge all changes to the master locally and push to server...
$>git checkout master
$>git merge release-4.1.11
$>git push -u origin master

Delete old branch

$>git branch -d release-4.1.11
* Option -D deletes a not merged branch...

Display commits and force to specific commit

$>git reflog
$>git reset --hard e072e63

PowerShell Grep Recent Logfiles

I’ve written this PowerShell script to search for specific txt in recent logfiles (changed within last 24 hours). The output is returned to standard out.

# *****************************************************************************
# Scriptnaam: CHECKLOGFILES.PS1
# Written_by: Tim van Kooten Niekerk
# Versie: 20120522B
# Info: PowerShell script to search for specific text in files modified in the last 24 hours.
# *****************************************************************************

# Functions en Procedures...
function fGetFileModTime([string]$sFileName) {
  $vFileInfo = get-childitem $sFileName
  return $vFileInfo.lastwritetime 
}

function fSendMessage([string]$sNode, [string]$sApplication, [string]$sMessage) {
  $sMessage
  # And send result to operations...
  #return Start-Process...
}

# Start Main script...
if (($args[0]) -and ($args[1]) -and ($args[2]) -and ($args[3])) {
  # Check if path exists...
  if (Test-Path $args[0]) {
    # Check for searchterm in files modified in the last 24 hours...
    [boolean]$bResultFound = $false
    [string]$sSearchTerm = $args[1]
    Get-ChildItem $($args[0]) | where {$_.LastWriteTime -gt (Get-Date).AddHours(-24)} |
      % {
	    $oResult1 = select-string -path $_.fullname -pattern $sSearchTerm -context 0 
	    if (($oResult1.Linenumber -gt 0) -or ($oResult1.Count -gt 0)) { 
	      $sResult1 = $oResult1 | format-list -property line,path,linenumber | Out-String
	      [string]$sResultMerge = [string]$sResultMerge + $sResult1
	      $bResultFound = $true
	    }
	  }
    # $sResult1 = select-string -path $($args[0]) -pattern $($args[1]) -context 0 
    # Send message when searchterm is found...
    if ($bResultFound -eq $true) {
      $sMessage1 = "Searchterm [" + $args[1] + "] found in recent logfiles... `r`n`r`nRESULT:"
      fSendMessage $args[2] $args[3] $sMessage1 
    }
  } else {
    $sMessage1 = "Error executing ... `r`n`r`nERROR: Pad niet gevonden."
    fSendMessage $args[2] $args[3] $sMessage1  
  }
} else {
  "Error executing script... `r`n`r`nERROR: Arguments missing."
  "SYNTAX: checklogfiles.ps1 `"<c:pathtodir*.log>`" `"<searchterm>`" `"<hostname>`" `"<service>`""
}

 

MSSQL List Active DBFiles

Met behulp van de volgende query kun je een overzicht opvragen van alle actieve bestanden eventueel kun je een WHERE clause opnemen (WHERE type_desc = ‘LOG|ROWS’) om alleen de logbestanden of alleen de data bestanden weer te geven.

SELECT smf.physical_name, sdb.name as database_name
FROM sys.master_files smf
LEFT JOIN sys.databases sdb on sdb.database_id = smf.database_id
--WHERE type_desc = 'LOG'
ORDER BY smf.physical_name

PowerShell Check File LastWriteTime

PowerShell script to start a specific routine when a file is older than two days (LastWriteTime). This specific example writes an error in the application event log.

# *****************************************************************************
# Scriptnaam: CHKMODTIME.PS1
# Geschreven_door: Tim van Kooten Niekerk
# Versie: 2010.10.29.01
# Info: PowerShell script t.b.v. uitvoeren actie als de wijzigingsdatum
# Info: van het opgegeven bestand ouder is dan ingestelde waarde.
# *****************************************************************************

function fGetFileModTime([string]$sFileName) {
  $vFileInfo = get-childitem $sFileName
  return $vFileInfo.lastwritetime 
}

# Opvragen van wijzigingsdatum bestand...
[datetime]$dFileModTime = fGetFileModTime("D:PadNaarBestand.bak")
# Voer een actie uit als de wijzigingsdatum van het bestand ouder is dan 2 dagen...
if ((Get-date).AddDays(-2) -gt $dFileModTime) {
  # Schrijf Error melding weg naar eventlog of voer een andere actie uit...  
  $oEventLog = new-object System.Diagnostics.EventLog('Application')
  $oEventLog.MachineName = "."
  $oEventLog.Source = "WSH"
  $oEventLog.WriteEntry("Back-up is to old...", "Error")
}

 

PowerShell Edit Multiple Files

PowerShell example to edit multiple files. This specific example remove the first 15 chars from every XML file in a directory.

get-childitem D:TEMPMessages *.xml |
  % { 
         [string]$sFileContent = cat $_.fullname
         $sFileContent = $sFileContent.substring(15,$sFileContent.length-15) | Out-File -Filepath $_.fullname
         echo $_.fullname
  }

MSSQL DBFile SpaceUsed

Script to return database file usage (GB) from a database.

USE [DATABASE]
GO
SELECT DBFiles.fileid as FileID,
       DBFiles.filename as FileName,
       DBFiles.name as Name,
       CONVERT(decimal(18,3),ROUND(((CAST(FILEPROPERTY(DBFiles.Name, 'SpaceUsed') AS decimal) * 8) /1024 /1024), 3)) AS SpaceUsedGB, 
       CONVERT(decimal(18,3),ROUND(((CAST(DBFiles.size AS decimal) * 8) /1024 /1024), 3)) AS FileSizeGB
FROM dbo.sysfiles DBFiles
GO

 

MSSQL Log space used percentage

Met onderstaande T-SQL kun je de vulling in procent van het transaction log bestand van een specifieke database opvragen en monitoren. Dit is alleen handig in specifieke situaties. Bij een correct database onderhoudsplan zal dit niet nodig zijn.

CREATE TABLE #tTLSpace 
( 
DBName sysname, 
TLSize decimal(18,5), 
TLUsed decimal(18,5), 
status INT 
)
GO

INSERT INTO #tTLSpace 
       exec ('DBCC SQLPERF(logspace)') 
GO

DECLARE @dTLUsed decimal
SELECT @dTLUsed = TLUsed from #tTLSpace WHERE DBName = 'DATABASE'
IF ( @dTLUsed > 90)
BEGIN
  PRINT @dTLUsed
  PRINT 'TransactionLog bestand 90 procent vol...'
END
GO

DROP TABLE #tTLSpace 
GO