基本上,我有一个CSV文件,列出了要分析任何丢失文件的目录内容。
我的脚本执行此操作,但我尝试将丢失文件的结果导出到新的CSV文件。
当前脚本:
#get working directory
$documents = 'C:\Users\Me\Documents\ScriptTest'
#path to files located in the directory
$myFolder = Get-ChildItem 'C:\Users\Me\Documents\Test\1' -Recurse -Include *.txt |
Select-Object -ExpandProperty BaseName |
Where-Object{$_ -notmatch "\\FolderName\\"}
#get items located in CSV file list column
$myCSV = Import-CSV -Path 'C:\Users\Me\Documents\Test.csv' |
Select-Object -ExpandProperty 'File Path'
$CSVexport = '\Users\Me\Documents\Test.csv'
$results=@()
$desiredColumns = @{
ID = $CSVexport | Select-Object ID
'File Path' = $CSVexport | Select-Object 'File Path'
}
#split the CSV item names
$splits=@()
foreach($file in $myCSV){
$split = $file.split("\\")[2]
$split2 = $split.split(".")[0]
$splits+=$split2
}
#compare the CSV items to the folder items
$compare = Compare-Object -ReferenceObject $splits -DifferenceObject $myFolder -includeequal
Write-Output "`n_____Results____`n"
#Write the results and export to a CSV file
$compare | ForEach-Object {
if($_.SideIndicator -eq "<="){
write-host "`n$($_.InputObject) is missing from the Test folder.`n"
$results = New-Object PSObject -Property $desiredColumns
$results.'File Path' = $_.InputObject
$results | Export-Csv -Path C:\Users\Me\Documents\Results.csv –NoTypeInformation
}
}
我得到的全部是:
它只获取一个丢失的文件而没有“ID”列。我希望能够获得比较结果并将其导出到包含第一个CSV文件中相关列的新CSV。例如:
我能否得到一些关于我可能做错的事情的帮助?
新守则:
$documents = 'C:\Users\Me\Documents'
$NewCsv = Import-CSV -Path 'C:\Users\Me\Documents\Test.csv' |
Select-Object ID,'File Path' |
ForEach-Object {
if (!(Test-Path (Join-Path $documents $_.'File Path'))){
[PSCustomObject]@{
ID = $_.ID
Missing = $_.'File Path'
}
}
}
$NewCsv
输出:
Name Value
---- -----
ID 4
Missing Test\1\File4.txt
ID 6
Missing Test\1\File6.txt
答案 0 :(得分:0)
非常复杂。
如果你迭代你的csv,检查每个文件的存在并动态生成一个新的csv,它可以很简单:
## Q:\Test\2018\05\24\SO_50517360.ps1
$BasePath = "C:\Users\Me\Documents"
$NewCsv = Import-CSV -Path '.\Test.csv'|Select-Object ID,'File Path' |
ForEach-Object {
if (!(Test-Path (Join-Path $BasePath $_.'File Path'))){
[PSCustomObject]@{
ID = $_.ID
Missing = $_.'File Path'
}
}
}
$NewCsv
示例输出(可以通过
将其放入新文件中
$NewCsv|Export-Csv .\Missing.csv -NoTypeInformation
> .\SO_50517360.ps1
ID Missing
-- -------
4 Test\1\File4.txt
6 Test\1\File6.txt