michaellwest / PowerShell-Modules

PowerShell modules used for various daily tasks.
25 stars 9 forks source link

-Credential parameter is not implemented #1

Open franckberneron opened 5 years ago

franckberneron commented 5 years ago

The documentation for Invoke-sqlcommand here https://docs.microsoft.com/en-us/powershell/module/sqlserver/invoke-sqlcmd?view=sqlserver-ps

mentions Invoke-sqlcmd can take a PSCredential Object to authenticate against the server. When actually passing -Credential to Invoke-sqlcmd, I get an error stating the -Credential parameter could not be found.

Indeed, reading the synopsis, you can't find it in the available parameters list.

Implementing it would be immensely convenient to avoid passing usernames & passwords and to facilitate scripting.

Thanks !

michaellwest commented 5 years ago

Happy to take a look at it and see what I can do.

michaellwest commented 5 years ago

@franckberneron Can you test out the function from the below commit?

d462fae

franckberneron commented 5 years ago

@michaellwest I'm quite new to Powershell and I can't find how to import your version of the module to test-run it. I tried calling the script directly or calling Import-Module with the file path but still get the NamedParameter error. So I guess I'm not importing it the right way. Would you mind just pointing me out to some documentation so that I can test-run your new version ? Thanks forward...😉

michaellwest commented 5 years ago

@franckberneron Perhaps the easiest way to test is to go to the link below, view raw file, copy and paste into the ISE, and then below add whatever command you want to execute. You'll notice on line 124 I added a check where if the Credential is provided use that.

https://github.com/michaellwest/PowerShell-Modules/blob/d462faeaf2b29542eee956a95696cf589114098d/CorpApps/Invoke-SqlCommand.ps1

$creds = Get-Credential
Invoke-SqlCommand -Server "DATASERVER" -Database "Web" -Query "SELECT COUNT(*) FROM Test.Sample" -Credential $creds
franckberneron commented 5 years ago

@michaellwest I had finally come to that idea after scavenging through dot sourcing, Import-Module -Force and the like...😂

Just done testing it with VS Code and it works perfectly...🍾

I tried it both with a PSCredential object declared using a secure string like this $passwd = Get-Content 'D:\securestring.txt' | ConvertTo-SecureString $SQLServerCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $passwd and one with no $passwd. Connection is seemless when the PSCredential object is well formed and an interactive pop-up asking for username & password shows up when not. So it looks we're all good !😉 Thanks again & congrats !😉 Ps: how do you actually use these scripts? Are you calling them up when needed from your main script or did you convert them into full-blown modules imported in your PS environment?