简体   繁体   中英

Powershell parameter passing to function

I'm facing with an annoying problem: my script seemingly doesn't pass any argument to a function I've defined.

$server = 'http://127.0.0.1:8080'

Function Get-WorkingDirectory([string]$address)
{
    #echo $address

    $content = Get-Content -path C:\....\file.txt 
    $content -contains $address
} #end Get-WorkingDirectory function



if(Get-WorkingDirectory $server)
{
    echo "works"
}
else
{
    echo "error"
}

It is stuck on "works". If I try to echo address in the function, it is empty. What the heck I'm doing wrong?! I know this is a pretty noobish question, but I tried everything I found on the net. Thanks in advance for help!

Output of Get-WorkingDirectory is shadowed by if statement.

Try to use it without if and you'll see that argument is passed correctly. For example,

$server = 'http://127.0.0.1:8080'

Function Get-WorkingDirectory([string]$address)
{
    Write-Host $address
} 

Get-WorkingDirectory $server

Address is printed well

echo is an alias for Write-Output but as you are using the output of the function in the if statement, nothing gets shown.

For testing purposes, use Write-Host in this instance to show the variable being passed correctly.

$server = 'http://127.0.0.1:8080'

Function Get-WorkingDirectory([string]$address)
{
    write-host "$address using write host"
} #end Get-WorkingDirectory function


if (Get-WorkingDirectory $server) {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM