我正在尝试创建一个脚本,该脚本将从服务器目录中的多个安装位置查找最新的build_info文件,从每个文件中选择“version:”文本,并比较它们以查看它们是否全部相同(这是我们希望的),或者某些安装位置是否有不同的版本。作为奖励,让每个路径的安装版本都有自己的变量也是很好的,这样如果我必须输出任何差异,我可以说哪些特定路径有哪些版本。例如,如果在Path1,Path2和Path3中安装了某些内容,我希望能够说“所有路径都在3.5版本上”或“Path1是版本1.2,Path2是版本3.5,Path3是版本4.8”。
这是我正在尝试做的更简洁的清单:
这是我到目前为止所写的内容:
$Directory = dir D:\Directory\Path* | ?{$_.PSISContainer};
$Version = @();
foreach ($d in $Directory) {
$Version = (Select-String -Path D:\Directory\Path*\build_info_v12.txt -Pattern "Version: " | Select-Object -ExpandProperty Line) -replace "Version: ";
}
if (@($Version | Select -Unique).Count -eq 1) {
Write-Host 'The middle tiers are all on version' ($Version | Select -Unique);
}
else {
Write-Host 'One or more middle tiers has a different version.';
}
我不得不在最新的build_info文件中使用硬编码,因为我不确定如何将排序方面纳入此方法。我也不确定如何有效地将每个路径的结果分配给变量,如果存在差异则输出它们。就排序方面而言,这就是我一直在搞乱,但我不知道如何合并它,我甚至不确定它是否是正确的方法:
$Recent = Get-ChildItem -Path D:\Directory\Path*\build_info*.txt | Sort-Object CreationTime -Descending | Select-Object -Index 0;
答案 0 :(得分:1)
您可以使用Sort-Object和Select-Object来确定最新的文件。这是一个函数,您可以提供一组文件,它将返回最新的文件:
function Get-MostRecentFile{
param(
$fileList
)
$mostRecent = $fileList | Sort-Object LastWriteTime | Select-Object -Last 1
$mostRecent
}
答案 1 :(得分:0)
以下是一种可能的解决方案:
Get-ChildItem "D:\Directory\Path" -Include "build_info*.txt" -File -Recurse |
Group-Object -Property DirectoryName |
ForEach-Object {
$_.Group |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1 |
ForEach-Object {
New-Object -TypeName PsCustomObject |
Add-Member -MemberType NoteProperty -Name Directory -Value $_.DirectoryName -PassThru |
Add-Member -MemberType NoteProperty -Name FileName -Value $_.Name -PassThru |
Add-Member -MemberType NoteProperty -Name MaxVersion -Value ((Select-String -Path $_.FullName -Pattern "Version: ").Line.Replace("Version: ","")) -PassThru
}
}
这将生成一个对象集合,一个对应于树中的每个目录,具有目录名称,最新版本和我们在其中找到版本号的文件的属性。您可以将这些对象传输到更多cmdlet以进行过滤等。