2016-11-14 83 views
0

我试图从Version.txt文件中获取应用程序版本,通过一堆文件夹循环。这本身并不是什么大问题,但问题是这些文件中还有很多其他的东西。获取文本文件中的版本

例子:

'1.0.0.1' 

'Version - 0.11.0.11' 

'ApplicationName - 1.0.12.89' 

'Definitely some useful information. 
ApplicationName - 1.0.13.0' 

文件总是与版本结束,但没有其他的相关性。每次版本的长度都不相同,因为点之间可能有不同数量的数字。 这让我疯狂。有什么建议么?

+1

嗨,你可以请编辑你的问题,包括你到目前为止尝试过的代码吗? – sodawillow

+0

好吧,如果它的最后一个,得到最后一个字符串并解析它? – 4c74356b41

+0

如果您的输入始终具有上面列出的四种不同输入中的任何一种的格式,那么您可以通过运行'($ version_text -split“ - ”| select -last 1).Trim()'来获得版本号。它也应该与你的其他例子一起工作。这里'$ version_text'包含你的输入字符串,即Version.txt的内容。 – kim

回答

0

溶液1

((get-content "C:\temp\file1.txt" -Tail 1) -split "-|'")[1].Trim() 


#Code decomposed for explain 

#get last row of file 
$lastrowfile=get-content "C:\temp\file1.txt" -Tail 1 

#split last row with - or ' as separator 
$arraystr=$lastrowfile -split "-|'" 

#take element 1 of split and trim final string 
$arraystr[1].Trim() 
+0

这可以很好地工作,但在返回字符串的开始处总是有一个空格键。我可以要求解释一下你的代码吗? –

+0

我已修改我的空间代码并解释我的代码;) – Esperento57

+0

非常感谢!我将它缩短为:(Get-Content $ VersionFilePath -Last 1).Split(“ - |'”)[1] .Trim() –

0

因为版本总是在最后一行,使用Get-Content cmdlet与-tail参数只读最后一行。

(Get-Content 'Your_File_Path.txt' -Tail 1 | Select-String "(?<=-).*(?=')").Matches.Value 

输出:

1.0.13.0 
+0

谢谢Martin,但由于某种原因它不起作用。虽然没有错误。 –

0

这将在文件中搜索出现对他们有一个版本号的所有行,采取然后使用Select-String小命令和选择版本在该文件中匹配最后一行,并返回版本号。

$content = Get-Content 'path\to\your\version.txt' 
$regex = [regex]"\d+(\.\d+)+" 

# Grab the last line in the version file that appears to have a version number 
$versionLine = $content -match $regex | Select-Object -Last 1 

if ($versionLine) { 
    # Parse and return the version 
    $regex.Match($versionLine).Value 
} 
else { 
    Write-Warning 'No version found.' 
} 

与所有您发布的版本号的工作,如果版本号似乎是在文件的结尾会的工作,但有额外的空格之后,等

+0

对不起,它根本不起作用。 –

+0

奇怪。它会抛出一个错误吗?你正在运行哪个版本的PowerShell?我在v5上测试过这个。 –

0

解决方案2

((get-content "C:\temp\file1.txt" | where {$_ -like "*ApplicationName*"} | select -Last 1) -split "-|'")[1] 
0

可以使用Get-内容,然后分:

((get-content "C:\test.txt" | where {$_ -like "*ApplicationName*"} | select -Last 1) -split "-|'")[1]