File

PowerShell Remove Old Files From a Directory

Script for removal of old backup or logfiles from a specific directory. The example below removes all files from a directory that are older than 90 days. A log of all files that are removed is written to the windows eventlog.

# Global config settings...
[string]$sDirName = "D:\LogFiles"
[string]$sFileNameMask = "*.log"
[string]$sGCIMask = $sDirName + "\" + $sFileNameMask
[string]$sEventLogMessage = "### Cleanup Script Started... ###`r`n"

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

# Start Main script...
if (Test-Path $sDirName) {
get-childitem $sGCIMask | 
    % { 
        # Get File Last Write Time...
        [datetime]$dFileModTime = fGetFileModTime($_.fullname)
        if ($dFileModTime -lt (Get-date).AddDays(-90)) {
        remove-item $_.fullname
        $sEventLogMessage = $sEventLogMessage + "File " + $_.fullname + " (" + $dFileModTime.DateTime + ") removed...`r`n"
        }
    }
}

# Finish and Cleanup...
[string]$sEventLogMessage = $sEventLogMessage + "### Cleanup Script Finished... ###"
write-eventLog -LogName "Windows PowerShell" -Source "PowerShell" -EventID 30001 -Message $sEventLogMessage -EntryType Information

GNU/Linux Find and Remove Old Files From Directory

You can use find to script removal of old backup or logfiles from a specific directory. The example below removes all files from a directory that are older than 14 days.

find /var/local/ucs/*.ucs -type f -mtime +14 -exec rm {} \;

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 [--recurse-submodules] ssh://git@gitlab.timvkn.nl: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
git submodule update --init --recursive

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

Add submodule

git submodule add https://github.com/dGlt/submodule Submodules

PowerShell Unzip Function

A small PowerShell function for unzipping a file.

function fUnzip([string]$sZIPFileName, [string]$sExtractToDir) {
  $oShell = new-object -com shell.application
  $oZIPFile = $oShell.namespace("$sZIPFileName")
  $oExtractTo = $oShell.namespace("$sExtractToDir")
  $oExtractTo.Copyhere($oZIPFile.items())
}

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