如何将GUID附加到现有文件名并保存为CSV

问题描述 投票:2回答:4

我目前有一个CSV,其中包含1列,列出了许多文件的FullNames。 (即“\\ server \ sub \ folder \ file.ext”)。

我正在尝试导入此CSV,将文件移动到单独的位置,并将GUID附加到新位置的文件名的开头(即GUID_File.ext)。我已经能够移动文件,生成GUID_但无法存储和重用现有的filename.ext,它只是被切断,文件最终只是一个GUID_。我只是不确定如何存储现有的文件名以供重用。

$Doc = Import-CSV C:\Temp\scripttest.csv

ForEach ($line in $Doc)
{
 $FileBase = $Line.basename 
 $FileExt = $Line.extension 
Copy-Item -path  $line.File -Destination "\\Server\Folder\$((new-guid).guid.replace('-',''))_$($Filebase)$($FileExt)"
}

如果可能的话,我还需要将所有新GUID_File.ext存储并放回CSV并将所有错误存储到另一个文件中。

windows shell powershell scripting guid
4个回答
0
投票

如果我仔细阅读你的问题,你想:

  • 复制“文件”列中CSV文件中列出的文件。
  • 新文件应该在文件名前加上GUID
  • 您需要一个新的CSV文件,其中存储新的文件名以供以后参考
  • 您想要跟踪任何错误并将其写入(日志)文件

假设您有一个输入CSV文件,如下所示:

File,Author,MoreStuff
\\server\sub\folder\file.ext,Someone,Blah
\\server\sub\folder\file2.ext,Someone Else,Blah2
\\server\sub\folder\file3.ext,Same Someone,Blah3

然后下面的脚本希望你想要的。它通过在GUID前面添加文件名来创建新文件名,并将列File中列出的CSV中的文件复制到某个目标路径。它在目标文件夹中输出一个新的CSV文件,如下所示:

OriginalFile,NewFile
\\server\sub\folder\file.ext,\\anotherserver\sub\folder\38f7bec9e4c0443081b385277a9d253d_file.ext
\\server\sub\folder\file2.ext,\\anotherserver\sub\folder\d19546f7a3284ccb995e5ea27db2c034_file2.ext
\\server\sub\folder\file3.ext,\\anotherserver\sub\folder\edd6d35006ac46e294aaa25526ec5033_file3.ext

任何错误都列在日志文件中(也在目标文件夹中)。

$Destination = '\\Server\Folder'
$ResultsFile = Join-Path $Destination 'Copy_Results.csv'
$Logfile     = Join-Path $Destination 'Copy_Errors.log'
$Doc         = Import-CSV C:\Temp\scripttest.csv

# create an array to store the copy results in
$result = @()
# loop through the csv data using only the column called 'File'
ForEach ($fileName in $Doc.File) {
    # check if the given file exists; if not then write to the errors log file
    if (Test-Path -Path $fileName -PathType Leaf) {
        $oldBaseName = Split-Path -Path $fileName.Path -Leaf
        # or do $oldBaseName = [System.IO.Path]::GetFileName($fileName)
        $newBaseName = "{0}_{1}" -f $((New-Guid).toString("N")), $oldBaseName
        # (New-Guid).toString("N") returns the Guid without hyphens, same as (New-Guid).Guid.Replace('-','')

        $destinationFile = Join-Path $Destination $newBaseName
        try {
            Copy-Item -Path $fileName -Destination $destinationFile -Force -ErrorAction Stop
            # add an object to the results array to store the original filename and the full filename of the copy
            $result += New-Object -TypeName PSObject -Property @{
                'OriginalFile' = $fileName
                'NewFile'      = $destinationFile
            }
        }
        catch {
            Write-Error "Could not copy file to '$destinationFile'"
            # write the error to the log file
            Add-content $Logfile -Value "$((Get-Date).ToString("yyyy-MM-dd HH:mm:ss")) - ERROR: Could not copy file to '$destinationFile'"
        }
    }
    else {
        Write-Warning "File '$fileName' does not exist"
        # write the error to the log file
        Add-content $Logfile -Value "$((Get-Date).ToString("yyyy-MM-dd HH:mm:ss")) - WARNING: File '$fileName' does not exist"
    }
}
# finally create a CSV with the results of this copy.
# the CSV will have two headers 'OriginalFile' and 'NewFile'
$result | Export-Csv -Path $ResultsFile -NoTypeInformation -Force

1
投票

我目前有一个CSV,其中包含1列,列出了许多文件的FullNames。 (即“\ server \ sub \ folder \ file.ext”)。

这不是CSV。它只是一个带有列表的纯文本文件。

但是,您可以通过以下方式实现目标:

foreach ($path in (Get-Content -Path C:\Temp\scripttest.csv))
{
    $file = [System.IO.FileInfo]$path
    $prefix = (New-Guid).Guid -replace '-'
    Copy-Item -Path $file.FullName -Destination "\\Server\Folder\${prefix}_$file"
}

这将获取您的列表,将项目转换为可以使用的FileInfo类型,并执行其余的逻辑。


1
投票

基于:

$FileBase = $line.basename $FileExt = $line.extension

听起来你错误地认为代表从$line返回的对象的Import-Csv C:\Temp\scripttest.csv实例是[System.IO.FileInfo]实例,但它们不是:

Import-Csv输出的是[pscustomobject]实例,其属性反映了输入CSV的列值,并且这些属性的值总是字符串。

因此,您必须使用$line.<column1Name>来引用包含完整文件名的列,其中<column1Name>是为输入CSV文件的标题行(第1行)中感兴趣的列定义的名称。

如果CSV文件没有标题行,您可以通过将列名称数组传递给Import-Csv-Header参数来指定列名称,例如, Import-Csv -Header Path, OtherCol1, OtherCol2, ... C:\Temp\scripttest.csv

我将假设感兴趣的列在以下解决方案中命名为Path

$Doc = Import-Csv C:\Temp\scripttest.csv

ForEach ($rowObject in $Doc)
{
  $fileName = Split-Path -Leaf $rowObject.Path
  Copy-Item -Path $rowObject.Path `
            -Destination "\\Server\Folder\$((new-guid).guid.replace('-',''))_$fileName"
}

请注意Split-Path -Leaf如何用于从完整输入路径中提取文件名,包括扩展名。


0
投票

感谢大家的解决方案。他们都工作和运作良好。我选择Theo作为他的解决方案解决了错误记录并将所有新重命名的文件与GUID_File.ext new存储到现有CSV信息这一事实的答案。

谢谢你们。

© www.soinside.com 2019 - 2024. All rights reserved.