Powershell通过两个目录迭代并将内容写入CSV

问题描述 投票:1回答:1

我必须将两个目录的内容写入CSV,其中目录1是列1,目录2是列2。

我是Powershell的新手,所以请保持温柔。

这是我尝试过的:

$source_loc = "Z:\Dir1"
$dest_loc = "Y:\Dir2"
$outfile = "C:\Outfile.csv"

$source = get-ChildItem $source_loc
$dest = get-ChildItem $dest_loc

Remove-Item $outfile -ErrorAction Ignore
Add-Content $outfile "Old URL, New URL"

$max = ( $source | Measure-Object ).Count

For ( $i = 0; $i -lt $max; $i++ )
{
    $cur = $source | Select-Object -Index $i | Select Name
    $old = "http://thisisawebsite.web/oldurl/" + $cur

    $cur = $dest | Select-Object -Index $i | Select Name
    $new = "http://thisisawebsite.web/newurl/" + $cur
    $line = $old + ',' + $new
    Add-Content $outfile $line
} 

我遇到的问题是,现在Outfile.csv的输出如下所示:

http://thisisawebsite.web/oldurl/@{Name=File1.ext},http://thisisawebsite.web/newurl/@{Name=File1.ext}
http://thisisawebsite.web/oldurl/@{Name=File2.ext},http://thisisawebsite.web/newurl/@{Name=File2.ext}

当我希望它看起来像这样:

http://thisisawebsite.web/oldurl/File1.ext,http://thisisawebsite.web/newurl/File1.ext
http://thisisawebsite.web/oldurl/File2.ext,http://thisisawebsite.web/newurl/File2.ext

我尝试转换为数组并将其编入索引,但它似乎做了同样的事情。我是否需要对$ cur变量执行substr并忽略前7个字符,然后忽略最后一个?我知道我的代码是垃圾,所以请尽量不要侮辱我。

谢谢! ^。^

windows powershell
1个回答
0
投票

我相信,有一些更简单的方法可以做你想做的事情。然而,快速而肮脏的方法是扩展您选择的“名称”属性。尝试使用以下两行注意的小片段:

$cur = $source | Select-Object -Index $i | Select -ExpandProperty Name


$cur = $dest | Select-Object -Index $i | Select -ExpandProperty Name

这应该选择“name”属性的值而不是包含两者的哈希表。

另一个需要注意的有用的事情是,使用双引号,您不需要在powershell中手动连接变量和字符串。

$new = "http://thisisawebsite.web/newurl/" + $cur

是相同的

$new = "http://thisisawebsite.web/newurl/$cur"
© www.soinside.com 2019 - 2024. All rights reserved.