PowerShell循环文件夹,按文件名和位置搜索,然后替换
问题描述:
我想为我的程序使用一个循环,该文件夹只在该目录的文件夹和子文件夹中获取.dll
的文件名。然后它搜索具有相同文件名的.dll
的指定位置/路径,如果存在,则替换它。到目前为止,我的程序将所有文件从一个位置复制到另一个位置,一旦它们被复制,我需要将上述内容制定出来。PowerShell循环文件夹,按文件名和位置搜索,然后替换
我最大的问题是如何在指定位置的循环中通过文件名进行搜索,如果存在,请将其替换为?在我使用服务器和其他驱动器放置正确路径之前,下面的代码在本地随机出现。
#sets source user can edit path to be more precise
$source = "C:\Users\Public\Music\Sample Music\*"
#sets destination
$1stdest = "C:\Users\User\Music\Sample Music Location"
#copies source to destination
Get-ChildItem $source -recurse | Copy-Item -destination $1stdest
#takes 1stdest and finds only dlls to variable
#not sure if this is right but it takes the .dlls only, can you do that in the foreach()?
Get-ChildItem $1stdest -recurse -include "*.dll"
答
在这里你去,你需要编辑你的路回去。另外,还要注意$1stDest
改为枚举目标文件夹中的文件列表。
逻辑遍历$ source中的所有文件,并在$1stDest
中查找匹配项。如果它发现一些,它将它们存储在$OverWriteMe
中。代码然后遍历每个文件被覆盖并复制它。
正如所写,它使用了-WhatIf
,所以您将预览运行之前会发生什么。如果你喜欢你所看到的,去掉-WhatIf
上线15
$source = "c:\temp\stack\source\"
#sets destination
$1stdest = get-childitem C:\temp\stack\Dest -Recurse
#copies source to destination
ForEach ($file in (Get-ChildItem $source -recurse)){
If ($file.BaseName -in $1stdest.BaseName){
$overwriteMe = $1stdest | Where BaseName -eq $file.BaseName
Write-Output "$($file.baseName) already exists @ $($overwriteMe.FullName)"
$overwriteMe | ForEach-Object {
copy-item $file.FullName -Destination $overwriteMe.FullName -WhatIf
#End of ForEach $overwriteme
}
#End Of ForEach $file in ...
}
}
输出
1 already exists @ C:\temp\stack\Dest\1.txt
What if: Performing the operation "Copy File" on target "Item: C:\temp\stack\source\1.txt Destination: C:\temp\stack\Dest\1.txt".
5 already exists @ C:\temp\stack\Dest\5.txt
What if: Performing the operation "Copy File" on target "Item: C:\temp\stack\source\5.txt Destination: C:\temp\stack\Dest\5.txt".
有与上面的代码中的错误。 “你必须在' - '运算符的右边提供一个值表达式。”我将如何去解决这个问题? – user6124417
再次尝试并复制它,我想我之前有一个额外的空间。如果仍然失败,请使用pastebin链接回复此主题以确认您的确切代码,我会帮您解决这个问题。 – FoxDeploy