📜 ⬆️ ⬇️

Powershell: Shuffle Files

Good day,% habrauser%!
Recently, they threw a rather simple at first glance puzzle: I need to mix about 1000 photos for the voting system.
Manually doing this is a thankless task. Need some nice little script.
PowerShell turned out to be an ideal option: I didn’t want to install something third-party like python, and I never made friends with .bat files in my life.

Perhaps we will begin.
The names of the photos were important and wanted to keep them. I decided to remove them in the file properties ("Summary" for WinXp, "Details" for Win7). Moreover, voting is written on sharepoint, and he knows how to pick up the "Name" from the file properties. It turned out very convenient.
To edit the file properties, the OLE File Property Reader 2.1 component was used (There is a library wrapper for .net in the example folder vb7), since it was already installed on the machine. The component is designed for office documents, but also suitable for pictures.

Actually script:
[System.Reflection.Assembly]::LoadFrom('c:\DsoFile\Source\Vb7Demo\bin\Interop.DSOFile.dll') function SetSummary-Name([string] $folder, [string]$pattern = '*.*') { $files = [System.IO.Directory]::GetFiles($folder, $pattern) foreach ($f in $files) { $oled = New-Object -TypeName DSOFile.OleDocumentPropertiesClass $oled.Open($f, $false, [DSOFile.dsoFileOpenOptions]::dsoOptionDefault) $sp = $oled.SummaryProperties $sp.Title = $f.Substring($f.lastindexof('\') + 1, $f.lastindexof('.') - $f.lastindexof('\') - 1) $oled.close($true) } } SetSummary-Name -folder 'c:\photo' 


Next, we proceed to mixing:
It was possible to generate numerical names, but suddenly I wanted very much to invent a bicycle of complex construction.
')
 #        function RandomName([string]$path) { $length = 20 #    $sb = New-Object -TypeName System.Text.StringBuilder for($i=0; $i -lt $length; $i++) { #   ,  ... [char]$ch = [Convert]::ToChar([Convert]::ToInt32([Math]::Floor(26 * $rand.NextDouble() + 65))) $tmp = $sb.Append($ch) # Append    ,    $tmp } $name = $path.Substring($path.lastindexof('\') + 1, $path.lastindexof('.') - $path.lastindexof('\') - 1) $sb = $sb.ToString().ToLower() return $path.Replace($name, $sb) } function MixFiles([string]$From, [string]$pattern = '*.*') { $files = [System.IO.Directory]::GetFiles($from, $pattern) foreach($f in $files) { $path = RandomName -path $f #    , while([System.IO.File]::Exists($path)) { #  ,    $path $path = RandomName -path $f } #        Write-Host ($f + ' -> ' + $path) [System.IO.File]::Move($f, $path) } } $rand = New-Object -TypeName Random MixFiles -from 'c:\test\' -pattern '*.jpg' 


Thank you for your attention, I hope someone will be useful.

Source: https://habr.com/ru/post/144888/


All Articles