Invoke-Command – Remote Powershell – Variables

Often have some issues figuring out just exactly how to do remote pssessions, passing variables, performing different stuff. I found, what I believe is the best solution for script based remote powershell for more complex operations. The below example is remote session against an SQL server, using loading some pssnapins using sqlcmd to set some database options. I use this example, because I find it a good demonstration on how and what is possible. The first example connections to basic server. The second example to an Exchange server, as the powershell connection string is different.

#– Basic server remote powershell with variables

$Session = New-PSSession -Computername $SQLServer -Authentication Kerberos
$SQLOptions = {param([Parameter(Mandatory=$true)]$Database,[Parameter(Mandatory=$true)]$DatabaseLog,[Parameter(Mandatory=$true)]$Instance)
	Add-PSSnapin sqlserverprovidersnapin100
	Add-PSSnapin sqlservercmdletsnapin100
	Invoke-SQLcmd -Query "USE master;ALTER DATABASE $Database SET RECOVERY FULL, AUTO_UPDATE_STATISTICS ON;" -ServerInstance "$Instance"
	Invoke-SQLcmd -Query "USE master;ALTER DATABASE $Database MODIFY FILE (NAME= $Database,FILEGROWTH= 150MB, MAXSIZE= UNLIMITED);" -ServerInstance "$Instance"
	Invoke-SQLcmd -Query "USE master;ALTER DATABASE $Database MODIFY FILE (NAME= $DatabaseLog,FILEGROWTH= 150MB, MAXSIZE= UNLIMITED);" -ServerInstance "$Instance"
	}

	Invoke-Command -ArgumentList $Database, $DatabaseLog, $Instance -Session $Session -ScriptBlock $SQLOptions
	Remove-PSSession $Session

#– Exchange remote powershell with variables. Difference in Session string.

	
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://"$MailServer"/PowerShell/ -Authentication Kerberos
$SendSettings = {param([Parameter(Mandatory=$true)]$MailServer,[Parameter(Mandatory=$true)]$Domain
	new-SendConnector -Name "$Domain" -Usage "Custom" -AddressSpaces "SMTP:$Domain;1" -IsScopedConnector $false -DNSRoutingEnabled $true -UseExternalDNSServersEnabled $false -SourceTransportServers '$MailServer'
	new-AcceptedDomain -Name "$Domain" -DomainName "$Domain" -DomainType 'ExternalRelay'
	}
Invoke-Command $Session -Argumentlist $Mailserver, $Domain -Scriptblock $SendSettings | Out-Null
Remove-PSSession $Session
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s