如何仅显示文本文件数组中的Read-Host值?

时间:2018-03-30 21:45:23

标签: arrays powershell foreach

我有一个文本文件数组JobTitle.txt,如下所示:

Sales Co-Worker, TSALES, TSALSK 
Business Navigator, BNOM, BNOMD

我想编写一个代码来读取用户的输入并显示来自同一行的第二个和第三个值。这是我写的:

$jobtitledb = Get-Content C:\Users\Username\Desktop\Scripts\JobTitle.txt
$jobtitleinput = Read-Host 'Input the job title'
foreach ($data in $jobtitledb) {
    $jobtitleinput, $basic, $extended = $data -split ','
    Write-Host "Basic template is: "$basic
    Write-Host "Extended template is: "$extended
}

我似乎无法弄清楚如何让它只返回所需的行。为了澄清,当我输入 Sales Co-Worker 时,我希望程序返回:

  

基本模板是:TSALES
  扩展模板是:TSALSK

3 个答案:

答案 0 :(得分:2)

您只需要一个if语句,检查以确保您的输入与其在每行读取的作业标题相同。

$jobtitledb = Get-Content C:\Users\Username\Desktop\Scripts\JobTitle.txt
$jobtitleinput = Read-Host 'Input the job title'
foreach($data in $jobtitledb) {
 $jobtitle, $basic, $extended = $data -split ','
  If ($jobtitle -eq $jobtitleinput) {
   Write-host "Basic template is: "$basic
   Write-host "Extended template is: "$extended
  }
}

此外,我认为当您阅读每一行时,您将作业标题分配给与用户输入相同的变量,因此您也应该更改它。上面的代码应该可以工作。

答案 1 :(得分:1)

这是一个带注释的脚本,可以解决您的问题。它与原始版本大致相同,除非我将其更改为存储$jobtitle中的记录而不是$jobtitleinput的作业磁贴,并添加了if语句。还添加了$jobnotfound变量和代码以打印相应的消息

$jobtitledb = Get-Content C:\Users\Username\Desktop\Scripts\JobTitle.txt
$jobtitleinput = Read-Host 'Input the job title'
$jobnotfound = $ftrue
foreach($data in $jobtitledb)
{
    # Store the job title from the record in $jobtitle instead of 
    # overwriting $inputjobtitle
    $jobtitle, $basic, $extended = $data -split ','
    # check the $jobtitle from record against the $jobtitleinput
    if ($jobtitle -match $jobinputtitle)
    {
        Write-host "Basic template is: "$basic
        Write-host "Extended template is: "$extended
        $jobnotfound = $false
        break
    }
}
if ($jobnotfound)
{
    Write-Host "No job matching '$jobinputtitle' was found."
}

答案 2 :(得分:0)

  

我添加了一个" else"声明,否则{Write-Host'鉴于职称   不存在'但它为每一行运行一次。如何让它回归   只有1行"给定的职称不存在"?

我还无法发表评论,但您应该只能在其他语句中使用break来退出foreach循环。

----------编辑----------

以下内容应提供所需的输出。

$jobtitledb = Get-Content C:\Users\Username\Desktop\Scripts\JobTitle.txt
$jobtitleinput = Read-Host 'Input the job title'
$found = $false
foreach($data in $jobtitledb) 
{
 $jobtitle, $basic, $extended = $data -split ','
  If ($jobtitle -eq $jobtitleinput) {
   Write-host "Basic template is: "$basic
   Write-host "Extended template is: "$extended
   $found = $true
   break
  }
}
if(!$found)
{
    Write-Host "Given job title does not exist"
}