powershell - 测试后停止将值写入屏幕

标签 powershell

我开始写一个可以测试有效IP地址并以此为基础的函数。我的代码工作正常,但是,当IP有效时,它将把有效IP写入屏幕。由于我将添加到此函数中,最终输出将是IP地址等等,因此,我想以某种方式禁止这种行为。

do {
   $ip=$(read-host "Enter an IP address")
   [ref]$a = $null
   $inputOk = [system.net.IPAddress]::tryparse($ip,$a)
   if ($inputOk -eq $false) {
       write-warning ("'{0}' is not a valid IP address, try again." -f $ip)
   }
} until ($inputOk)

输出看起来像这样:
Enter an IP address: 127.0.0.1
127.0.0.1

我希望它不返回刚刚输入的有效IP。

最佳答案

也许这可以帮助您:

Function Test-IP {
    [CmdletBinding()]
    Param (
        $IP
    )

    do {
        $IP = Read-Host "Enter an IP address"

        $Result = [System.Net.IPAddress]::TryParse($IP,[Ref]$null)

        if ($Result) {
            Write-Verbose "Valid IP found: $IP"
            <#
                Do stuff here with the valid IP
            #>
        }
        else {
            Write-Warning ("'{0}' is not a valid IP address, try again." -f $ip)
        }
    } until ($Result)
}

# See progress messages:
Test-IP -Verbose

# Without progress messages
Test-IP

如果创建的函数具有[CmdLetBinding()],则可以使用Verbose开关。要显示脚本/功能的进度,这是要走的路。如果您不希望看到函数中发生了什么,只需忽略Verbose开关即可。

关于powershell - 测试后停止将值写入屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33771105/

相关文章:

unicode - 如何在 PowerShell 字符串文字中对 32 位 Unicode 字符进行编码?

powershell - 我可以在 Windows Powershell ISE 中使用 "break when an exception is thrown"吗?

powershell - 使用管理员权限重新启动 powershell 并继续当前脚本

azure - 如何将输入参数传递给 Start-NewOrchestration powershell 命令 let

powershell - 从 dos 命令文件启动调试 .ps1 文件

linux - 是否可以编写一个在 bash/shell 和 PowerShell 中运行的脚本?

powershell - GetDate 为负 30 分钟并以 UTC 格式显示

javascript - 如何以编程方式(基于PowerShell?,JavaScript?)与基于Chromium的浏览器的GPU进程进行交互,以检测荒谬的内存占用/泄漏?

powershell - 使用以 DisplayName 命名的文件夹导入 GPO - Powershell

powershell - 你能用Powershell编写Windows服务吗