【问题标题】:Get relative paths of folder and its files with length in mb separate column?在 mb 单独列中获取文件夹及其文件的相对路径?
【发布时间】:2022-11-15 05:47:17
【问题描述】:

我需要在单独的 csv 列中找到文件夹及其长度为 MB 的文件的相对路径,并将该 csv 文件与另一个 csv 文件进行比较,并在绝对路径中的另一个 csv 中打印长度不匹配的文件路径

$srcpth = "C:\Users\vavenkatamanoj\Downloads"
$files = Get-ChildItem -Path $srcpth -File -Recurse

foreach ($f in $files)
{
    $filen = $f.Name
    $relativePath = $f.fullname.remove(0,($srcpth.length))
    $filesize = $f.Length
    Write-Output "$relativePath,$filesize" | Out-File C:\Users\vavenkatamanoj\Downloads\check.csv -Append
}

我尝试使用此脚本来获取具有大小的相对路径。没问题,但文件路径和长度在同一列中返回;我需要单独的列。谁能帮我?

【问题讨论】:

  • 谢谢你
  • 要获取相对路径,您可以使用Resolve-Path-Relative 开关,或使用.Net Path.GetRelativePath()。另外,创建对象使用所需的属性并使用 Export-Csv 创建您的 csv,而不是自己制作行。

标签: powershell


【解决方案1】:
$srcpth = "C:UsersavenkatamanojDownloads" 
$files = Get-ChildItem -Path $srcpth -File -Recurse 
$result = foreach ($f in $files) {

[pscustomobject][ordered]@{
        fileName = $f.Name
        RelativePath  =  $f.fullname.remove(0,($srcpth.length))
        FileSize = $f.Length
    }



}
$result | Export-Csv "c:	empoutput.csv" -NoTypeInformation -Append

使用 PSCustomObject 创建结构化数据。请找到以下链接以获取更多信息: https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-pscustomobject?view=powershell-7.3

【讨论】:

  • 像这样我们有 2csv 文件。现在我需要比较这 2 个 csv 文件并找到不匹配的文件路径并以绝对路径打印。
  • 快速说明,而不是吹毛求疵,PSCustomObject有序的默认。
  • @Rajesh - 在您的问题中,您要求提供两列的结果。请尝试使用比较对象learn.microsoft.com/en-us/powershell/module/…
【解决方案2】:

继续我的评论,

为什么不创建一个包含长度、绝对路径和相对路径的 CSV 文件?

$srcpth = 'C:UsersavenkatamanojDownloads'

# needed for Resolve-Path -Relative
$currentPath = (Get-Location).Path
Set-Location $srcpth
# you could now remove the -Path $srcpth if you like
$result = Get-ChildItem -Path $srcpth -File -Recurse | ForEach-Object {
    # output Objects
    [PsCustomObject]@{
        FileName     = $_.Name
        FileSize     = $_.Length
        RelativePath = $_.FullName | Resolve-Path -Relative
        AbsolutePath = $_.FullName
    }
}

# now, output the data as CSV
$result | Export-Csv -Path 'C:UsersavenkatamanojDownloadscheck.csv' -NoTypeInformation
# restore the current location
Set-Location $currentPath

【讨论】:

  • 不,不 。我有 2 个具有相对路径和长度的 csv 文件。现在我需要比较 csv 文件和输出是两个 csv 中存在的不匹配的文件路径,其绝对路径长度为 mb
  • @Rajesh 抱歉,但现在我不知道你想要什么。比较两个 csv 文件中列出的文件并检查它们的长度是否不同?我想您需要向我们展示那些 csv 文件,并更好地解释您想要的输出内容。一个例子会有所帮助
猜你喜欢
  • 2019-07-13
  • 2017-06-03
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
  • 2014-11-05
相关资源
最近更新 更多