【问题标题】:reversing slashes in string not replacing original反转字符串中的斜杠不替换原来的
【发布时间】:2019-08-25 08:54:11
【问题描述】:

当我通过 get-childitem 获取 dir 内容时,斜线在 html 验证中的方向错误。我试图通过进行字符替换来解决这个问题,但由于某种原因,每次我尝试打印出斜线时,它的方向都不正确。这是我目前的尝试:

$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
   }
}

当我查看输出文件时,它没有显示反斜杠。

我查看了split pathreplace chars in string,但是当我查看时它没有在输出文件中显示结果。有什么想法吗?

我看到从某处写入屏幕的输出带有正确的斜线。我想也许如果我使用 $_ 直接输出到文件而不改变原始数组,它会修复它。但它也没有奏效。我仍然在输出文件中看到原始斜杠。

【问题讨论】:

  • 您的-replace 操作并未将该更改存储在.fullname 属性中。因此,当您在下一行设置$temp 时,您仍然指的是旧的.fullname 属性。您应该删除整个|%{ },因为$file 已经是一个对象。然后,您的 $temp 分配应使用 ($file.fullname -replace "\\",'/') 代替 $_.Fullname

标签: powershell replace slash


【解决方案1】:

我会重写它以使其更简单并删除不必要的循环:

$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)
   $temp = '<li><a href="' +  ($file.FullName -replace "\\",'/') +  '" target="_app">' + $fileWithoutExtension + '</a></li>'
   Add-Content -Path $filenamePathOut -Value $temp
   }
}

【讨论】:

  • 这些都是很大的帮助。非常感谢!它现在正在工作!
【解决方案2】:

好吧,让我们从您正在尝试做的事情开始,以及为什么它不起作用。如果您查看其中任何文件的文件对象 ($file|get-member),您会看到 FullName 属性只有一个 get 方法,没有 set 方法,因此您无法更改该属性。因此,如果不重命名源文件并再次获取文件信息,您将永远不会更改该属性。

知道,如果您想使用替换的斜杠捕获路径,则需要在变量中捕获替换的输出。然后,您可以使用它来构建您的字符串。

$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}
}

【讨论】:

    猜你喜欢
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 2023-04-03
    • 2011-11-23
    相关资源
    最近更新 更多