Created
December 8, 2014 10:06
-
-
Save Wimpje/e7b529cbe8c85076d752 to your computer and use it in GitHub Desktop.
Split files with Powershell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param( [string]$file = $(throw "file is required"),$maxFiles = [Int32]::MaxValue, $upperBound = 500MB ) | |
# with a little help of https://gist.github.com/awayken/5861923 | |
$ErrorActionPreference = "Stop"; | |
trap { | |
$ErrorActionPreference = "Continue" | |
write-error "Script failed: $_ \r\n $($_.ScriptStackTrace)" | |
exit (1); | |
} | |
$file = (resolve-path $file).path | |
$fileNameExt = [IO.Path]::GetExtension($file) | |
$fileNameWithoutExt = [IO.Path]::GetFileNameWithoutExtension($file) | |
$fileNameDirectory = [IO.Path]::GetDirectoryName($file) | |
$fromFile = [io.file]::OpenRead($file) | |
$buff = new-object byte[] $upperBound | |
$count = $idx = 0 | |
try { | |
"Splitting $from using $upperBound bytes per file, with a max of $maxFiles files" | |
do { | |
$count = $fromFile.Read($buff, 0, $buff.Length) | |
if ($count -gt 0) { | |
$to = [IO.Path]::Combine($fileNameDirectory, "$fileNameWithoutExt.$idx$fileNameExt") | |
$toFile = [IO.File]::OpenWrite($to) | |
try { | |
"Writing to $to" | |
$tofile.Write($buff, 0, $count) | |
} finally { | |
$tofile.Close() | |
} | |
} | |
$idx ++ | |
} while ($count -gt 0 -and ($idx -lt $maxFiles)) | |
} | |
finally { | |
$fromFile.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment