繁体   English   中英

Get-ChildItem刷新/更新

[英]Get-ChildItem refresh/update

对Powershell来说还很陌生,希望有人能指出我正确的方向。 我试图找出是否有一种更干净的方法来实现我在下面的目标? 一旦对第一个Get-ChildItem调用(存储在$ items变量中)返回的文件进行了一些更改,是否可以刷新Get-ChildItem的内容?

在第一个foreach语句期间,我将为返回的所有文件创建日志签名。 完成之后,我需要做的是: 再次获取列表(因为路径中的项目已更改),第二个Get-ChildItem将包括在第一次Get-ChildItem调用期间找到的文件,以及在第一个foreach语句调用时生成的所有logFiles generate-LogFile函数。 所以我的问题是,有没有一种方法可以更新列表,而不必两次调用get-chilItem以及使用两个foreach语句?

感谢您的所有帮助!

--------------这是我根据推荐更改代码的内容--------------

$dataStorePath = "C:\Process"

function print-All($file)
{
    Write-Host "PrintALL filename:"  $file.FullName #Only prints when print-All($item) is called 
}

function generate-LogFile($file)
{
    $logName = $file.FullName + ".log"
    $logFilehandle = New-Object System.IO.StreamWriter $logName
    $logFilehandle.Writeline($logName)
    $logFilehandle.Close()
    return $logName
}

$items = Get-ChildItem -Path $dataStorePath

foreach ($item in $items)
{
    $log = generate-LogFile($item) #Contains full path C:\Process\$fileName.log
    print-All($item) 
    print-All($log) #When this goes to the function, nothing prints when using $file.FullName in the print-All function
}

---------输出----------------

为了进行测试,我在C:\\ Process中有两个文件:fileA.txt和fileB.txt

我将创建两个附加文件fileA.txt.log和fileB.txt.log

最终,我需要对所有四个文件进行处理。 我创建了一个全部打印功能,可以处理所有四个文件。 以下是当前输出。 可以看出,我只获得找到的两个原始文件的输出,而不是创建的两个附加文件的输出(调用print-All($ log)时获得空白行)。 我需要能够使用Get-ChildItem提供的fullpath属性,从而使用FullName

PrintALL filename: fileA.txt
PrintALL filename:
PrintALL filename: fileB.txt
PrintALL filename:

我不清楚您要问的是什么,可以通过generate-LogFile返回创建的日志文件,然后仅在您的文件和日志文件上调用generateRequestData吗? 像这样:

$items = Get-ChildItem -Path $dataStorePath
foreach ($file in $items)
{
    $logFile = generate-LogFile $file 
    generateRequestData $file
    generateRequestData $logFile
}

编辑:

在添加的示例中,您将从generate-LogFile返回一个字符串。 .NET字符串没有FullName属性,因此print-All不会打印任何内容。 要获取所需的FileInfo对象,请使用get-item命令集:

return Get-Item $logName

另外,在此示例中,您无需使用StreamWriter来写入文件,可以使用本机Powershell Out-File Commandlet:

function generate-LogFile($file)
{
    $logName = $file.FullName + ".log"
    $logName | Out-File $logName
    return Get-Item $logName
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM