cloudnyn3
cloudnyn3

Reputation: 897

Conversion function not working correctly

So I'm taking a powershell class and am trying to create a script that converts feet into meters. this is what I have so far but it's not working correctly. I've been tinkering with it for about an hour but can't quite get it to operate properly.

Write-Host Hey there. This is an easy script that will convert Feet to Meters - ForegroundColor Cyan -BackgroundColor Magenta
PAUSE;
Function script:converttometers($feet)
{
    "$feet feet equals $($feet*.31) Meters"
} #end Converttometers

Converttometers -feet $feet(Read-Host)

I'm having trouble getting it to take the input from read-host. Doesn't want to use it for some reason =/

Upvotes: 1

Views: 132

Answers (1)

Keith Hill
Keith Hill

Reputation: 201662

Try calling your function like this:

ConvertToMeters -feet (Read-Host -prompt "Enter feet")

Also be aware that when you write a message to the console using Write-Host and you don't quote the string, PowerShell will remove extra spaces and commas. And if you have to be careful with - because Powershell might try to interpret the following text as a parameter. Subsequently I recommend just using quotes:

Write-Host 'Hey there. This is an easy script that will convert Feet to Meters' -ForegroundColor Cyan -BackgroundColor Magenta

BTW that's a horrible color combination. :-)

The other problem you are running into is due to $feet being a string rather than a number. Try it like this:

Write-Host 'Hey there. This is an easy script that will convert Feet to Meters' -Fore Cyan -Back Magenta 
PAUSE 

Function ConverTo-Meters($feet) { 
    "$feet equals $(.31*$feet) meters" 
} 

ConvertTo-Meters -feet (Read-host -prompt "Enter Feet")

Another way you could solve this is to specify the type of $feet e.g.:

Function Converttometers([double]$feet) { ... }

The way you have it now, PowerShell is using a feature where you can take a string and repeat it e.g.:

"a" * 4 # outputs aaaa

Since you specified .31 which is less than one, you get an empty string as result e.g.:

("10" * .31).length # outputs 0

Upvotes: 1

Related Questions