0

I am trying to use powershell to split up huge log files into separate files so I can view them. I found some code online to get me started and I modified to fit my needs now I am just fine tuning it. The issue I have is I would like the script in a folder separate than the log file but have the split files be created in the same folder as the log file. Currently it splits the log files in the same folder the script is in. I tried doing the set-location(split-path $filename -parent -resolve) which changes the directory to the folder the log file is in but still spits out the split log files into the folder where the script is. Any help will be greatly appreciated Thanks.

 #split test
param (
[string] $filename = $null
)
$sw = new-object System.Diagnostics.Stopwatch
$sw.Start()
$rootName = [io.path]::GetFileNameWithoutExtension($filename)
$ext = [io.path]::GetExtension($filename)
$linesperFile = 100000#100k
$filecount = 1
$reader = $null
Set-Location(split-path $filename -parent -resolve)
try{
$reader = [io.file]::OpenText($filename)
try{
    "Creating file number $filecount"
    $writer = [io.file]::CreateText("{0}-{1}{2}" -f ($rootName,$filecount.ToString("000"),$ext))
    $filecount++
    $linecount = 0

    while($reader.EndOfStream -ne $true) {
        "Reading $linesperFile"
        while( ($linecount -lt $linesperFile) -and ($reader.EndOfStream -ne $true)){
            $writer.WriteLine($reader.ReadLine());
            $linecount++
        }

        if($reader.EndOfStream -ne $true) {
            "Closing file"
            $writer.Dispose();

            "Creating file number $filecount"
            $writer = [io.file]::CreateText("{0}-{1}{2}" -f ($rootName,$filecount.ToString("000"),$ext))
            $filecount++
            $linecount = 0
        }
    }
} finally {
    $writer.Dispose();
}
} finally {
$reader.Dispose();
}
$sw.Stop()

Write-Host "Split complete in " $sw.Elapsed.TotalSeconds "seconds"
themackyo
  • 363
  • 1
  • 4
  • 13
  • See [my answer](http://stackoverflow.com/a/32379304/4424236) for this question: [split text file into smaller files based on size (windows)](http://stackoverflow.com/questions/32360801/split-text-file-into-smaller-files-based-on-size-windows). – beatcracker Mar 30 '16 at 16:58

1 Answers1

1

The .NET methods (like File.CreateText() for example), resolves partial paths relative to the Working Directory of the process running, rather than the PowerShell-specific location set by Set-Location.

Create an absolute path with Join-Path and pass that to CreateText() instead:

$newFileName = '{0}-{1}{2}' -f ($rootName,$filecount.ToString("000"),$ext)
$fullPath    = Join-Path -Path (Split-Path $filename -Parent) -ChildPath $newFileName
$writer      = [IO.File]::CreateText($fullPath)
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Thank you for the explanation on how .NET methods resolve the path it was helpful and your code worked as intended Thank you. – themackyo Mar 30 '16 at 18:04