在Powershell中将输出写入文件时出现问题

时间:2020-07-10 17:19:17

标签: powershell

第一次在这里提问。我是Powershell的新手,并尝试使用它来获取具有保存在.txt文件中的路径的几个文件的最后写入时间。我必须要处理约9000个CAD文件,目前正在练习。下面是我要工作的内容,但是当我尝试将其写入文件时,它给我一个错误,并且我不知道如何解决它。

这就是我正在工作的:

> foreach($line in get-content
> c:\users\jcuthbertson\desktop\filesforgettingdate.txt) {
> if($line -match $regex){
> -join((get-item $line).lastwritetime,",", (get-item $line).name)}}
6/24/2020 11:38:42 AM,Book1.xlsx
6/30/2020 4:16:47 PM,Book2.xlsx
7/10/2020 7:37:31 AM,dwg_vwx_mcd files.xlsx
7/7/2020 9:43:30 AM,Program cleaning flow sequences.xlsx
7/9/2020 8:49:14 AM,vxw paths commas.xlsx

但是当我添加“ out-file”命令时,它给了我错误提示说有空管道

> foreach($line in get-content
> c:\users\jcuthbertson\desktop\filesforgettingdate.txt) {
> if($line -match $regex){
> -join((get-item $line).lastwritetime,",", (get-item $line).name)}} | out-file c:\users\jcuthbertson\desktop\testdatawrite.txt
At line:3 char:68
+ ... get-item $line).lastwritetime,",", (get-item $line).name)}} | out-fil ...
+                                                                 ~
An empty pipe element is not allowed.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : EmptyPipeElement

任何帮助将不胜感激! 谢谢!

2 个答案:

答案 0 :(得分:3)

这是对AdminOfThings good answer的补充。如果您是PowerShell的新手,我认为您可能希望看到另一个选择。您可以使用ForEach-Object cmdlet,该cmdlet允许您直接利用管道。

$File = 'c:\temp\Test_Input.txt'

Get-Content $File |
ForEach-Object{
    If( $_ -match $RegEx ) {
        $Item = Get-Item $_
        $Item.LastWriteTime, $Item.Name -join ','
    }
} |
Out-File c:\temp\test_output.txt -Append

也许这是偏好和环境的问题,但是通过拥抱管道,它将提高内存效率。不要误会我的意思,内存通常不是问题,但是通过子表达式$(...)或通过存储在变量中来预先收集对象之间是有区别的。前一个答案中的选项2和3将整个输出存储到文件中,然后再将其写入文件。另外,上一个答案的选项1是反复打开和关闭文件。

也不必多次运行Get-Item,因此我介绍了$Item。但是,在任何示例中都可以进行修改。

让我知道是否有帮助。

答案 1 :(得分:0)

发生此现象的原因是foreach脚本块实际上没有向管道输出任何内容。具有流水线功能的输出来自-join循环内的foreach运算符。这为您提供了一些将数据管道传输到Out-File的选项。

选项1:将-join的结果传送到Out-File

foreach($line in get-content c:\users\jcuthbertson\desktop\filesforgettingdate.txt) {
    if($line -match $regex){
        -join ((get-item $line).lastwritetime,",",(get-item $line).name) |
            Out-File c:\users\jcuthbertson\desktop\testdatawrite.txt -Append
    }
}

请注意,使用-Append开关不会在每次迭代时覆盖文件。

选项2:捕获变量中的输出并将其内容传递给管道

$output = foreach($line in get-content c:\users\jcuthbertson\desktop\filesforgettingdate.txt) {
    if($line -match $regex){
        -join ((get-item $line).lastwritetime,",",(get-item $line).name)
    }
}
$output | Out-File c:\users\jcuthbertson\desktop\testdatawrite.txt

选项3:使用子表达式operator foreach

强制$()脚本块为表达式
$(foreach($line in get-content c:\users\jcuthbertson\desktop\filesforgettingdate.txt) {
    if($line -match $regex){
        -join ((get-item $line).lastwritetime,",",(get-item $line).name)
    }
}) | Out-File c:\users\jcuthbertson\desktop\testdatawrite.txt