这是一个场景:我们有一个生产Web服务器,它有几千个附加了“_DATE”的文件和文件夹.我们希望将它们移动到临时文件夹(确保它们未被使用),并在以后删除文件.
我可以用:
Get-ChildItem -Path W:\IIS -Recurse | Where-Object{$_.Name -match "_\d{8,10}$"}
获取所有文件/文件夹及其位置的列表.但手动删除它们似乎都需要做很多工作,特别是如果将来需要这样做的话.我找到了几个几乎可以做我想要的例子:
cls
$source = "W:\IIS"
$destination = "C:\Temp\DevTest"
foreach ($i in Get-ChildItem -Path $source -Recurse)
{
if ($i.Name -match "_\d{8,10}$")
{
Copy-Item -Path $i.FullName -Destination $item.FullName.ToString().Replace($source,$destination).Trim($item.Name)
}
}
和:
cls
$source = "W:\IIS"
$destination = "C:\Temp\DevTest"
$bin = Get-ChildItem -Path $source -Recurse | Where-Object{$_.Name -match "_\d{8,10}$"}
foreach ($item in $bin) {
Copy-Item -Path $item.FullName -Container -Destination $item.FullName.ToString().Replace($source,$destination).Trim($item.Name) -Recurse
}
这两个问题是,当我用copy-item测试它们时,我最终得到一个平面目录,我需要保留目录结构,这样如果移动出错我可以恢复(最好通过拖放所有文件夹回到IIS文件夹)或者我得到了许多额外文件夹/文件的副本,这些文件夹/文件在我运行第一个命令时没有出现.
修改我的第一个命令:
Get-ChildItem -Path W:\IIS -Recurse | Where-Object{$_.Name -match "_\d{8,10}$"} | Copy-Item -Container -Destination C:\Temp\DevTest -Recurse
将复制我需要的所有东西,但使用平面目录树,而不是保留树结构(但用目的地替换源目录).
有什么建议/意见吗?
您可以使用以下内容,这似乎可以完成工作(虽然它可以使用一些重构).核心是ProcessFolder(…),它被递归调用.
function Log
{
param($Error)
if(!$script:log)
{
$script:log = join-path $dst "log$timestamp.txt"
}
$timestamp
$timestamp >> $script:log
$Error
$Error >> $script:log
}
function CopyFile
{
param($Path)
$tmp = join-path $dst $Path.Substring($src.Length)
write-host "File src: $Path"
write-host "File dst: $tmp"
Try
{
#copy the file
copy $Path $tmp -Force
}
Catch
{
Log "ERROR copying file $Path to $tmp`:`
$_"
}
}
function ProcessFolder
{
param($Path)
$tmp = join-path $dst $Path.Substring($src.Length)
write-host "Dir. src: $Path"
write-host "Dir. dst: $tmp"
Try
{
#create target directory
New-Item $tmp -itemtype directory -force > $null
#process files if they match
dir $Path | ?{!$_.PsIsContainer -and $_.Name -match "_\d{8,10}$" } | sort | %{ CopyFile $_.FullName }
#process subdirectories
dir $Path | ?{$_.PsIsContainer} | sort | %{ ProcessFolder $_.FullName }
#remove target directory if it contains no files on any level
if( !(dir $tmp -recurse | ?{!$_.PsIsContainer}) ) { del $tmp -recurse }
}
Catch
{
Log "ERROR copying folder $Path to $tmp`:`
$_"
}
}
cls
$src = "W:\IIS\"
$dst = "C:\Temp\DevTest\"
$log = $null
$timestamp = '{0:yyyyMMddHHmmssfffffff}' -f (Get-Date)
ProcessFolder $src
''
'DONE!'
if( $log )
{
echo "Check the log file: $log"
}
Read-Host
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。