Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Powershell script not accepting input of dynamic variable value at command line

$
0
0

I have a script that builds a variable based on a counter dynamically, such as name1, name2, name3, etc. If I set the value of the name2 inside the script, it works just fine. If I try to execute the script with a -name2value it doesn't see the value at all. Why can't I set the value of this variable at execution? Script:

Param(
    [string]$DBName,
    [string]$DBType,
    [string]$DBTypeNo,
    [int]$DBCount,
    [int]$DBCounter
)

$DBCount = "2"
#$DBName2 = "Me2"
$DBType="You"

while ($DBCounter -lt $DBCount)
{
 $DBCounter = $DBCounter + 1
 $nametest = (Test-Path Variable:\DBName$DBCounter)
if ($nametest)
    {
    $DBTypeNo = (Get-Variable "DBName$DBCounter" -ValueOnly)
    }
    else
    {
    $DBTypeNo = $DBType + $DBcounter
    }

echo "Count = $DBCounter"
echo "Name set = $nametest"
echo "DbtypeNo = $DBTypeNo"
}

If I use, from the powershell window:

test.ps1 -DBName2 Me2

I get:

Count = 1
Name set = False
DbtypeNo = You1
Count = 2
Name set = False
DbtypeNo = You2

If I uncomment the  "#$DBName2 = "Me2"" and then just run test.ps1, I get:

Count = 1
Name set = False
DbtypeNo = You1
Count = 2
Name set = True
DbtypeNo = Me2

So, it seems if I set it "inside" the script, it works fine, but if I try to pass it in at runtime, no go. I need to pass in the value at runtime. What am I doing wrong, or how can I fix this?

mpleaf


Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>