Delete Duplicate Images in the Folder


HI Everyone,

Often we end up having same image multiple times in the same folder. It is very hard to remove. Below script will help you in easing this task.

$Folder = “C:\Users\chaitanya\pictures\Testing”

$Folderobj =get-childitem -Path $Folder -Recurse |where { ! $_.PSIsContainer }

$FolderobjCount = $Folderobj.Count

$ImageObjArr = @();

$Folderobj| ForEach-Object {

$FolderobjCount–;

$ImageHash = $null

$ImageFileName = $_.Name

$ImageFilePath = $_.FullName

$ImageFileCreateDate = $_.CreationTime

$ImageHash = Get-FileHash -Path $ImageFilePath -Algorithm MD5

Write-Host “Creating Hash for Destination Image name $($ImageFileName) and Current Image Count is : $($FolderobjCount) ” -ForegroundColor cyan

if($ImageHash)

{

$ImageObjArr += [pscustomobject]@{ImageFileName=$ImageFileName;ImageFilePath=$ImageFilePath;ImageCreateDate=$ImageFileCreateDate; ImageFileHash=$($ImageHash).Hash;}

}

}

$DeletedImages = @();

$ImageObjArr | Group-Object -Property ImageFileHash | Where-Object {$_.count -gt ‘1’} | ForEach-Object -process{

$DuplicateImageObj = $_.group | Sort-Object -Property ImageCreateDate |select -Skip 1

if($DuplicateImageObj)

{

foreach($dup in $DuplicateImageObj)

{

Write-Host “Started Deleting the Duplicate Image name $($dup.ImageFileName) ” -ForegroundColor Yellow

$DeletedImages += [pscustomobject]@{ImageFileName=$dup.ImageFileName;ImageFilePath=$dup.ImageFilePath;}

get-childitem -Path $dup.ImageFilePath | Remove-Item -Force

Write-Host “Completed Deleting the Duplicate Image name $($dup.ImageFileName) ” -ForegroundColor Green

}

}

}

$DeletedImages |Out-GridView

Note: Please be careful while giving the folder that you want, it does recursive operation and search sub folders and delete the files too apart from Images.

Regards,

Chaitanya

Advertisements

Compare 2 Image folders and copy the missing images


Hi Everyone,

 

often , we do take photos and store it in our external drives  with same name or different name.

ex: we have inserted the  Camera memory card  in our system and copy it to our specific drive or to other external drive.  some time though images are same, file names might be different.  we can do the image comparison using powershell hash. below is the script for this.

 

$Source= “C:\Users\Chaitanya\Pictures\Camera Roll”
$Destination = “C:\Users\Chaitanya\Pictures\Test\Testing”

$Destinationobj =get-childitem -Path $Destination -Recurse

$DestinationobjCount=$Destinationobj.Count

$DestObjArr=@();
$Destinationobj| ForEach-Object {

$DestinationobjCount–;

$DestHash=$null
$DestFileName = $_.Name
$DestFilePath = $_.FullName
$DestHash = Get-FileHash -Path $DestFilePath -Algorithm MD5

Write-Host “Creating Hash for Destination Image name $($DestFileName) and Current Image Count is : $($DestinationobjCount) ” -ForegroundColor cyan

if($DestHash)
{

$DestObjArr+=[pscustomobject]@{DestFileName=$DestFileName; DestFileHash=$($DestHash).Hash;}

}

}

$SourceObj =get-childitem -Path $Source -Recurse

$SourceObjCount=$SourceObj.Count

$SourceObj| ForEach-Object {

$SourceObjCount–;

$SrcFile = $_.FullName
$SRCFileName = $_.Name

$DestFilepath =$Destination+”\”+$SRCFileName

Write-Host “Creating Hash for Source Image name $($SRCFileName) and Current Image Count is : $($SourceObjCount)” -ForegroundColor cyan

$SrcHash = Get-FileHash -Path $SrcFile -Algorithm MD5

if ($SrcHash)

{

Write-Host “Checking the Destination Hash for Source File Name : $($SRCFileName) ” -ForegroundColor Cyan

if ($DestObjArr | Where-Object {$_.DestFileHash -eq $($SrcHash).Hash})
{

Write-Host “Hash Exists for Source Image Name $($SRCFileName)” -ForegroundColor DarkYellow

}
else
{

Write-Warning “Hash does Not Exists for Source Image Name :$($SRCFileName), Copying ..”

if (!(Test-Path $DestFilepath))
{

Write-Host “File Name not exists, Copying started for Source Image Name :$($SRCFileName)” -ForegroundColor White

Copy-Item $SrcFile -Destination $DestFilepath

}
else
{

Write-Host “File Name exists, create new name, Copying started for Source Image Name :$($SRCFileName)” -ForegroundColor Magenta

[string]$logdate= Get-Date -Format “yyyyMMddHHssmm”

$DestFilepath =$Destination+”\”+$SRCFileName.Split(“.”)[0]+ $($logdate)+”.”+$SRCFileName.Split(“.”)[1]

Copy-Item $SrcFile -Destination $DestFilepath

}

Write-Host “Copying complete for Source Image Name :$($SRCFileName)” -ForegroundColor Green
}

}

}

 

 

i hope with this your problem with the image saving in your external drives will be solved.

 

post your comments and let us your opinion on this.

 

regards,

Chay

IIS Log file Location check Using PowerShell


Hi All,

if you want to check the IIS web site log location, You need to go to server and check the log file location.

Below is the simple power shell script, you could use on multiple servers and get the web sites Log file Location and latest log file name.

invoke-command -ComputerName Server1,Server2 -ScriptBlock {

Import-Module WebAdministration

$array =@()

foreach($WebSite in $(get-website))

{

$logFileLoc = "$($Website.logFile.directory)\w3svc$($website.id)".replace("%SystemDrive%",$env:SystemDrive)

$latestLogFileName =Get-ChildItem -path $logFileLoc |Sort-Object LastWriteTimeUtc -Descending |select -First 1

$array += [pscustomobject] [ordered] @{ # Only if on PowerShell V3

ServerName=$env:computername

WebsiteName = $($WebSite.name)

LogFileLocation = $logFileLoc

LatestLogFileName = $($latestLogFileName.BaseName)

}

}

$array

}| Select-Object * -ExcludeProperty RunspaceId, PSComputerName |Out-GridView

Regards,

Chaitanya

Finding Files in a Folder having Carriage return


Below is the simple powershell script to find Files in a Folder having Carriage return

Get-ChildItem -Path ‘\\fileshare\folder’ | ForEach-Object {

$contents = [System.IO.File]::ReadAllText($_.FullName)

if ($contents -cmatch ‘\r\n’) {

$_.BaseName

}

}

Happy scripting.

Regards,

Chaitanya

Delete Unwanted Host Instances on the specified BizTalk Server


<#

.SYNOPSIS

<Delete Unwanted Host Instances on the specified BizTalk Server >

.DESCRIPTION

< you can delete the host instances that are not using , because host instances cause CPU and Memory Consumption>

.EXAMPLE

<Open the script in power Shell ISE with Run as Admin permission in the Any one of the BizTalk Web server and run it>

#>

[ARRAY]$hostInstanceObj = get-wmiobject MSBTS_HostInstance -namespace ‘root\MicrosoftBizTalkServer’ -Filter ‘RunningServer="Server1"’

[ARRAY]$HostInstanceObj1 = "Process_Host2","Archive_Host" # Provide the Unwanted Host Instances that you want to remove on the Server1

$hostInstances = $hostInstanceObj | ?{$HostInstanceObj1 -contains $_.hostname}

[ARRAY]$HostInfo = get-wmiobject MSBTS_ServerHost -namespace ‘root\MicrosoftBizTalkServer’ -Filter ‘ServerName="Server1"’

foreach ( $hostInstance in $hostInstances)

{

if ( $hostInstance.GetState().state -eq ‘4’)

{

Write-Output " stopping the Host name $($hostInstance.hostname)"

$hostInstance.InvokeMethod("Stop",$null)

}

if ( $hostInstance.GetState().state -eq ‘1’)

{

Write-Output " Deleting the Host name $($hostInstance.hostname)"

$hostInstance.InvokeMethod("UnInstall",$null)

foreach ( $hostrem in $HostInfo )

{

if ( $hostrem.hostname -eq $hostInstance.hostname)

{

$host2 = $hostrem

$host2.InvokeMethod("UnMap",$Null)

Write-Output " Unmapped the Host $($hostrem.hostname)"

}

}

}

}

Disclaimer : Please test in Lower environments before using this production . it Deletes the Host Instances that you mention

PowerShell Script to Start Only Specified Host instances and Stop remaining Host Instances in BizTalk server


Hi All,

Some of the times, we are in a situation to start only specified host instances in your biztalk group and stop the remaining . in that case, you could use this script to achieve that.

<#

.SYNOPSIS

<This is the Biztalk Server product related Script, you could use this in the

biztalk server Environment for starting only specified hosts and stop another Host Instances

>

.DESCRIPTION

<Used to Start the specified Host Instances on your BizTalk environment and stop the remaining Hosts >

.EXAMPLE

<Open the script in power Shell ISE with Run as Admin permission in the Any one of the BizTalk Web server and run it>

#>

[ARRAY]$hostInstanceObj = get-wmiobject MSBTS_HostInstance -namespace ‘root\MicrosoftBizTalkServer’

[ARRAY]$HostInstanceObj1 = "BizTalkServerApplication","TrackingHost"

$StophostInstances = $hostInstanceObj | ?{$HostInstanceObj1 -notcontains $_.hostname}

$starthostInstances = $hostInstanceObj | ?{$HostInstanceObj1 -contains $_.hostname}

$StophostInstancesFinal = $StophostInstances|?{$_.HostType -eq ‘1’}

foreach ( $hostInstance in $StophostInstancesFinal)

{

if ( $hostInstance.GetState().state -eq ‘4’)

{

Write-Output " stopping the Host name $($hostInstance.hostname) on Server $($hostInstance.RunningServer)"

$hostInstance.InvokeMethod("Stop",$null)

}

}

foreach ( $stInstance in $starthostInstances)

{

if ( $stInstance.GetState().state -eq ‘1’)

{

Write-Output " Starting the Host name $($stInstance.hostname) on Server $($stInstance.RunningServer)"

$stInstance.InvokeMethod("Start",$null)

}

}

Disclaimer : Please test in Lower environments before using this production . it stop the other host instances that you would not mention.

Regards,

Chaitanya

Want Copy Files From Sql Result as you want


Hi All,

Often we try to copy the files from sql server tables and we end up renaming the copied file names manually.

Here is simple sql server statement, where it pull the message archive location and name of the file will be with some GUID and you want to name with PO number column , use this simple select statement

select ‘copy ‘+MessageArchiveLocation +’,’+’"’+PONumber+’.xml’+’"’ from Ordertransactions (nolock) where PONumber in

(‘12344′,’112112′,’11231232’)

order by 1 desc

you will get the results, then copy them to batch file and run it.

Regards,

Chaitanya

Delete GUID named files in folders


Hi All,

Want to delete the GUID named files in your folders?

Here is the simple script that takes the regex for GUID and compares the file name and remove it.

get-childitem |? {$_.basename -match("^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$")} |Remove-Item

if you want to Include subfolders too, use the recurse option like below

get-childitem -Recurse |? {$_.basename -match("^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$")} |Remove-Item

Note: please test it in lower environments before implementing in production.

Regards,

Chaitanya

check .Net frame work Version for the DLLs


Hi All,

If you got bunch of DLLs and want to check the .net version for those, this is simple script you can use to find out the version.

# check .net frame work for the DLLs

$filepath=’D:\Builds\\AutomatedDeployment\Deployment\Add-PreDlls’

$files=Get-ChildItem -Path $filepath -Recurse -filter *.dll

foreach($file in $files)

{

$version = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($file.FullName).ImageRuntimeVersion;

echo "$($file) is using Framework: $version"

}

Happy scripting….

Regards,

Chaitanya

Configure schedule task that runs every 5 minutes for N years


Hi all,

Here is the sample PowerShell script to configure schedule task that runs every 5 minutes for 3 years.

You can change the years , why did I not mentioned infinite time is because of some limitation that I had explained in the other article.

https://sqlblogging.com/2017/08/16/fixethe-task-xml-contains-a-value-which-is-incorrectly-formatted-or-out-of-range-durationp99999999dt23h59m59s/

Script:

$mycredentials = Get-Credential

Invoke-Command -ComputerName “Server1”,”Server2” -Credential $mycredentials -ScriptBlock {

$dt= ([DateTime]::Now)

$timespan = $dt.AddYears(3) -$dt;

$Action = New-ScheduledTaskAction -Execute ‘powershell.exe’ -Argument ‘-command “D:\PS_Jobs\PS_Job1.ps1” -ExecutionPolicy RemoteSigned -NoProfile’

$Trigger = New-ScheduledTaskTrigger -Once -At 9am -RandomDelay (New-TimeSpan -Minutes 30) -RepetitionDuration $timespan -RepetitionInterval (New-TimeSpan -Minutes 60)

$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings (New-ScheduledTaskSettingsSet)

$Task | Register-ScheduledTask -TaskName ‘Job1 Task’

}

Regards,

Chaitanya

%d bloggers like this: