2016-11-23 63 views
1

我已经编写了一个脚本,试图确定最大编号。每列的字符。这是我写的:尝试确定每列中字符的最大数量

$path = 'folder path' 
$file = Get-ChildItem $path\* 
$FileContent = foreach ($files in $file) { 
    $FileHeader = @((Get-Content $files -First 1).Split($delimiter)) 
    $importcsv = @(Import-Csv $files -Delimiter "$delimiter") 
    for ($i=0; $i -lt $FileHeader.Length; $i++) { 
     #select each column 
     $Column = @($importcsv | select $FileHeader[$i]) 

     #find the max no. of character 
     $MaxChar = @(($Column[$i] | 
        Select -ExpandProperty $FileHeader[$i] | 
        Measure-Object -Maximum -Property Length).Maximum) 

     $output = New-Object PSObject 

     $output | Add-Member NoteProperty FullName ($files.FullName) 
     $output | Add-Member NoteProperty FileName ($files.Name) 
     $output | Add-Member NoteProperty Time (Get-Date -Format s) 
     $output | Add-Member NoteProperty FileHeader ($($FileHeader[$i])) 
     $output | Add-Member NoteProperty MaxCharacter ($($MaxChar[$i])) 

     Write-Output $output 
    } 
} 

上面的脚本只是它的一部分,所以$delimiter已定义。最后我会将结果导出为CSV。

脚本运行时没有任何错误,但是当我打开文件时,它只给了我第一列/标题的最大数量。的字符,其余的列/标题丢失。

完美的结果将显示每个列/标题最大号。的性格。

我的循环有问题吗?

我的老板正试图创建一个自动化过程来查找原始数据中的所有信息并使用这些信息上传到数据库,因此缺少的脚本部分是关于确定原始文件的分隔符, $CleanHeader$FileHeader的全新版本(删除所有特殊字符,将大写字母转成小写字母),那些清理程序将用于数据库表中的标题。并且他还想知道每列中的最大字符数,以便信息可以使用它们在数据库中的表中创建列的大小(他知道这部分可以在sql中完成),但是他问我可以在PowerShell中完成或不完成。

+0

为什么你需要知道最大字符数?而你列的是什么意思?你在问如何找到名字很长的文件? –

+1

PowerShell中的功能很少,因此对于“可以在PowerShell中执行XXX”问题的回答几乎总是“是”。真正的问题是:实施XXX需要多少努力? –

回答

0

这应该工作:

$ht = @{} 

# import a CSV and iterate over its rows 
Import-Csv $f.FullName -Delimiter "$delimiter" | ForEach-Object { 
    # iterate over the columns of each row 
    $_.PSObject.Properties | ForEach-Object { 
    # update the hashtable if the length of the current column value is greater 
    # than the value in the hashtable 
    if ($_.Value.Length -gt $ht[$_.Name]) { 
     $ht[$_.Name] = $_.Value.Length 
    } 
    } 
} 

# create an object for each key in the hashtable 
$date = Get-Date -Format s 
$ht.Keys | ForEach-Object { 
    New-Object -Type PSObject -Property @{ 
    FullName  = $f.FullName 
    Name   = $f.Name 
    Time   = $date 
    FileHeader = $_ 
    MaxCharacter = $ht[$_] 
    } 
} 
+0

我测试了它,它的工作原理,我对PowerShell很陌生,所以我有几个初学者的问题,是$ _ =(Import-csv ...),这是否正确?那么$ _是什么意思?我知道$ ht是散列表,所以$ ht [$ _。Name]是什么意思?谢谢 – gshtong

+0

'$ _'是当前的对象变量(保存管道中的当前对象)。请参阅['about_Automatic_Variables'](https://technet.microsoft.com/en-us/library/hh847768.aspx)。 –

0

FileHeader[$i]用引号返回列名的"ColumnName"代替ColumnName

要解决,只需添加一个微调到你拉头行:

$FileHeader = @((Get-Content $files -First 1).Split($delimiter).trim('"'))