SQL DM automation

Hi All,

I am trying to do automation for SQLDM like set the instance to maintenance mode and removing the instance from Maintenance mode.I tried below but getting errors.

Add-PSSnapin SQLdmSnapin

New-SQLdmDrive dm InstanceNmae SQLdmRepository

cd dm:\

($db in Invoke-Sqlcmd -query "select instance from db.dbo.name;" -database SQLdmRepository -serverinstance InstanceName)
#Enable MM for the
selected server Set-SQLdmMonitoredInstance (Escape-SQLDMName -name $db.Instance) -MMAlways

Here I am getting errors 

selected: The term 'selected' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.
At line:5 char:1
+ selected server Set-SQLdmMonitoredInstance (Escape-SQLDMName -name $db.Instance ...
+ ~~~~~~~~
+ CategoryInfo : ObjectNotFound: (selected:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

1. do i need to add the add-pssnapin sqlservercmdletsnapin100 

2. when I am closing the Powershell window, dm drive is also removing, is it every time I need to create the dm drive