Monday, October 27, 2014

Search a file for a string and update text using powershell

"Starting"
# Put the directory where the photos are located here
$Directory = "C:\Users\jmm\Desktop\deploy"
# filename to search for
$FileName = get-childitem $Directory -recurse -Include ac360.js
# Counter for testing
#$g = 0
foreach ($file in $FileName){
$filename = $file.BaseName
$Find_This = "var maxLen = obj.maxlength;"
If (Get-Content $file | Select-String -Pattern $Find_This){
$indx = Select-String $Find_This $file | ForEach-Object {$_.LineNumber}
#array of file lines is 0 based.
$indxone = $indx - 1
"Found at line $indxone with line content " + (Get-Content $file)[$indxone]
# Need to check line previous to the line we are changing to make sure the file wasn't already changed
# since we are adding stuff after the line and not before.
$indxtwo = $indx - 2
# If it finds what it thinks it should find
If ((Get-Content $file)[$indxtwo] | select-string -Pattern "var obj = acEvent.srcElement; "){
"Found at $indxtwo " + (Get-Content $file)[$indxone] + "Changed at $indxone " + (Get-Content $file)[$indxone]
# replace the line and save it back to the same file
(get-content $file) | foreach-object {$_ -replace $Find_This, "if (typeof obj.maxLength == 'undefined'){`r`n            obj.maxLength = 4000;`r`n            }`r`n       var maxLen = obj.maxLength; "} | set-content $file
}else{
"Doesn't Qualify : " + $indxtwo + " : " + (Get-Content $file)[$indxtwo]
}
}
#$g++
}
"Done"

Tuesday, October 14, 2014

Date Conversion

,CASE
WHEN ISNUMERIC([SITE VISIT]) = 1
THEN CONVERT(SMALLDATETIME, (CAST([Site Visit] AS INT)), 101)
ELSE
CASE WHEN ISDATE([SITE VISIT]) = 1
THEN CONVERT(DATETIME, ([Site Visit]), 101)
ELSE '' END
END AS date_time