如何使用Powershell从csv文件中获取几行

时间:2019-08-01 12:09:26

标签: powershell

我需要能够将csv文件从一个目录复制/粘贴到另一个目录,以命名第一列,并且仅获得整个文件的3行,并且整个文件每24小时运行一次。

我已经完成了从一个目录到另一个目录的复制/粘贴的前两点并命名了第一列,但是我很难完成第三部分。我只需要整个文件的三行。

这是到目前为止我所做的一些代码:

$Src = 'C:\1From'
$Dst = 'C:\2To'
$header = ‘Scan’

# Wildcard for filter
$Extension = '*_ALL_Scan_Details.csv'

# Get file objects recursively
Get-ChildItem -Path $Src -Filter $Extension -Recurse |
# Skip directories, because XXXReadMe.txt is a valid directory name
Where-Object {!$_.PsIsContainer} |
    # For each file
    ForEach-Object {
        # Copy file
        Copy-Item -Path $_.FullName -Destination $Dst 
    }


# Get file objects recursively
Get-ChildItem -Path $Dst -Filter $Extension -Recurse |
# Skip directories, because XXXReadMe.txt is a valid directory name
Where-Object {!$_.PsIsContainer} 

    ForEach-Object {
        # Add header
       (Import-Csv $_.FullName -Delimiter ",") |
       Select-Object -Skip 1 |
       ConvertFrom-CSV -UseCulture -Header $header | export-csv $_.FullName -Delimiter "," -NoTypeInformation
    }

任何帮助将不胜感激!非常感谢。

2 个答案:

答案 0 :(得分:0)

这显示了一种获取包含指定目标值的文件行的方法。 [ grin ],如果您仍然需要标题行,它将始终是原始集合中的第一项-例如$InStuff[0]

# fake reading in a text file
#    in real life, use Get-Content
$InStuff = @'
P_1, P_2, P_3, P_4
1, One, Wun, Run
2, Two, Tuu, Item
3, Three, Item, Tree
4, Four, Fo, Pho
5, Item, Five, Phyv
6, Six, Ziks, Psiks
'@ -split [System.Environment]::NewLine

$TargetValue = 'Item'

$InStuff -match $TargetValue

输出...

2, Two, Tuu, Item
3, Three, Item, Tree
5, Item, Five, Phyv

答案 1 :(得分:0)

这种方式对我有用。感谢您的帮助。

 # Setup source and destination paths
 $Src = 'C:\1From'
 $Dst = 'C:\2To'
 $header = ‘Scan’

 # Wildcard for filter
 $Extension = '*_ALL_Details.csv'

 ######################################################
 ########   Copy files from src to dest folder  #######

 # Get file objects recursively
 Get-ChildItem -Path $Src -Filter $Extension -Recurse |
 # Skip directories, because XXXReadMe.txt is a valid directory name
 Where-Object {!$_.PsIsContainer} |
     # For each file
     ForEach-Object {
         # Copy file
         Copy-Item -Path $_.FullName -Destination $Dst -Force
     }

 ##########################################################
 #######  Add Dest files a header and override csv  #######

 # Get file objects recursively
 Get-ChildItem -Path $Dst -Filter $Extension -Recurse |
 # Skip directories, because XXXReadMe.txt is a valid directory name
 Where-Object {!$_.PsIsContainer} |
     ForEach-Object {
         # Add header
        (Import-Csv $_.FullName -Delimiter ",") |           
        ConvertFrom-CSV -UseCulture -Header $header | ? Scan -like *Item* | export- 
 csv $_.FullName -Delimiter "," -NoTypeInformation
     }