gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:56:22 28 4
gpt4 key购买 nike

第一次在这里问一个问题。我是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
任何帮助是极大的赞赏!
谢谢!

最佳答案

发生此现象的原因在于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

关于powershell - 在Powershell中将输出写入文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62839334/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com