Search code examples
powershelldebuggingtextsave

How do I save a text file in PowerShell without drastically increasing its size?


I have a PowerShell script that either adds text to lines, or creates lines if a file is blank, however it invalidates the file (which should be a simple text file, but with a custom extension ".env") my code looks like this:

$menvs = @()
$paths = @()
Get-ChildItem -Path c:\Users\$env:UserName\Documents\maya\ -filter Maya.env -Recurse | % {
     $menvs = $menvs + $_.FullName
}

Foreach($fl in $menvs){
    if ((Get-Content $fl) -eq $null){
        $paths = @("MAYA_SCRIPT_PATH = P:/InProd/tools/maya/mel;P:/InProd/tools/maya/mel/nativeMaya",
                        "XBMLANGPATH = P:/InProd/tools/maya/icons",
                        "MAYA_PLUG_IN_PATH = P:/InProd/tools/maya/plugins",
                        "PYTHONPATH = P:/InProd/tools/maya/python")
    }
    else {
        $paths = Get-Content $fl
        for ($i = 0; $i -lt $paths.Length; $i++){
            if ($paths[$i] -match "MAYA_SCRIPT_PATH"){
                $paths[$i] = $paths[$i] +";P:/InProd/tools/maya/mel;P:/InProd/tools/maya/mel/nativeMaya"
            }
            if ($paths[$i] -match "XBMLANGPATH"){
                $paths[$i] = $paths[$i] +";P:/InProd/tools/maya/icons"
            }
            if ($paths[$i] -match "MAYA_PLUG_IN_PATH"){
                $paths[$i] = $paths[$i] +";P:/InProd/tools/maya/plugins"
            }
            if ($paths[$i] -match "PYTHONPATH"){
                $paths[$i] = $paths[$i] +";P:/InProd/tools/maya/python"
            }
        }
    }
    if($paths){
        $paths | Out-File $fl
        "paths updated in $fl"
    }
}

It writes the input just fine, I can read it in any text editor, but I noticed the file size is 4 times larger than if I had just typed in the information manually via text editor, also the application this file is for no longer reads it at all, it recognizes the file is there, but no longer tries to read it.

Am I missing something? is there more than just Out-File I need to ensure it's a basic text file?


Solution

  • I propose you to rewrite always your file like this :

    $Content =@"
    MAYA_SCRIPT_PATH =P:/InProd/tools/maya/mel;P:/InProd/tools/maya/mel/nativeMaya
    XBMLANGPATH = P:/InProd/tools/maya/icons
    MAYA_PLUG_IN_PATH = P:/InProd/tools/maya/plugins
    PYTHONPATH = P:/InProd/tools/maya/python
    "@
    
    Get-ChildItem -Path "c:\Users\$env:UserName\Documents\maya\" -file -filter Maya.env -Recurse | %{
        Set-Content -Path $_.FullName -Value $Content -Encoding Default
        "paths updated in " + $_.FullName 
    }