我现在有一个程序输出文件名到控制台。
我想给它一系列目录来搜索(按顺序)搜索以找到该文件名,如果找到它,则复制到另一个目录。
我到目前为止:
[string]$fileName = "document12**2013" #** for wildcard chars
[bool]$found = false
Get-ChildItem -Path "C:\Users\Public\Documents" -Recurse | Where-Object { !$PsIsContainer -and GetFileNameWithoutExtension($_.Name) -eq "filename" -and $found = true }
if($found = true){
Copy-Item C:\Users\Public\Documents\ c:\test
}
目前我有两个问题。我只知道如何查看一个目录,我不知道如何指定脚本来复制我刚刚找到的特定文件。
答案 0 :(得分:3)
Path参数接受一组路径,因此您可以指定多个路径。您可以使用Filter参数获取所需的文件名,并将结果通过管道传递到Copy-Item
cmdlet:
Get-ChildItem -Path C:\Users\Public\Documents,$path2,$path3 -Recurse -Filter $fileName |
Copy-Item -Destination $Destination
答案 1 :(得分:0)
您可以在一个管道中完成所有这些工作:
$folders = 'C:\path\to\folder_A', 'C:\path\to\folder_B', ...
$folders | Get-ChildItem -Recurse -Filter filename.* |
? { -not $_.PSIsContainer } | Copy-Item -Destination 'C:\test\'
请注意,如果您在Copy-Item
中使用文件夹作为目标,则必须具有结尾反斜杠,否则cmdlet将尝试将文件夹C:\test
替换为文件C:\test
,会导致错误。
答案 2 :(得分:0)
将它包装成函数怎么样?
使用Shay的方法:
function copyfile($path,$fileName,$Destination) {
Get-ChildItem -Path $path -Recurse -Filter $fileName |
Copy-Item -Destination $Destination
}
$path1=C:\Users\Public\Documents
$path2=C:\Users\Public\Music
$path3=C:\Users\Public\Pictures
copyfile $path1 corporate_policy.docx \\workstation\c$\users\Public\Documents
copyfile $path2 intro_from_ceo.mp3 \\workstation\c$\users\Public\Music
copyfile $path3 corporate_logo.jpg \\workstation\c$\users\Public\Pictures