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

时间:2018-08-28 22:24:03

标签: windows shell powershell scripting guid

我目前有一个CSV,其中包含1列,列出了许多文件全名。 (即“ \\ 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并将任何错误存储到另一个文件。

4 个答案:

答案 0 :(得分:1)

  

我目前有一个CSV,其中包含1列,列出了许多文件全名。 (即“ \ 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 :(得分:1)

基于:

  

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

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

Import-Csv的输出是[pscustomobject]实例,它们的 properties 反映了输入CSV的列值,并且这些属性的值始终是 strings

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

如果CSV文件没有标题行,则可以通过将列名称数组传递给Import-Csv的{​​{1}}参数来指定列名称,例如,
-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" } 从完整的输入路径中提取文件名(包括扩展名)。

答案 2 :(得分: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

答案 3 :(得分:0)

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

谢谢大家。