从基于 CSV 文件的目录复制文件

Copy file from a directory based on CSV file

我现在有一些关于 PowerShell 中的代码的问题。

我想在 PowerShell 中编写脚本,根据 CSV 文件将文件从一个文件夹复制到另一个现有文件夹:

例如,我的 CSV 文件中有两列:一列是没有扩展名的文件名,一列是我要将文件复制到的路径。

csv 示例:

File,Pathdestinationfile
test1_000,C:/Documents/test1

所以我需要从 C:/Source 等路径获取我的文件,并将其复制到我的 CSV 中提到的特定目标文件路径。

这是我目前拥有的代码,但它不起作用:

Import-CSV C:\Users\T0242166\Documents\SCRIPT_CSV\testscript.csv | 
    Where-Object Name -Like $_.File | 
        foreach { Copy-item  -Path "C:/Source" -Destination $_.Filepathdestination -Recurse }

你能帮我解决这个问题吗?

谢谢

我在脚本中提供了注释以帮助您理解我在做什么。

(注意:这个可以压缩,但我把它分开了,这样你更容易看。)

# Define your constant variable    
$sourceFolder = "C:\Source"


# Import Your CSV
$content = Import-Csv "C:\Users\T0242166\Documents\SCRIPT_CSV\testscript.csv"


# Iterate Through Your Objects From CSV
foreach ($item in $content)
{
    # Find the file you are looking for
    $foundFile = Get-Item -Path ($sourceFolder + "$($item.File).*")

    # Copy the file using the FullName property, which is actually the full path, to your destination defined in your csv file.
    Copy-Item $foundFile.FullName -Destination ($item.Pathdestinationfile)

}

精简版:

# Import and Iterate Through Your Objects From CSV
foreach ($item in (Import-Csv "C:\Users\T0242166\Documents\SCRIPT_CSV\testscript.csv"))
{
    # Find the file you are looking for and copy it
    Copy-Item "C:\Source$($item.File).*" -Destination $item.Pathdestinationfile
}

另一个浓缩版:

Import-Csv "C:\Users\T0242166\Documents\SCRIPT_CSV\testscript.csv" | foreach { Copy-Item "C:\Source$($_.File).*" -Destination $_.Pathdestinationfile }

虽然您一直在文件路径中使用正斜杠,但在 PowerShell 中这会起作用:

# import the data from the CSV file and loop through each row
Import-CSV -Path 'C:\Users\T0242166\Documents\SCRIPT_CSV\testscript.csv' | ForEach-Object {
    # get a list of FileInfo objects based on the partial file name from the CSV
    # if you don't want it to find files in subfolders of "C:\Source", take off the -Recurse switch
    $files = Get-ChildItem -Path "C:\Source" -Filter "$($_.File).*" -File -Recurse
    foreach ($file in $files) {
        $file | Copy-Item -Destination $_.Pathdestinationfile
    }
}