在 PowerShell 脚本中的这段代码中,它根据文件名中的编号将文件移动到具有正确编号的相应导出文件夹中。
例如,在本例中,它将把文件名中包含 472 的文件移动到名为 472 的导出文件夹中。
不幸的是,有时(看似随机)似乎会将 472 文件移至 047 文件夹中。我觉得这不是巧合,因为两者都存在 47 个。
Foreach ($file in $fileArray)
{
$siteDir = getSiteIDFromFileName($file);
writeToLog "Site Dir: $sitedir";
$eodFull = $eodBaseLocation + $siteDir + '/exports/';
以下功能
function getSiteIDFromFileName
{
Param ([string]$fileName)
[int]$returnedInt = -1;
$siteID = $file.name.Substring(4,3);
[bool]$isNumber = [int32]::TryParse($siteID, [ref]$returnedInt)
if($isNumber -AND ($returnedInt -gt 0))
{
return '{0:d3}' -f $returnedInt;
}
}
文件数组
if ($env -eq 'Test')
{
$fileArray = @(Get-ChildItem -Path $exportLocation | Where-Object {! $_.PSIsContainer -AND ($_.Name -Match "MFILE") -AND ($_.Name -NotMatch "transferred") -AND ($_.Name -NotMatch "TEST")});
}
else
{
$fileArray = @(Get-ChildItem -Path $exportLocation | Where-Object {! $_.PSIsContainer -AND ($_.Name -Match "MFILE") -AND ($_.Name -NotMatch "transferred")});
}
最困扰我的是它是断断续续的。
您可以完全不使用该功能
getSiteIDFromFileName
并使用正则表达式 -replace 代替(有关详细信息,请参阅下文)。
此外,如果将开关 ! $_.PSIsContainer
附加到 Get-ChildItem 命令,则不需要 -File
,并且可以通过过滤名称中包含“MFILE”的文件来加快速度。
尝试以下
# create a regex string for the -notmatch operator, depending if $env equals 'Test' or not
$excluded = if ($env -eq 'Test') { 'transferred|test' } else { 'transferred' }
$fileArray = @(Get-ChildItem -Path $exportLocation -Filter '*MFILE*' -File | Where-Object {$_.Name -notmatch $excluded})
foreach ($file in $fileArray) {
# get the three digits from the file name directly after 'MFILE'
$siteDir = $file.Name -replace '^.*MFILE(\d{3}).*', '$1'
# invoke your script to write the siteId to a log file
writeToLog "Site Dir: $sitedir"
# create the full target path to move the file to
$eodFull = Join-Path -Path ('{0}{1}' -f $eodBaseLocation, $siteDir) -ChildPath 'exports'
# if needed, create the target folder
$null = New-Item -Path $eodFull -ItemType Directory -Force
# move the file
$file | Move-Item -Destination $eodFull
}
正则表达式详细信息
^ Assert position at the beginning of the string
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
MFILE Match the characters “MFILE” literally
( Match the regular expression below and capture its match into backreference number 1
\d Match a single digit 0..9
{3} Exactly 3 times
)
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)