![Powershell 选择一个字符串并在一个单词后](https://linux22.com/image/1580816/Powershell%20%E9%80%89%E6%8B%A9%E4%B8%80%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%B9%B6%E5%9C%A8%E4%B8%80%E4%B8%AA%E5%8D%95%E8%AF%8D%E5%90%8E.png)
我的问题有没有办法选择虚拟名称使用 select-string?我有这些日志,我需要从中选择时间和虚拟帐户名称。我
*> <event seq="453211" time="2019-01-24 11:01:03.639873 -0500" app="hServer 7.45" name="I_SFS_TRANSFER_FILE" desc="Virtual filesystem: transfer file.">
<session id="44500" service="SSH" remoteAddress="00.00.00:57292" virtualAccount="xxxxxxxx" windowsAccount="Server3\Users"/>
<channel type="session" id="1"/>
<sfs moduleName="FlowSfsWin" mountPath="/" code="90000" desc="Transferring file ended.">*
这是我迄今为止尝试过的。
New-Item "C:\clients.log" -type file -force
$strings = "virtualAccount=","time="
Foreach($string in $strings){
Get-Content 'C:\uploads.log'|
Select-String $string1 -AllMatches | % { $_.Matches } | % { $_.Value } |
Add-Content "C:\clients.log"
}
答案1
如果您的代码提供了所需的数据,我猜它不是按照您想要的顺序排列的。我假设您希望将时间戳和帐户名称放在一起,而不是将时间戳分开,然后是帐户名称。我写了下面的示例,它创建了一个 $myInfo 对象,其中包含您想要从日志行获取的信息。我希望它有助于编写您的解决方案。
我不得不说,这些正则表达式不是我的。我很难捕捉引号之间的文本。谷歌帮了我大忙:https://stackoverflow.com/questions/13024073/regex-c-sharp-extract-text-within-double-quotes
foreach ($line in Get-Content 'C:\uploads.log') {
$rslt = $line | Select-String -Pattern 'time=\"([^\"]*)\".*virtualAccount=\"([^\"]*)\"'
$myinfo = [PSCustomObject]@{
Time = $rslt.Matches.Groups[1].Value;
Account = $rslt.Matches.Groups[2].Value
}
$myinfo
}
答案2
这是用单词分割字符串的方法,你可以做你需要做的事情
$str = '<event seq="453211" time="2019-01-24 11:01:03.639873 -0500" app="hServer 7.45" name="I_SFS_TRANSFER_FILE" desc="Virtual filesystem: transfer file.">
<session id="44500" service="SSH" remoteAddress="00.00.00:57292" virtualAccount="xxxxxxxx" windowsAccount="Server3\Users"/>
<channel type="session" id="1"/>
<sfs moduleName="FlowSfsWin" mountPath="/" code="90000" desc="Transferring file ended.">*'
$str2= $str -split ('time=') -split ('app=') -split ('name=') -split ('desc=') -split ('id=') -split ('service=') -split ('remoteAddress=')-split ('virtualAccount=')-split ('windowsAccount=') -split ('channel type=')
Write-host "time=" $str2[1]
Write-host "app=" $str2[2]
Write-host "name=" $str2[3]
Write-host "desc="$str2[4]
Write-host "id="$str2[5]
Write-host "service= "$str2[6]
Write-host "remoteAddress= "$str2[7]
Write-host "virtualAccount= "$str2[8]
Write-host "windowsAccount=" $str2[9]