首页 > 解决方案 > PowerShell 函数单独运行时可以正常工作,但在被另一个函数跟随时停止工作。为什么?

问题描述

第一个功能将单独工作。

功能:

function Get-Search {

    $find = Read-Host "Type of Git to search"
    $url = 'https://github.com/search?q=' + $find
    Write-Host ""
    Write-Host "Here is a list of the top 10 results:"
    $contributors = Invoke-WebRequest -Uri $url -UseBasicParsing
    $contributors.Links| where class -EQ "v-align-middle" | select href 

}                                 

Get-Search

它可以正确打印我在搜索输入中输入的内容(Linux)。

Type of Git to search: Linux

Here is a list of the top 10 results:

href                        
----                        
/torvalds/linux             
/raspberrypi/linux          
/jaywcjlove/linux-command   
/0xAX/linux-insides         
/GameServerManagers/LinuxGSM
/judasn/Linux-Tutorial      
/endlessm/linux             
/beagleboard/linux          
/linuxkit/linuxkit          
/afaqurk/linux-dash

这是正确的输出。

但是当我添加以下功能时:

function Get-Search {

    $find = Read-Host "Type of Git to search"
    $url = 'https://github.com/search?q=' + $find
    Write-Host ""
    Write-Host "Here is a list of the top 10 results:"
    $contributors = Invoke-WebRequest -Uri $url -UseBasicParsing
    $contributors.Links| where class -EQ "v-align-middle" | select href 

}                                 

Get-Search

function Get-Menu {
    
    Write-Host 
    "
    Options:

    Want to explore a 'Git-README'? Type 1
    Want to load a 'Git-Repo'? Type 2
    Want to make a new search? Type 3

    "
    $choice = Read-Host "Type number here"
    Write-Host ""
    $pick1 = if ([string]1 -eq $choice )

    {
    $add = Read-Host "Add an above repo here"
    $url2 = 'https://raw.githubusercontent.com/' + $add + '/master/README.md'
    $contributors = Invoke-WebRequest -Uri $url2 -UseBasicParsing
    $contributors.Links| where class "p" | select innerText
    }

}

Get-Menu

第一个功能停止工作:

Type of Git to search: Linux

Here is a list of the top 10 results:


Type number here:

搜索到的列表现在丢失了。

为什么?

标签: powershell

解决方案


Write-Host 
"
Options:

Want to explore a 'Git-README'? Type 1
Want to load a 'Git-Repo'? Type 2
Want to make a new search? Type 3

"

是不同的命令:

  1. Write-Host它不向显示器输出任何内容(换行除外)
  2. 其余的是放在管道上的字符串,类似于. 输出 ( ) 具有与 object 不同的属性,另请参阅:PowerShell write-output missing information - prints only 1st objectWrite-Output ...
    string$contributors

在 PowerShell 中,通常不需要Write-Output在默认显示输出的情况下使用 cmdlet。

因此,正确的语法是:

Write-Host "

Options:

Want to explore a 'Git-README'? Type 1
Want to load a 'Git-Repo'? Type 2
Want to make a new search? Type 3

"

(报价应直接在之后Write-Host


推荐阅读