Home > Back-end >  PowerShell - Split zip (or any) file into multiple files - Script not working
PowerShell - Split zip (or any) file into multiple files - Script not working

Time:10-06

$inFile = "C:\InnoWake\Server\MiningServer.zip"
function split($inFile,  $outPrefix, [Int32] $bufSize){

  $stream = [System.IO.File]::OpenRead($inFile)
  $chunkNum = 1
  $barr = New-Object byte[] $bufSize

  while( $bytesRead = $stream.Read($barr,0,$bufsize)){
    $outFile = "$outPrefix$chunkNum"
    $ostream = [System.IO.File]::OpenWrite($outFile)
    $ostream.Write($barr,0,$bytesRead);
    $ostream.close();
    echo "wrote $outFile"
    $chunkNum  = 1
  }
}

I have the above script that I am trying to get working. I need to split a 1.5GB zip file into 100 mini files then bring them back together once they have been moved.

When I run the script above, it fails to do anything. Obviously I'm hosing things up. Can anyone see where I'm heading south?

Regards, -Ron

CodePudding user response:

You need to call the split function after defining it.

Add the following:

split -inFile $inFile -outPrefix "prefixGoesHere" -bufSize 4MB 

on a new line at the bottom of the script. Change "prefixGoesHere" and 4MB to the appropriate values you want to pass.


If you want to be able to pass arguments to the script itself, add a param block at the top of the script, and then pass the arguments to the split function:

param(
  [string]$inFile = "C:\InnoWake\Server\MiningServer.zip",
  [string]$outPrefix = "",
  [int]$bufSize = 4MB
)

function split($inFile,  $outPrefix, [Int32] $bufSize){

  $stream = [System.IO.File]::OpenRead($inFile)
  $chunkNum = 1
  $barr = New-Object byte[] $bufSize

  while( $bytesRead = $stream.Read($barr,0,$bufsize)){
    $outFile = "$outPrefix$chunkNum"
    $ostream = [System.IO.File]::OpenWrite($outFile)
    $ostream.Write($barr,0,$bytesRead);
    $ostream.close();
    echo "wrote $outFile"
    $chunkNum  = 1
  }
}

# splatting the $PSBoundParameters variable will pass all the parameter arguments that were originally passed to the script, to the `split` function
split @PSBoundParameters

CodePudding user response:

Try adding the below after this line $outFile = "$outPrefix$chunkNum"

$outFile = "$((Get-Item -Path $inFile).Directory)\$outFile"

then call your function like normal

split $inFile $outPrefix $bufSize

CodePudding user response:

You can try my function I wrote relatively recently -- Chunk-File and Recombine-File. If nothing else, you can use it as a reference to see how I did it and adapt your script to similar logic:

https://thepip3r.blogspot.com/2021/07/hackem-up-disassembling-and-recombining.html

  • Related