Starting to manage servers with PowerShell scripts...
I installed VSCODE + PowerShell extension in my laptop.
I set my WSMAN Trusted list to *
And ran the following script (below, for example with F5 key) that suppose to stop a service in the remote machine:
$computers = "IP ADDRESS"
[string] $domainAdminUserName = "USERNAME"
[string] $domainAdminPlainPassword = "PASSWORD"
$securePassword = $domainAdminPlainPassword | ConvertTo-SecureString -AsPlainText -Force
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $domainAdminUserName, $securePasswordEnter-PSSession -Computer $computers -Credential $credentials
$svcSQL = Get-WmiObject -Class Win32_Service -Computer $computers -Credential $credentials -Filter "Name='MSSQLSERVER'"
$svcSQLAgent = Get-WmiObject -Class Win32_Service -Computer $computers -Credential $credentials -Filter "Name='SQLSERVERAGENT'"
$svcOLAP = Get-WmiObject -Class Win32_Service -Computer $computers -Credential $credentials -Filter "Name='MSSQLServerOLAPService'"
Invoke-Command -Computer $computers -Credential $credentials -ScriptBlock {Get-WmiObject -Class Win32_Service | Where-Object {$_.name -eq $svcSQL} | Stop-Service -Force}
Invoke-Command -Computer $computers -Credential $credentials -ScriptBlock {Get-WmiObject -Class Win32_Service | Where-Object {$_.name -eq $svcOLAP} | Stop-Service}
Exit-PSSession
The services weren't stop
Then, I went to the PowerShell Integrated Console and execute the following commands:
PS> Enter-PSSession -Computer "IP ADDRESS" -Credential "DOMAIN ADMIN USER"
PS> PASSWORD: ******
PS [IP ADDRESS]> Get-Service -Name "MSSQLSERVER"
PS [IP ADDRESS]> PowerShell found the service
PS [IP ADDRESS]> Stop-Service -Name "MSSQLSERVER"
The service was stopped successfully
How can I fix the problem in order to run the script and get the expected result?
Note:
- PC: My pc (WIN 10 is in one domain (Home)
- VM: My remote lab machine (WIN 2016 is in another domain (Work)
- PC: To get remote access to my lab I need to use VPN app
- PC: My WSMan
Trusted List = *
- VM: WinRM is running in my remote lab (GPO: Windows Remote Management (WS-Management (Startup Mode = Automatic)
- VM: port 5985 is open, 5986 not
- PC & VM:
Set-ExecutionPolicy Unrestricted
in client and server wasn't help
[ValidateNotNullOrEmpty()]
. These are meant to be used with parameters, not for simply declaring variables in the code. If parameters is what you want, put the first three lines inside aParam(..)
block – Theo[Validate*]
on parameters, not in variable creation. – Theo