Call a Powershell Scriptfile that resides on a remote server - powershell

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" }

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
}

Remote Commands fail after adding machines to TrustedHosts

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

how to run remote program on Powershell for long running program

I need to run a long running program on a remote computer. Currently the exe runs as long as the PS session exists. if the session is removed the exe stops. How can i have the exe running even if the PS session is lost
$mmoVMTemplate = "Machine"
for($i=1;$i -le 80; $i++)
{
$mmoVM = $mmoVMTemplate + $i
.\InstallWinRMCertAzureVM.ps1 -SubscriptionName 'my subscription' -ServiceName $mmoVM -Name $mmoVM
$secPassword = ConvertTo-SecureString 'password' -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential('username', $secPassword)
$uri = Get-AzureWinRMUri -ServiceName $mmoVM -Name $mmoVM
$session = New-PSSession -ConnectionUri $uri -Credential $credential
Invoke-Command -Session $session -ScriptBlock {Set-Location "C:\MyProgram\"
start-process -FilePath 'C:\MyProgram\TestTool.exe'}
Disconnect-PSSession -Session $session
Write-Host $mmoVM
}
Use the parameter -Wait by start-process -FilePath 'C:\MyProgram\TestTool.exe' -Wait.
So the invoke comamnd waits until the TestTool.exe is finished.

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