Why isn’t my PowerShell function accepting parameters?

0
8
Asked By CuriousCoder123 On

I'm having trouble with a PowerShell function I wrote. I've got other functions working fine, but this one isn't accepting the parameter as expected. Here's the code:

```powershell
# 1. Set input variable
$domainInput = "test"

# 2. Define the function
function Set-Domain {
param (
[string]$input
)

Write-Host "Input is: $input"

if (-not $input) {
Write-Host "[ERROR] No input was found."
}

if ($input -eq "true") {
return "@dynamicdomain.dk"
}
else {
return "@$input"
}
}

# 3. Call the function
Write-Host $domainInput
Set-Domain -input $domainInput
Write-Host "Result: $domain"

Set-Domain -input "true"
```

The output I'm getting is confusing:
```
test
Input is:
[ERROR] No input was found.
@
Result: @
Input is:
[ERROR] No input was found.
@
```

I can't figure out why `$input` has no value inside the function. Can anyone help?

1 Answer

Answered By PowerShellNinja42 On

The issue here is that `$input` is a reserved automatic variable in PowerShell. That means it's already being used by the system, which is why it doesn't hold your assigned value. Try renaming your parameter to something else, like `$input1`, and it should work just fine!

CodeGuru99 -

Yes, and if you were using VS Code, it would have warned you about using a reserved name.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.