NoServiceFoundForGivenName when stop another server's service with invoke-command - powershell

I have 2 windows server, Server1 (now 2019) and ServerUpdate (2012 R2)
On each server I have an admin user named: AdminUpdate with the same password.
Im currently switching my Server1 windows server 2012 R2 for a windows server 2019. The following powershell code was working #1 before the switch.
I try to run this powershell on ServerUpdate to stop aservice on Server1
# Obtient une instance du mot passe sécurisé
$passwordCred = ConvertTo-SecureString *SomePassword* -AsPlainText -Force
# Obtient les crédentials
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList AdminUpdate, $passwordCred
# Effectue le Stop sur le service
invoke-command -computerName *Server1Ip* -scriptBlock {
# Effectue le stop en local
Stop-Service -Name $args[0] -Force
} -credential $cred -ArgumentList *someServiceName*
For some reason I always got this error:
'*someServiceName*'.
+ CategoryInfo : ObjectNotFound: (*someServiceName*:String) [Stop-Service], ServiceCommandException
+ FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.
Commands.StopServiceCommand
+ PSComputerName : *Server1Ip*
But if i try directly this, its return the service
Get-Service -ComputerName *Server1Ip* -Name *someServiceName*
I have check this https://blog.netspi.com/powershell-remoting-cheatsheet/
I have the PSRemoting Enable
I put the sevice WinRM auto
I put my Server1 ip in the Trustedhosts on the ServerUpdate and same for the Server1, I put the ServerUpdate ip in the Trustedhosts
Did someone know why I got this error?

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

O365 Mobile Device Export

The following code works on our internal exchange server minus the connection bits as thats not needed on-prem. I have added connection code to 365, which works fine. When I run this, I get the following error and it forces me to login a second time and exports only a fraction of the results:
Starting a command on the remote server failed with the following error message : The I/O operation has been aborted
because of either a thread exit or an application request. For more information, see the about_Remote_Troubleshooting
Help topic.
+ CategoryInfo : OperationStopped: (ps.outlook.com:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : JobFailure
+ PSComputerName : ps.outlook.com
Processing data from remote server ps.outlook.com failed with the following error message: WS-Management cannot
process the request. The operation failed because of an HTTP error. The HTTP error (12152) is: The server returned an
invalid or unrecognized response . For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OperationStopped: (ps.outlook.com:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : JobFailure
+ PSComputerName : ps.outlook.com
Below is the code I am attempting to use. Do I have it formatted wrong?
#Script Created by Daniel Taylor 8/8/18
#Set Location for export:
$fLocation = "C:\temp\"
#Get username and password for 0365 connection
$cred = get-credential
#Import microsoft online
Import-module msonline
#Connect to MSonline
connect-msolservice -Credential $cred
#Connect to exchange online
$EolSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri “https://ps.outlook.com/powershell/” -Credential $cred -Authentication Basic -AllowRedirection
Import-PSSession $EolSession -DisableNameChecking
Write-host "You are now connected to Exchange. Begning ActiveSync Export:" -ForegroundColor DarkGreen
#create File to write report to:
$fName = $fLocation+"ActiveSyncDevices.txt"
$test = test-path $fName
if ($test -eq $True)
{
write-host "Removing Old File..." -ForeGroundColor Red
Remove-Item $fName
}
#Else
#{
#New-Item $fName -type file
#}
Write-host "Creating New File..." -ForeGroundColor Green
New-Item $fName -type file
#Get ActiveSync and Mailbox data
$EASDevices = ""
$AllEASDevices = #()
$EASDevices = ""| select 'User','PrimarySMTPAddress','DeviceType','DeviceModel','DeviceOS', 'LastSyncAttemptTime','LastSuccessSync'
$EasMailboxes = Get-Mailbox -ResultSize unlimited
foreach ($EASUser in $EasMailboxes) {
$EASDevices.user = $EASUser.displayname
$EASDevices.PrimarySMTPAddress = $EASUser.PrimarySMTPAddress.tostring()
foreach ($EASUserDevices in Get-MobileDevice -Mailbox $EasUser.alias) {
$EASDeviceStatistics = $EASUserDevices | Get-MobileDeviceStatistics
$EASDevices.devicetype = $EASUserDevices.devicetype
$EASDevices.devicemodel = $EASUserDevices.devicemodel
$EASDevices.deviceos = $EASUserDevices.deviceos
$EASDevices.lastsyncattempttime = $EASDeviceStatistics.lastsyncattempttime
$EASDevices.lastsuccesssync = $EASDeviceStatistics.lastsuccesssync
$AllEASDevices += $EASDevices | select user,primarysmtpaddress,devicetype,devicemodel,deviceos,lastsyncattempttime,lastsuccesssync
}
}
$AllEASDevices = $AllEASDevices | sort user
$AllEASDevices | Export-Csv $fname
write-host "The script completed successfully! The output file can be found at $fName" -ForeGroundColor Yellow
You cannot be logged in to Exchange on-prem and Exchange online at the same time. They use the same cmdlet and on-prem will take precedence.
If you are using PSRemoting, you must use two different sessions, and it's best to prefix those, so they are unique.
Or, be on the Exchange server directly and do your thing there, and open a new PSRemoting session to O365, prefixed so that the proxied commands have the prefix name.
Then make your O365 calls with the proxied cmdlets, not the on-prem ones.
Example Session setup:
# Exchange PowerShell Remote Management
#
$creds = Import-Clixml -Path $CredPath
$ExchangeSession = New-PSSession -ConfigurationName 'Microsoft.Exchange' `
-ConnectionUri ('http://' + $ExchangeServerFQDN + '/PowerShell') `
-Authentication Kerberos -Credential $Creds.ExpAdmin
Import-PSSession $ExchangeSession -Prefix 'EXP'
$creds = Import-Clixml -Path $CredPath
$ExchangeOnlineSession = New-PSSession -ConfigurationName 'Microsoft.Exchange' `
-ConnectionUri 'https://outlook.office365.com/PowerShell-liveid/' `
-Authentication Basic -Credential $Creds.ExoAdmin -AllowRedirection
Import-PSSession $ExchangeOnlineSession -Prefix 'EXO'
Get-PSSession
Each of the command will have EXP or EXO as part of the name of the proxied cmdlets.
Again, if you are doing this directly on Exchange, you only need the EXO session, and use the on-prem Exchange cmdlets normally.

Could not find or load main class com.smartbear.ready.cmd.runner.pro.SoapUIProTestCaseRunner

I have a Power Shell script that sits on a VM and creates a PSSession to a physical machine and runs a batch file. Running the batch file directly in the physical machine works as expected, however when I try running it remotely from the VM is it throwing up error.
Power Shell:
$Username = "Domain\User"
$Password = ConvertTo-SecureString "Password*" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($Username, $password)
$session = New-PSSession -ComputerName "K2" -Credential $cred
Enter-PSSession -Session $session
Invoke-Command -ComputerName "K2" -ScriptBlock {
Set-Location 'C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Test Runner'
& '.\PSTR.bat'
}
Exit-PSSession
Get-PSSession | Remove-PSSession
Batch File:
"C:\Program Files\SmartBear\ReadyAPI-2.4.0\bin\testrunner.bat" -A -j "-fC:\Users\administrator.HYPERSPHERIC\Desktop\Go4Schools Tests\Test Results" "-RJUnit-Style HTML Report" -FXML -EDevTest "C:\Users\administrator.HYPERSPHERIC\Desktop\Go4Schools Tests\Project Saves\SoapUI_Mobile_API_Project.xml"
Error:
PS C:\> C:\Users\administrator.HYPERSPHERIC\Desktop\PS_TR.ps1
C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Test Runner>"C:\Program Files\SmartBear\ReadyAPI-2.4.0\bin\testrunner.bat" -A -j "-fC:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Sch
ools Tests\Test Results" "-RJUnit-Style HTML Report" -FXML -EDevTest "C:\Program Files\SmartBear\ReadyAPI-2.4.0\Go4Schools Tests\Project Saves\SoapUI_Mobile_API_Project.xml"
Error: Could not find or load main class com.smartbear.ready.cmd.runner.pro.SoapUIProTestCaseRunner
+ CategoryInfo : NotSpecified: (Error: Could no...oTestCaseRunner:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : K2
Ready API and soapUI use some environment variables in testrunner.bat to set up dependencies and the like. So, whenever I've executed testrunner.bat with a script from outside of the application, I've always CD'ed to the bin directory first:
cd <Ready API installation directory>\bin
./testrunner.bat ...

Powershell - Change SQL Server Service Password and Start Service

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.

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..