使用 PowerShell 的命名约定中的文件名示例:
SYSTEM_20201019-01_PRE 文件夹
- SYSTEM_20201118_文件1.txt
- SYSTEM_20201118_文件2.csv
- SYSTEM_20201118_文件3_和文件4.txt
SYSTEM_20201019-01_POST 文件夹
- SYSTEM_20201119_文件1.txt
- SYSTEM_20201119_文件2.csv
- SYSTEM_20201119_文件3_和文件4.txt
我们使用了这个惯例并且它工作得很好,就像“SYSTEM_file1.txt“在我们添加日期之前。如果我们在其中包含日期,我们的脚本将仅在日期匹配时才比较它们(这是有道理的)。这主要是因为文件名在之前和之后通常相同。但是,有时日期会发生变化,我们只需手动重命名之前的所有文件,然后它就可以正常工作。我们希望减轻其他人的手动工作。
有没有办法可以采用 PRE 和 POST 并重新定义它们,解析出前 XX 个字符,以便仅根据第二个_
字符后的名称进行比较?文件名、文件名长度和扩展名各不相同,所以我需要从头开始,而不是从尾开始。
完整代码如下:
if($changeStatus -eq "POST"){
Write-Host "`n`n*********************************************"
Write-Host "`nComparing all PRE/POST files for differences."
$folderPath = $changeID + "_" + $env:COMPUTERNAME + "_"
$postFolderPath = $folderPath + "POST"
$preFolderPath = $folderPath + "PRE"
$comparisonFile = "$postFolderPath\Output_Comparison.txt"
if(!(Test-Path $preFolderPath)){
Write-Host "Missing PRE folder with the associated ChangeID. Unable to perform comparison."
Write-Host "Press any key to exit......"
Read-Host
exit
}
else{
$fileName = Get-ChildItem -Path $postFolderPath | Select-Object -ExpandProperty Name
ForEach ($file in $fileName){
$preFile = Get-Content ($preFolderPath + "\" + $file)
$postFile = Get-Content ($postFolderPath + "\" + $file)
$comparisonOutput = Compare-Object $preFile $postFile | Where-Object {($_.SideIndicator -eq "=>") -and (($_.InputObject -replace '"',"") -ne $dateRan)} | Select-Object -ExpandProperty InputObject
if($comparisonOutput -ne $null){
if(Test-Path $comparisonFile){
"`r`n`r`nDifference in file $file" | Add-Content -Path $comparisonFile
$comparisonOutput | Add-Content -Path $comparisonFile
}
else{
"The following are the diffences found in POST files:" | Out-File -FilePath $comparisonFile
"`r`nDifference in file $file" | Add-Content -Path $comparisonFile
$comparisonOutput | Add-Content -Path $comparisonFile
}
}
}
}
}
答案1
您没有展示任何代码,但您应该这样做,以避免我们的假设和猜测,并更好地从我们这里获得指导;但如果我得到您的用例,有几种方法可以解决这个问题。
# Break the string into an array
'SYSTEM_20201118_file1.txt'.Split('_')
# Results
<#
SYSTEM
20201118
file1.txt
#>
# Grab the first array item and change it, then join them back together
'SYSTEM_20201118_file1.txt'.Split('_')[0]
# Results
<#
SYSTEM
#>
# Or just replace a specific string
'SYSTEM_20201118_file1.txt' -replace 'SY','SX'
# Results
<#
SXSTEM_20201118_file1.txt
#>
根据您下面所述的评论进行更新
重构时不使用拆分,而是使用正则表达式。
Clear-Host
(Get-ChildItem -Path 'D:\Temp' -Filter 'System_*').FullName
# Results
<#
D:\Temp\SYSTEM_20201119_file1.txt
D:\Temp\SYSTEM_20201119_file2.csv
D:\Temp\SYSTEM_20201119_file3_and_file4.txt
#>
Clear-Host
Get-ChildItem -Path 'D:\Temp' -Filter 'System_*' |
# Use regex to get the last the string after the last underscore
ForEach-Object {[regex]::Matches($PSItem.BaseName, '[^_]+$').Value}
# Results
<#
file1
file2
file4
#>
然后根据这些结果做你想做的事。