【问题标题】:PowerShell add full path to filename and copyPowerShell添加文件名的完整路径并复制
【发布时间】:2014-03-06 19:12:16
【问题描述】:

如何在复制过程中将文件夹名称复制到文件名。目前,该脚本仅复制子目录中的文件,而不复制所有文件夹和子文件夹名。但是,我希望在复制时采用绝对路径名。

这里是一个例子: 文件夹 1 子文件夹 1 子文件夹 2 子文件夹 3 子文件夹4 文件 1 文件夹2

然后复制的文件将被称为:

Folder1_Subfolder1_Subfolder2_Subfolder3_Subfolder4_File.pdf

     Powershell code:
     Get-ChildItem –path C:\12  -Recurse -Include "*.???"  |
     Foreach-Object  { copy-item -Path $_.fullname -Destination c:\12 }

【问题讨论】:

  • 如果你这样做,你不只是将它们复制回同一个位置吗?

标签: file powershell copy


【解决方案1】:

好的,如果我的理解正确,您需要一个类似的文件:

C:\12\foo\bar\baz.txt

要复制到:

C:\12\foo_bar_baz.txt

如果我理解正确,那么下面的内容应该可以工作:

function Copy-FileUsePath {
[cmdletbinding()]
    param(
        [parameter(Mandatory=$true,Position=0)][string]$Path,
        [parameter(Mandatory=$true,Position=1)][string]$Destination
    )

    $files = Get-ChildItem -Path $Path -Recurse -Include "*.???"
    foreach ( $file in $files ) {
        $discard = $Destination.Length
        if( $Destination -notlike "*\" ) {
            $discard++
        }
        $newFileName = $file.FullName.Replace('\', '_').Remove( 0, $discard )
        $newFile = $Destination + '\' + $newFileName
        Write-Verbose "Copy-Item -Path $file.fullname -Destination $newFile"
        Copy-Item -Path $file.fullname -Destination $newFile
    }
}

要使用它,请将其保存到一个文件中(我称之为 Copy-FileUsePath.ps1),您可以执行以下操作:

. .\Copy-FileUsePath.ps1
Copy-FileUsePath -Path C:\12 -Destination C:\export

【讨论】:

  • @HunterEdison:我想你想用 .Replace($Destination, "").Remove (0, $Destination.length) 替换 .Substring(3) 以便便携
  • 您好,谢谢您的帮助,是的,您是对的。但是你能不能改变你的函数,这样我就可以把路径和目​​的地作为变量放入源代码中。您可以使用 c:\12 作为路径,使用 c:\export 作为目标 抱歉,我对 powershell 没有太多经验。
  • 如果我调用函数,我会得到错误:Copy-FileUsePath("D:\test\Folder1", "D:\test") error msg=Copy-FileUsePath : Die Argumenttransformation für den Parameter “路径” kann nicht verarbeitet werden。 Der Wert kann nicht in den Typ "System.String" konvertiert werden。贝泽勒:18 蔡臣:17+ Copy-FileUsePath
  • 谢谢,@MatM,我认为我现在拥有的版本更便携(比我应该处理的目标路径上的尾随“\”更麻烦,可能或可能不存在)
  • @HunterEdison:删除 $discard 部分(包括删除)并将$newFile = $Destination + '\' + $newFileName 替换为$newFile = Join-Path $Destination $newFileName。它将为您处理“\”问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-19
  • 1970-01-01
  • 2011-01-08
  • 1970-01-01
  • 2014-09-26
  • 2018-10-20
相关资源
最近更新 更多