【问题标题】:How to prevent random output?如何防止随机输出?
【发布时间】:2021-12-17 16:47:43
【问题描述】:

当我运行我的脚本时,它会添加一个我没有请求的输出。

$input = Read-Host -p "Message?";
$morseFile = Get-Content C:\Users\lukas.downes\Documents\Script\morse.csv
$letter;
$code;
$outputAsString = "";


for ($j = 0; $j -lt $input.Length; $j++)
{
    for ($i = 1; $i -lt $morseFile.Length; $i++)
    { 
        $letter = ([string]$morseFile[$i]).Split(',')[0];
        $code = ([string]$morseFile[$i]).Split(',')[1];

        if ($input[$j] -eq $letter) 
        {
            $outputAsString += $code;
            write-host ("" + $letter + ": " + $code)
        }

    }
}

Write-Host $outputAsString

这个输出:

> Message?: sos 
> Z
> --.. 
> S: ... 
> O: --- 
> S: ... 
> ...---...

这很奇怪,因为我什至没有在我的脚本中使用“Z”。

【问题讨论】:

  • 删除 $letter;$code; 行 - PowerShell 中的变量不需要声明,您看到的垃圾输出很可能是上次运行时这些变量的内容。
  • morse.csv 真的是 CSV(逗号分隔值)文件吗?它有标题吗?

标签: powershell scripting


【解决方案1】:

如果您的输入 csv morse.csv 看起来像这样:

Letter,Code
O,---
P,.--.
Q,--.-
R,.-.
S,...

那么这应该适合你:

# import the csv as array of objects
$codes = Import-Csv -Path 'C:\Users\lukas.downes\Documents\Script\morse.csv'
# for more speed, change this array of objects into a lookup Hashtable
$morse = @{}
foreach ($item in $codes) {
    $morse[$item.Letter] = $item.Code
}

$inputString = Read-Host -p "Message?"
if (![string]::IsNullOrWhiteSpace($inputString)) {
    $inputString.ToUpper().ToCharArray() | ForEach-Object {
        '{0}: {1}' -f $_, $morse[$_.ToString()]  # or: $morse["$_"]
    }
}

输入'sos'时,输出为:

S: ...
O: ---
S: ...

附:不要使用$input作为自定义变量,因为它是一个Automatic variable

【讨论】:

    猜你喜欢
    • 2012-06-28
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 2014-01-01
    相关资源
    最近更新 更多