Thanks Don, nice explanation around Register-PSSessionConfiguration which I was not aware of. In fact, I visited the url
where I read “create a new Remoting Configuration to load your SQL Items into your profile…”.
Anyway, here is the story behind all this mess. I am implementing a POC for SQL Database continuous integration using flywayDB and Jenkins where I need to use a Jenkins powershell job to delete and create a database on a remote server as follows (this was my starting point as I am new to PS remoting)
[blockquote]$password = ConvertTo-SecureString “mypassword” -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential [“mydomain\myuser”, $password ]
Enter-PSSession -ComputerName SQL2K12 -Credential $cred
Push-Location
Import-Module sqlps -DisableNameChecking
$databaseName = “HRDB”
$serverPath = “SQLSERVER:\SQL\SQL2K12\default”[/blockquote]
…
…
The statement Import-Module was failing when it was run from the jenkins platform but same code worked fine from ISE or the PS command prompt on the same machine. Not knowing well the “Remoting with powershell correctly”, I thought this forcing of loadind sqlps in the profile for each session will help which did not and by accident I came across this Set-location issue which you are absolutly correct.
To make a long story short, after posting this thread, I browsed MSDN and read about
[blockquote]New-PSSession and using invoke-command -session $session -scriptblock {…
[/blockquote]So I changed my code as follows which is working like a charm
[blockquote]$session = New-PSSession sql2k12 -Credential $cred
invoke-command -session $session -scriptblock { Set-ExecutionPolicy -ExecutionPolicy Unrestricted ; $databaseName = “payroll”; $serverPath = “SQLSERVER:\SQL\SQL2K12\default”; invoke-sqlcmd -query “sp_databases” -database master -serverinstance localhost | format-table; $databasePath = Join-Path $serverPath “Databases$databaseName”}
[/blockquote]
then issung all other commands using invoke-command
[blockquote]invoke-command -session $session -scriptblock {
if [Test-Path $databasePath]
{
Invoke-SqlCmd -ServerInstance SQL2K12 “USE [master]; ALTER DATABASE [$databaseName] set SINGLE_USER WITH ROLLBACK IMMEDIATE ; DROP DATABASE [$databaseName]”
}
}
[/blockquote]
Then
[blockquote]invoke-command -session $session -scriptblock { Invoke-SqlCmd -ServerInstance SQL2K12 “CREATE DATABASE [$databaseName]” }
[/blockquote]
So it seems to me that even when we have a handle for a remote session, we should always use "invoke-command " in order to make the commands run remotely, do you agree? Once you confirm, I will write a blog on this .
2 questions now, in any case when I get into the sql drive on the command line, how do I revert back to my C: drive.
2nd, If session is established using either "Enter-PSSession ", or “New-PSSession”, shouldn’t we be able to issue commands without any invoke stuff
Thanks again