无法获得正确的输出

时间:2020-03-25 19:46:14

标签: function powershell

我具有此功能,但无法正常工作,$ DecimalConversion输出未输出。.我认为我遇到一些语法错误。

function Get-DecimalNumber(){
$FileCheck = Test-Path "C:\Conversions\conversions.csv"
if($FileCheck){
Do
{
[int]$GetDecimal = Read-host "Write a number between 1-255" | Out-Null
}
while ($GetDecimal -notmatch '\d{1,3}' -or (1..255) -notcontains $GetDecimal)
$DecimalConversion= "{0:X}" -f $GetDecimal
$DecimalConversion
}
else{Write-Warning "Can not find conversions.csv, creating now under C:\Conversions\"; New-Item "C:\Conversions\conversions.csv" -Force | Out-Null}
}
$getfunction=Get-DecimalNumber

2 个答案:

答案 0 :(得分:2)

您可能会使用更好的while条件。但是,您的问题是由于out-null上的read-host cmdlet引起的。

如果使用它,$GetDecimal将不会获得您传递的值,因为out-null在分配发生之前就已处理。只需将其删除。而且应该可以。

答案 1 :(得分:0)

最终代码,我认为它看起来更好,请告诉我您的想法!

function Get-DecimalNumber { <# .Description The Get-DecimalNumber function gets user input for a decimal number and converts it into hexadecimal and binary numbers. Then this data is added to an excel file (.csv) and the date of conversion is displayed in short form m/d/yyyy. #> $ErrorActionPreference = 'silentlycontinue' #Silences errors $Test = Test-Path "C:\temp\test\conversions.csv" #Variable to test path if (! $Test) { #Checking if path does not exist Write-Warning "conversions.csv File Not Present, creating under C:\temp\test\" New-Item 'C:\temp\test\conversions.csv' -Force | Out-Null; break; exit #Creating path with file & suppressing output } else { [int]$Num = Read-Host "Enter number from 1-255" if ($Num -gt 255 -or $Num -le 1) { Write-Warning "You did not enter a number in the specified range"; break; exit } else { $Hex = [Convert]::ToString($Num, 16) #Converting from decimal to hexadecimal $Bin = [Convert]::ToString($Num, 2) #Converting from decimal to binary Write-Host "Decimal to Hex and Binary:" $NewHashTable1 = @{ } #Creating hashtable $NewHashTable1.Add('Decimal', $Num) #Adding values from variables to hash table $NewHashTable1.Add('Hexadecimal', $hex)
$NewHashTable1.Add('Binary', $bin) $NewHashTable1 #Output to screen the previously created hashtable $NewHashTable1 >> "C:\temp\test\conversions.csv" #Appending hashtable to .csv file Write-Output "'n" Get-Date -Format d #Output date in short format $Now = Get-Date -Format d $Now >> "C:\temp\test\conversions.csv" #Output date to .csv file } } }