gpt4 book ai didi

powershell - 脚本帮助重命名-复制-移动

转载 作者:行者123 更新时间:2023-12-03 00:16:39 25 4
gpt4 key购买 nike

我正在尝试编写PowerShell脚本来执行以下操作。

  • 根据源文件“Source_list.csv”,使用“current_name_datetime.csv”重命名源(FTP文件夹)目录中的文件,该文件的目录为“source,destination”,我希望此脚本可以查看该目录。
  • 根据Source_list.csv中的目标,将新重命名的文件复制到备份目录中。该文件的目录为“source,destination”,我希望此脚本查看该目录。
  • 将新重命名的文件移动到最终目标目录,该目录不在我当前的脚本中。

  • Source_list.csv内容

    cscenter,Costume_Supercenter

    fkimports,FKI导入

    我的剧本:

    $sdfiles = Get-Content c:\!tony\Source_list.csv
    $sourceDir = "c:\test\"
    $destinationDir = "c:\testing\"

    Get-ChildItem $sourceDir -Recurse -Include $sdfiles "*.csv"|
    ForEach-Object{
    $newname= "{0}{1}_{2}.csv" -f $destinationDir, $_.BaseName, [datetime]::Now.ToString('MM-dd-yyyy-hh-mm-ss')
    $_|Copy-Item -Include ,$sdfiles -Destination $newname -whatif }

    错误:
    What if: Performing operation "Copy Directory" on Target "Item: C:\test\cscenter Destination: C:\testing\cscenter_10-01-2015-12-22-24.csv".

    我在错误中看到它试图复制目录而不是每个目录中的单个文件,并尝试使用原始文件夹名称创建新文件夹,并重命名该文件夹并附加日期/时间戳。

    最佳答案

    困惑。 -Include参数应仅接受单个字符串数组,将"*.csv"放在其末尾将无法使用AFAIK。另外,它将解释CSV的整个行,即搜索文件“cscenter,Costume_Supercenter”,因此不应返回任何内容。至少当我在计算机上复制此文件时,会看到这些。

    最后,您尝试过过滤文件,将其通过管道传输到Copy-Item并尝试再次进行过滤?

    我会采取一种更简单的方法:

    $sdfiles = Import-CSV c:\!tony\Source_list.csv -Header @("File", "Folder")

    $sourcedir = "c:\test\"
    $destinationdir = "c:\testing\"

    $sdfiles | ForEach-Object {
    $path = $sourcedir + $_.File + ".csv"
    $folder = $destinationdir + $_.Folder + '\'
    if (!(Test-Path $folder)) { New-Item -Type Directory -Path $folder }
    if (Test-Path ($path))
    {
    $newname = "{0}{1}_{2}.csv" -f $folder, $_.File, (Get-Date).ToString('MM-dd-yyyy-hh-mm-ss')
    Copy-Item -Path $path -Destination $newname -whatif
    }
    else { Write-Error "File $($_.File) not found" }
    }

    它有点笨拙,但更易于阅读和调整。请注意,Import-CSV确实需要PowerShell v3。让我知道您是否拥有v2,并且需要帮助来对其进行二维数组调整。

    我还建议您浏览Microsoft在PowerShell上的MVA类(class),它们是入门的绝佳资源。

    关于powershell - 脚本帮助重命名-复制-移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32894170/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com