Remote Commands fail after adding machines to TrustedHosts - powershell

I added both local and remote machine to TrustedHosts:
winrm set winrm/config/client '#{TrustedHosts="WIN-XXXXX,Windows7-1"}'
After doing that remote commands now fail
Invoke-Command -ComputerName "Windows7-1" -Credential $cred -ScriptBlock {Rename-Computer -ComputerName 'Windows7-1' -NewName 'XXXX' -Force -PassThru -Restart }
If I wait for 2 mins and run same code it will work fine...

$hostName="DomainName"
$winrmPort = "5986"
$username = "Username"
$secpasswd = ConvertTo-SecureString “Password” -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential (“$username”, $secpasswd)
$soptions = New-PSSessionOption -SkipCACheck
Invoke-Command -ComputerName $hostName -ScriptBlock { Command Session } -Port $winrmPort -Credential $mycreds -SessionOption $soptions -UseSSL

Related

Remote execution on Exchange server failed

I want to remote enable the email-address-policy for a single mailbox on a exchange server (2010).
I can do this:
$samaccountname = $args[0] # gets sam from command line
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName Set-Mailbox
Get-Mailbox -Identity $samaccountname | Set-Mailbox -EmailAddressPolicyEnabled $True
Remove-PSSession $Session
It works if I open a powershell as administrator on the Orchestrator server. Then it executes the command on the exchange server as it should.
But the script does not work if Orchestrator tries to execute it. I do not know what settings Orchestrator uses when executing it. But I have a similar script, which is working with Orchestrator.
$samaccountname = $args[0] # gets sam from command line
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName enable-mailbox
$username_param = $samaccountname
$emailalias_param = $samaccountname
Invoke-Command -ArgumentList $username_param,$emailalias_param –session $Session -scriptblock {
param($username_exc, $alias_exc)
Enable-Mailbox -Identity $username_exc -Alias $alias_exc -DomainController 'xyzdc01.zfpdom.zfp'
}
Remove-PSSession $Session
This script makes a new mailbox. It is working.
Can anyone show me a solution for the first script? I am totally new in powershell so I can't figure it out. Maybe someone can change my first script to do it with this Invoke-Command scriptblock. I am sure, then it will work.
Thank you.
Greetings
Replace the commands inside the invoke-command, and the variables accordingly. Also, add the get-mailbox commandlet to the session. I am not able to try it, though, so I added the -verbose and -whatif switches as a failsafe. Note that if the samaccountname variable is empty, the Set-Mailbox will run on all mailboxes. The script can be tested standalone before running it in the Orchestrator.
$samaccountname = $args[0] # gets sam from command line
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName Set-Mailbox,Get-Mailbox
Invoke-Command -ArgumentList $samaccountname –session $Session -scriptblock {
param($username_exc)
Get-Mailbox -Identity $username_exc| Set-Mailbox -EmailAddressPolicyEnabled $True -verbose -whatif # remove the -whatif to perform changes
}
Remove-PSSession $Session
Another working solution I have found out:
#Parameter Laden
$samaccountname = $args[0] # $samaccountname wird übergeben
$EncryptedPassword = Get-Content -Path "C:\temp\password.txt"
$SecurePassword = ConvertTo-SecureString -String $EncryptedPassword
$Credential = New-Object System.Management.Automation.PSCredential "xyzdom\sco_admin", $SecurePassword
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://xyzexcas01/PowerShell/ -Authentication Kerberos -Credential $Credential
Import-PSSession $Session -AllowClobber -CommandName Set-Mailbox,Get-Mailbox
Get-Mailbox -Identity $samaccountname | Set-Mailbox -EmailAddressPolicyEnabled $True
Remove-PSSession $Session

Need to execute winrm set winrm/config/client '#{TrustedHosts="192.168.4.231"}' command from PowerShell script from remote

I am firing following script from remote machine to add the executer IP (192.168.4.231) in trusted list. but the below script is getting fired but not I am not getting desired results.
Please let me know is there any wrong way I am executing below script.
$servers = #("192.168.4.236")
foreach($server in $servers) {
$username = 'administrator'
$password = '*******'
$pw = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ($username, $pw)
$s = New-PSSession -ComputerName $server -Credential $cred
Enter-PSSession $s
Invoke-Command -Session $s -Scriptblock {
Invoke-Expression 'winrm set winrm/config/client '#{TrustedHosts="192.168.4.231"}''
}
Write-Host "Completed"
Remove-PSSession $s
}

Permission denied error while creating file in remote system by Azure powershell

I have written below code to create file in remote system by domain credentials.
When i execute this code I get permission denied error.
Code:
$username = "domain\username"
$password = "Welcome1234$"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
Invoke-Command -Credential $cred -Computer VM1{
New-Item \\VM2\sapmnt\SID\SYS\profile\test.txt -ItemType file
}
error:
Access to the path '\\VM2\sapmnt\SID\SYS\profile\test.txt' is denied.
+ CategoryInfo : PermissionDenied: (\\VM2\s...rofile\test.txt:String) [New-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : NewItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand
Can you use that account to access that path \\VM2\sapmnt\SID\SYS\profile? Do you have permission to read or write?
I had test in my lab, it works for me.
Grant permission (Read/Write)to that account:
Here is the script:
$username = 'jason'
$pass = ConvertTo-SecureString -string 'password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
$s = New-PSSession -ConnectionUri 'http://13.73.23.129:5985' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
Invoke-Command -Session $s -ScriptBlock {new-item \\jasonvm\profile\jasontest3.txt}
Update:
changing the ip-address to HOSTNAME resolve this issue:
$username = 'jason'
$pass = ConvertTo-SecureString -string 'password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
$s = New-PSSession -ConnectionUri 'VM2hostname:5985'; -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
Invoke-Command -Session $s -ScriptBlock {new-item \\jasonvm\profile\jasontest3.txt}

Call a Powershell Scriptfile that resides on a remote server

how do I call a ps1 file that resides on a target machine? All tutorials mostly say that I run a local ps1 on a remote machine. I tried the following but it just does nothing :/
$username = "theusername"
$password = "thepassword"
$secpassword = ConvertTo-SecureString –String $password –AsPlainText -Force
$credential = New-Object –TypeName "System.Management.Automation.PSCredential" –ArgumentList $username, $secpassword
$so = New-PSSessionOption -SkipCACheck
$session = New-PSSession -ConnectionUri "https://servername:5986/WSMAN" -SessionOption $so -Credential $credential
Invoke-Command -Session $session -ScriptBlock { "powershell E:\\Tools\Powershells\MyPowershell.ps1" }
Exit-PSSession
Executing a script by path (possibly with spaces) is done with
& "path with spaces\script.ps1"
This works just as well when remoted, so to execute a remote script stored remotely, use
Invoke-Command -Session $session -ScriptBlock { & "path with spaces\script.ps1" }

Simple Powershell script doesn't work when compiled or run as a script

I have a simple snippet I can run no problems within the powershell console. When I compile it to an EXE, or even a ps1 and run it, it doesn't find the reg value, no idea why.
Here is the code:
$User = "Training\Administrator"
$PWord = ConvertTo-SecureString -String "P#ssWord" -AsPlainText -Force
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$creds = $Credentials
enter-pssession –computername Win7Client –credential $creds
Start-Sleep -s 2
Set-itemproperty “HKLM:\SOFTWARE\Citrix\Metaframe Password Manager\Extensions\SyncManager\Syncs\DefaultSync\Servers” -name Server1 -value \\DFSI\CPMStore
Return
I would change the last lines to:
$Pssn = new-psssession –computername Win7Client –credential $creds
invoke-command -Session $Pssn -scriptblock {Set-itemproperty “HKLM:\SOFTWARE\Citrix\Metaframe Password Manager\Extensions\SyncManager\Syncs\DefaultSync\Servers” -name Server1 -value \\DFSI\CPMStore }
Return
Hope this helps,
Luc