0

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?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
rasonage
  • 53
  • 1
  • 1
  • 9

2 Answers2

1

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 
}
Esperento57
  • 16,521
  • 3
  • 39
  • 45
  • That's quite elegant, I had to keep in mind not to overwrite what was already there if something was already set up, just append (plus I'm a noob at PowerShell). – rasonage Nov 29 '20 at 06:41
0

Ahh I found the answer here

need the -Encoding Default flag on my Out-File line. phew.

rasonage
  • 53
  • 1
  • 1
  • 9