Powershell - Change SQL Server Service Password and Start Service - powershell

The SQL Server service is currently not running.
I am trying to change the password for my local SQL instance then start the instance using PowerShell.
I've tried using a remote session as suggested from this site (http://www.databasejournal.com/features/mssql/managing-sql-server-services-with-powershell.html)
PS - When I run PowerShell ISE 5, I am running it as an admin.
#Create a new remote PowerShell session and pass in the scrip block to be executed
$session = New-PSSession -ComputerName Laptop123 -Credential Domain01\User01
$UserName = "Domain01\User01" # specify user Name here
$Password = "Password1" # specify Password here
Invoke-Command -Session $session -ArgumentList $UserName, $Password -Scriptblock {
param($UserName, $Password)
# Start SQL Server Database engine service (default instance)
$Svc = Get-WmiObject win32_service -filter "name='MSSQL$SQL2008R2_32BIT'"
$Svc.Change($Null, $Null, $Null, $Null, $Null, $Null, $UserName, $Password)
Stop-Service -Name 'MSSQL$SQL2008R2_32BIT' -Force
Start-Service 'MSSQL$SQL2008R2_32BIT'
# Start SQL Server SQL Server Agent service (default instance)
$Svc = Get-WmiObject win32_service -filter "name='SQLAgent$SQL2008R2_32BIT'"
$Svc.Change($Null, $Null, $Null, $Null, $Null, $Null, $UserName, $Password)
Stop-Service -Name 'SQLAgent$SQL2008R2_32BIT' -Force
Start-Service 'SQLAgent$SQL2008R2_32BIT'
}
However, I end up getting the following errors:
Method invocation failed because [System.ServiceProcess.ServiceController] does not contain a method named 'Change'.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
+ PSComputerName : Laptop123
Service 'SQL Server (SQL2008R2_32BIT) (MSSQL$SQL2008R2_32BIT)' cannot be started due to the following error: Cannot start service MSSQL$SQL2008R2_32BIT on computer '.'.
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException
+ FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand
+ PSComputerName : Laptop123
Any suggestions on how to change the service password and then start it?

it looks like you are calling the wrong name of the service in your script try changing the name filter to 'SQL Server (SQL2008R2_32BIT)'
Let me know if that works, if not list any output you may receive from trying that.

Related

Configuring Remote Desktop Services remotely via powershell

Trying to manage our Remote Desktop Services installation using PowerShell and we're running into an issue where the commands in the RemoteDeskop module and the RemoteDesktopServices module do not appear to work when being run via Invoke-Command. Basically it appears that these functions do not work when run in a remote session.
The script below gets the following error:
The RD Connection Broker server is not available. Verify that you can
connect to the RD Connection Broker server.
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-RDServer
+ PSComputerName : AWSELABSDevX13.LABSDEV.com
$server = "OUR_SERVER"
$connection_broker = "OUR_SERVER"
$collectionName ="COLLECTION"
$admin_user = "FULLY_QUALIFIED_DOMAIN_USER"
$password = "PASSWORD"
$password_sec = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($admin_user, $password_sec)
$sb =
{
function Test-IsAdmin {
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}
if (Test-IsAdmin) {
""
"You are running with Administrator access."
""
} else {
""
"You do not have admin access."
""
}
whoami /priv
Import-Module RemoteDesktop
Import-Module RemoteDesktopServices
Get-RDServer
}
Invoke-Command -Credential $cred -ComputerName $connection_broker -ScriptBlock $sb

retrieve vhdx path from a remote server

hi i' m trying to retrieve the vhdx of specified vmname from the remote host server
here part of the script
$pth="C:\path\resize-vm"
$list=gc $pth\list-host.txt
foreach ($hostserver in $list) {
$vm=(Invoke-Command -ComputerName $hostserver -ScriptBlock {Get-VM}).VMName
Write-Host -NoNewline " here the vm installed in " $hostserver `r`n $vm
$vmname=Read-Host -Prompt "please chose a vmname to resize "
#the issue in the last line
$pathvhd=Invoke-Command -ComputerName $hostserver -ScriptBlock {(Get-VMHardDiskDrive -VMName $vmname).path}
When I launch this command $vmname="dc-kozhan"
I am getting this error
Cannot validate argument on parameter 'VMName'. The argument is null
or empty. Provide an argument that is not null or empty, and then try
the command again.
+ CategoryInfo : InvalidData: (:) [Get-VMHardDiskDrive], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.HyperV.PowerShell.Commands.GetVMHardDiskDrive
Command
+ PSComputerName : h-uludag-3
But when I specified dc-kozhan literally it work
PS C:\Users> Invoke-Command -ComputerName $hostserver -ScriptBlock {(Get-VMHardDiskDrive -VMName "DC-KOZAHAN")
.path}
V:\DC-KOZAHAN\DC-KOZAHAN-SYSTEM.vhdx
V:\DC-KOZAHAN\DC-KOZAHAN-DIRECTORY.vhdx
V:\DC-KOZAHAN\DC-KOZAHAN-SYSVOL.vhdx
V:\DC-KOZAHAN\DC-KOZAHAN-BACKUP.vhdx
does anyone have an idea why it does not work when it's specified in a variable
You need to understand how to pass arguments inside the scriptblock. The scope is different when you try to pass the value inside the scriptblock. As a result, $VMname is becoming null in your first statement.
Kindly change your existing Invoke-command statement to the below one:
Invoke-Command -ComputerName $hostserver -ScriptBlock {Param([string]$vmname)(Get-VMHardDiskDrive -VMName $vmname)} -ArgumentList $vmname
Also, my suggestion for you to read about the argumentlist in powershell in case invoke-command
Hope it helps.

Adding Shared Printer to Remote Computer via Powershell

I am unable to run an invoke-command script to install printers on a remote machine. My code works locally, but as soon as I pipe it into Invoke-command, i get errors.
Local:
$Printer = "\\server1\printer1"
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($Printer)
And this adds the printer just fine. I can do this same command on the remote computer with no issues. But when i tried to execute the command remotely I have the issues.
Remote:
$compname = "computer"
$Printer = "\\server1\printer1"
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer')}
Which returns the error "The printer name is invalid"
So I tried to see what the shell was sending to the remote computer with the following code, and everything in the write output looks good, but I still get errors:
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer'); write-host "(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('$Printer')"}
Output:
Exception calling "AddWindowsPrinterConnection" with "1" argument(s): "The printer name is invalid. (Exception from
HRESULT: 0x80070709)"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : computer
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection('\\server1\printer1')
Edit 1/5/2015
So I've tried Paul's code with a number of different entries to the argumentlist. All have not worked so far. i think the first 3 are closer to an answer.
-ArgumentList ""\\server1\printer1""
-ArgumentList ""'\\server1\printer1'""
-ArgumentList "\"\\server1\printer1""
Results in:
Invoke-Command : A positional parameter cannot be found that accepts argument '\\server1\printer1'.
At line:1 char:1
+ Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Ne ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
-ArgumentList "'\\server1\printer1'"
-ArgumentList \'"\\server1\printer1"'
-ArgumentList \""\\server1\printer1""
-ArgumentList \"\\server1\printer1"
Result in:
Exception calling "AddWindowsPrinterConnection" with "1" argument(s): "The printer name is invalid. (Exception from
HRESULT: 0x80070709)"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : sso-mxl327082y
Try this:
Invoke-Command -ComputerName $CompName -Scriptblock {(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($args[0]); write-host "(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($($args[0]))"} -ArgumentList "\\server1\printer1"
I think it´s because your $printer variable is placed between single quotes, variables between single quotes are not interpreted by powershell. So the printername your function probably gets is "$printer".
In case you wonder it is printed out correctly in your write-host statement because here the single quotes are inside a string.
you need to use $Using:yourvar to pass variables to the scriptblock
$compname = "computer"
$Printer = "\\server1\printer1"
Invoke-Command -ComputerName $CompName -Scriptblock
{
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($Using:$Printer)
}
I think it's because of the so called 'double hop problem', where your authentication isn't transfered to the next remote computer which is sharing the printer.
I tried to solve similar problem using add-printer and following this article double hop problem solution.
However, although it works with get-childitem etc. it doesn't work with add-printer cmdlet.

New-PSsession not working in Script

I have a strange problem with one of my servers :
I am trying to open a PSsession with it.
If I copy my script directly in powershell everything works fine, but if i run it via a .ps1 file I get a access denied error.
The same sript works on multiple machines except this one.
Additonal information:
Executing Server : Server 2012
Target Server2003SP2
Another Server2003SP2 is working fine without a Problem
the Client Server was configured using :
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts MY2012Server -concatenate -force
Restart-Service WinRM
And the Error Message:
New-PSSession : [Server2003SP2] Connecting to remote server Server2003SP2 failed with the following error message : Access is denied. For more information,
Help topic.
At C:\Users\Administrator\Desktop\Script.ps1:23 char:13
+ $Session = New-PSSession -ComputerName $Servername -credential $Cred #-sessionO ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Edit : My full SCript as requested :
$Password = "Hereismypasswordwith#and€init"
$Username = "Servername\Administrator"
$Servername = "Servername"
$Language = {
$oscode = Get-WmiObject Win32_OperatingSystem -ErrorAction continue
$oscode = $oscode.oslanguage
$switch = switch ($oscode){
1031 {"Deutsch"};
1033 {"English"};
default {"English"};
}
write-host $switch
return $switch
}
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord
$pssessionoption = new-pssessionoption -operationtimeout 7200000 -IdleTimeout 7200000
$Session = New-PSSession -ComputerName $Servername -credential $Cred -sessionOption $pssessionoption
Invoke-Command -Session $Session -Scriptblock $Language
Remove-PSSession -Session $Session
UPDATE :
it seems to be something within the Char encoding.
the password in the ps1 file produces a difrent output for the € in it :
in the ps1. ¬
in the ps window : ?
if i pass the Password as a Paramter it also works.
$password.gethash() also prouces difrent outputs. codepage is the same though (chcp)
the script was created in notepad++
Changing / Converting to ansi from UTC without BOM fixed the issue.. jesus crist who thinks about stuff like that / why the hell was it set to this value..

PowerShell IIS:\ WebAdmin Remote Invocation triggers WSAStartup error, WSANOTINITIALISED

I'm using PSRemoting with the WebAdministration module to get info about various sites, and it's working. I am, however, receiving an annoying non-fatal COM exception during invocation of the command, and wondering if anyone else has resolved it. Here's a minimal implementation:
cls
$command = {
param($alias)
Import-Module 'WebAdministration'
$binding = Get-WebBinding -HostHeader $alias
$binding
}
$server = 'server'
$args = #('alias')
$session = New-PSSession -ComputerName $server
Write-Host ("Invoking")
try {
Invoke-Command -Session $session -ScriptBlock $command -ArgumentList $args
Write-Host ("Invoked")
} catch {
Write-Host ("Caught $_")
} finally {
Write-Host ("Removing")
Remove-PSSession -Session $session
Write-Host ("Removed")
}
And here are the results:
Invoking
protocol : http
bindingInformation : 10.x.x.x:80:alias
...
Schema : Microsoft.IIs.PowerShell.Framework.ConfigurationElementSchema
An unhandled COM interop exception occurred: Either the application has not called WSAStartup, or WSAStartup failed. (Exception from HRESULT: 0x800
7276D)
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : COMException
Invoked
Removing
Removed
I observe the result is returned prior to the error being thrown.
Amusing details:
- Get-Website, Get-Item "IIS:\...", Get-WebBinding all result in the same error
- Running $command directly on the target machine as written results in no error
- Get-Item "d:\..." does not result in any error
- The COM error doesn't
I was able to work around the issue using the following:
$iisIpAddresses = Invoke-Command -Session $session -scriptblock {
if (!(Get-Module WebAdministration))
{
Import-Module WebAdministration
}
$iisBindings = Get-WebBinding
[String[]]$iisBindings = $iisBindings | Select bindingInformation
$iisBindings
}
Remove-PSSession $session
This is buried somewhere deep in the bowels of PowerShell's implementation of .NET and winsock. It's below anything I can calibrate, so I've added " -ErrorAction SilentlyContinue" to my remote invoke. It doesn't fix anything, but everything works correctly. That's answer enough for now, I guess.