0

I have a PowerShell Script that will invoke a command on a remote server. I'm trying to set this script up so that I can pass in a service parameter and it will drop that specific table in MongoDB

$service = "DatabaseName"

$username = "username"
$password = "password"

$pass = ConvertTo-SecureString -AsPlainText $password -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $pass

Invoke-Command -ComputerName Remote-Server1 -Credential $cred -ArgumentList $service -ScriptBlock {
    param($service) 
    & 'C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe' $service --eval 'db.dropDatabase()'
}

Invoke-Command -ComputerName Remote-Server2 -Credential $cred -ArgumentList $service -ScriptBlock {
    param($service) 
    & 'C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe' $service --eval 'db.dropDatabase()'
}

If I were to use the following it does not drop the MongoDB database:

& 'C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe' $service --eval 'db.dropDatabase()'

However, If I use the following it works as expected:

& 'C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe' DatabaseName --eval 'db.dropDatabase()'

Why does it work when I hard code that database name but not when I use a variable.

1 Answer 1

1

Since your code only needs $service in a read-only manner you can use the Using:-scope modifier, see additional information here.

Based on that you can change the code to:

$service = "DatabaseName"
$username = "username"
$password = "password"

$pass = ConvertTo-SecureString -AsPlainText $password -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $pass

Invoke-Command -ComputerName Remote-Server1 -Credential $cred -ArgumentList $service -ScriptBlock {
    & 'C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe' $Using:service --eval 'db.dropDatabase()'
}

Invoke-Command -ComputerName Remote-Server2 -Credential $cred -ArgumentList $service -ScriptBlock {
    & 'C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe' $Using:service --eval 'db.dropDatabase()'
}

When performing remote commands via Invoke-Command I either use the Using modifier of prefix the variables in the param block with remote. Based on that I can avoid "unwanted" behaviors (as the one you stated above).

So another alternative would be:

Invoke-Command -ComputerName Remote-Server1 -Credential $cred -ArgumentList $service -ScriptBlock {
    param($remoteService)
    & 'C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe' $remoteService --eval 'db.dropDatabase()'
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.