将字符数与常量值进行比较,然后执行next语句

时间:2016-09-25 19:39:55

标签: powershell powershell-v2.0 powershell-v3.0 powershell-v4.0 powershell-remoting

我有一个PowerShell脚本,我从文件中获取某个字符串的计数,然后转到下一步或仅在字符串计数为30时执行下一步。

我有获取字符串计数的代码,以及执行下一步的代码。唯一缺少的是合并if声明。

要获取字符串计数,我使用以下内容:

$FileContent = Get-Content "YourFile.txt"
$Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches

要进行下一步,我正在使用以下内容;

"d:/scripts/plink.exe" -ssh %1 -l hpov -pw NDIA123 -m %com%|find "host" >>%lnm%

如何在上述两个代码之间包含if条件,以便只有当字符串的数量超过30时才会跟随最后一个命令?

2 个答案:

答案 0 :(得分:1)

首先,不要将$Matches用于用户定义的任何内容 - 它是an automatic variable

顺便说一句:由于Select-String可能会返回多行,您应该按长度排序并测试最长行的长度:

$FileContent = Get-Content "YourFile.txt"
$LongestMatch = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches |Sort-Object {$_.Line.Length} |Select-Object -Last 1

if($LongestMatch.Line.Length -gt 30){
    # We found a match in a string longer than 30 chars!
    # run plink here!
}

答案 1 :(得分:0)

这可能过于简单了。我觉得在这个问题上我肯定会遗漏一些东西。

$FileContent = Get-Content "YourFile.txt"
$Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches

if ($Matches -eq 30) {
    & "d:/scripts/plink.exe" -ssh %1 -l hpov -pw NDIA123 -m %com%|find "host" >>%lnm%
}