Search code examples
powershellreplaceslash

reversing slashes in string not replacing original


When I get-childitem to get dir contents, the slashes are in the wrong direction for html validation. I'm trying to fix this by doing a character replace, but for some reason, every time I try to print out the slashes, it's not in the right direction. This is my current try:

$filenameOut = "out.html"

#get current working dir
$cwd = Get-ScriptDirectory #(Get-Location).path #PSScriptRoot #(Get-Item -Path ".").FullName
$filenamePathOut = Join-Path $cwd $filenameOut

$InitialAppointmentGenArr = Get-ChildItem -Path $temp 

foreach($file in $InitialAppointmentGenArr)
{
   $fileWithoutExtension = [io.path]::GetFileNameWithoutExtension($file)
   #$file = $file -replace "\\", "/" #this didn't work
   $file | % {
      $_.FullName.ToString() | % {$_ -replace '\\','/'} #Replace("\\","/")
      $temp = '<li><a href="' +  $_.FullName +  '" target="_app">' + $fileWithoutExtension + '</a></li>'
      Add-Content -Path $filenamePathOut -Value $temp
   }
}

When I look at the output file, it's not showing the reversed slashes.

I looked at split path, and also replace chars in string, but it's not showing the results in the output file when I look. Any idea?

I'm seeing output written to screen from somewhere with slashes correct. I thought maybe if I use $_ to output directly to the file and not change in the original array, it would fix it. But it didn't work either. I still see original slashes in the output file.


Solution

  • Well, let's start with what you are attempting to do, and why it isn't working. If you look at the file object for any of those files ($file|get-member), you see that the FullName property only has a get method, no set method, so you can't change that property. So you are never going to change that property without renaming the source file and getting the file info again.

    Knowing that, if you want to capture the path with the replaced slashes you will need to capture the output of the replace in a variable. You can then use that to build your string.

    $filenameOut = "out.html"
    
    #get current working dir
    $cwd = Get-ScriptDirectory #(Get-Location).path #PSScriptRoot #(Get-Item -Path ".").FullName
    $filenamePathOut = Join-Path $cwd $filenameOut
    
    $InitialAppointmentGenArr = Get-ChildItem -Path $temp 
    
    foreach($file in $InitialAppointmentGenArr)
    {
       $filePath = $file.FullName -replace "\\", "/"
       '<li><a href="' +  $filePath +  '" target="_app">' + $file.BaseName + '</a></li>' | Add-Content -Path $filenamePathOut}
    }