首页 > 解决方案 > How to append GUID to existing filenames and save to CSV

问题描述

I currently have a CSV which contains 1 column that lists many file FullNames. (ie. "\\server\sub\folder\file.ext").

I am attempting to import this CSV, move the file to a separate location and append a GUID to the beginning of the filename in the new location (ie GUID_File.ext). I've been able to move the files, generate the GUID_ but haven't been able to store and reuse the existing filename.ext, it just gets cut off and the file ends up just being a GUID_. I just am not sure how to store the existing filename for reuse.

$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)"
}

If possible, I'm going to also need to store and place all the new GUID_File.ext back into a CSV and store any errors to another file.

标签: windowsshellpowershellscriptingguid

解决方案


我目前有一个 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可以使用的类型,然后执行其余的逻辑。


推荐阅读