我需要解析文件名并根据部分文件名将文件移动到文件夹。
假设我在文件夹C:\ SYSLOG \ Servers和Firewall \ Logs中有多个文件。它们是来自几个不同服务器或设备的日志文件。我需要将它们移动到我们的NAS进行存档。示例文件名:
Boston.North.Application.S01.120613.log
Boston.South.Application.S12.122513.log
Lexington.System.S02.073013.log
Lexington.System.S22.073013.log
Madison.IPS.S01.050414.txt
我需要将它们移动到NAS上的相应文件夹。我的文件夹结构如下所示:
\\NAS\Logs\Boston North Application
\\NAS\Logs\Boston South Application
\\NAS\Logs\Lexington System
\\NAS\Logs\Madison IPS
所以基本上我想解析服务器左侧的所有文件名(Sxx),并替换。用空格来创建目标文件夹名称。
文件并不总是.log文件。所有文件名称中都包含.Sxx,xx始终为数字。如果目标文件夹不存在,则跳过该文件。 C:\ SYSLOG \ Servers和Firewall \ Logs中没有子文件夹。
我想我正在尝试做类似于powershell to move files based on part of file name
的事情答案 0 :(得分:1)
如果您只是用空格替换.
,请依赖文件中的所有内容直到Sxx块为目的地:
# Retrieve the filenames
$Directory = "C:\SYSLOG\Server and Firewall\Logs"
$FileNames = (Get-Item $Directory).GetFiles()
foreach($FileName in $FileNames)
{
# Split the filename on "."
$Pieces = $FileName-split"\."
# Counting backwords, grab the pieces up until the Sxx part
$Start = $Pieces.Count*-1
$Folder = $Pieces[$Start..-4]-join" "
# Build the destination path
$Destination = "\\NAS\Logs\{0}\" -f $Folder
# Test if the destination folder exists and move it
if(Test-Path $Destination -PathType Container)
{
Move-Item -Path $FileName -Destination $Destination
}
}
答案 1 :(得分:0)
最终版本。
# Retrive list of files
# $sDir = Source Directory
$sDir = "C:\Temp\Logs\"
# Generate a list of all files in source directory
$Files = (Get-ChildItem $sDir)
# $tDir = Root Target Directory
$tDir = "C:\Temp\Logs2\"
# Loop through our list of file names
foreach($File in $Files)
{
# $wFile will be our working file name
$wFile = $File.Name
# Find .Sx in the file name, where x is a number
if ($wFile -match ".S0")
{
# tFile = Trimmed File Name
# We now remove everything to the right of the . in the .Sx of the file name including the .
$tFile = $wFile.substring(0,$wFile.IndexOf('.S0'))
}
# If we do not find .S0 in string, we search for .S1
elseif ($wFile -match ".S1")
{
$tFile = $wFile.substring(0,$wFile.IndexOf('.S1'))
}
# If we do not find .S0, or S1 in string, then we search for .S2
elseif ($wFile -match ".S2")
{
$tFile = $wFile.substring(0,$wFile.IndexOf('.S2'))
}
# Now we exit our If tests and do some work
# $nfold = The name of the sub-folder that the files will go into
# We will replace the . in the file name with spaces
$nFold = $tFile.replace("."," ")
# dFold = the destination folder in the format of \\drive\folder\SubFolder\
$dFold = "$tDir$nFold"
# Test if the destination folder exists
if(Test-Path $dFold -PathType Container)
{
# If the folder exists then we move the file
Move-Item -Path $sDir$File -Destination $dFold
# Now we just write put what went where
Write-Host $File "Was Moved to:" $dFold
Write-Host
}
# If the folder does not exist then we leave it alone!
else
{
# We write our selves a note that it was not moved
Write-Host $File "Was not moved!"
}
# Now we have a drink!
}