David Brand
David Brand

Reputation: 3

Can't get it to provide proper output

I have this function and I can not get it to work, the $DecimalConversion output is not coming out.. I think I am having some syntax errors.

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

Upvotes: 0

Views: 77

Answers (2)

David Brand
David Brand

Reputation: 3

Final code, I think this looks better, let me know what you think!

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 } } }

Upvotes: 0

Sid
Sid

Reputation: 2676

You could probably use a better while condition. However, ur issue is caused because of the out-null cmdlet on read-host.

If you use that, $GetDecimal will not get the value you pass in since the out-null is processed before the assignment happens. Just remove it. And it should work.

Upvotes: 2

Related Questions