how to run remote program on Powershell for long running program - powershell

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.

Related

PowerShell - Why do I have to state the New-PSSession Variable again?

So I am running an Invoke-CimMethod to push an Enable-PSRemoting command to target computer. Then run an Invoke-Command using PS-Session as a parameter. The two scripts work separately, but if I run them together I keep getting this error:
Copy-Item : The runspace state is not valid for this operation.
I had to restate the $session variable like so in order for it to run. I have bolded and highlighted the line below. My question is why?
$env:hostname = 'PC1'
$Session = New-PSSession $env:hostname
$DestinationPath = "C:\windows\temp"
$SessionArgs = #{
ComputerName = $env:hostname
Credential = $credential
SessionOption = New-CimSessionOption -Protocol Dcom
}
$MethodArgs = #{
ClassName = 'Win32_Process'
MethodName = 'Create'
CimSession = New-CimSession #SessionArgs
Arguments = #{
CommandLine = "powershell Start-Process powershell -ArgumentList 'Enable-PSRemoting -Force'"
}
}
Invoke-CimMethod #MethodArgs
Invoke-Command -Session $Session -ScriptBlock { Param($Destination) New-Item -Path $Destination -ItemType Directory -ErrorAction SilentlyContinue} -ArgumentList $DestinationPath
Copy-Item -Path "\\shared\drive\foo\bar\" -Destination "C:\windows\temp\ZScaler" -Recurse -force
############Restated here#############
$Session = New-PSSession $env:hostname
############Restated here#############
Invoke-Command -Session $session -ScriptBlock {
$msbuild = "C:\Windows\Temp\Installer\Installer.msi"
$arguments = "/quiet"
Start-Process -FilePath $msbuild -ArgumentList $arguments -Wait -Verbose
}
$Session | Remove-PSSession

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
}

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

Powershell Start-Process for a remote machine not working

remotePSExecuter.ps1 file:
$InputArgs=$args[0]
$Username=$args[1]
$Password=$args[2]
$ComputerName=$args[3]
$PSToExecute=$args[4]
write-host $Username $Password $ComputerName $PSToExecute
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" $Username, $SecurePassWord
$Session = New-PSSession -ComputerName $ComputerName -credential $Cred
$DownloadInstallJob = Invoke-Command -Session $Session -filepath "${PSToExecute}" -ArgumentList "${InputArgs}"
echo $DownloadInstallJob
Remove-PSSession -Session $Session
downloadInstallWinVcops.ps1 file:
$buildId=$args[0]
$storageDir = "C:\vcops-downloads"
$webclient = New-Object System.Net.WebClient
$url = "http://build-squid.com/build/mts/release/${buildId}/publish/Web_Installers/InstData/Windows/VM/file.exe"
write-host url=$url
write-host downloading windows vcops build ${buildId} ...
$file = "$storageDir\winvcops.exe"
$webclient.DownloadFile($url,$file)
write-host downloading windows vcops finished!
write-host installing windows vcops...
Start-Process -FilePath "C:\vcops-downloads\winvcops.exe" -ArgumentList "-i silent" -wait
write-host windows vcops installation finished!
This is the way I am calling on Jenkins machine:
.\EnterpriseAdapters/remotePSExecuter.ps1 sb-xxxx Administrator password 10.xx.xx.xx EnterpriseAdapters/downloadInstallWinVcops.ps1
Problem:
Start-Process -FilePath "C:\vcops-downloads\winvcops.exe" -ArgumentList "-i silent" -wait is not getting called on remote machine.

nested scriptblocks in a powershell remote session

I am trying to run a script block on a remote machine, but i don't to be prompted for credentials, i want to pass them in the script.
Some commands may but the commands i want to run are access denied unless i provide the credential.
for example this command can work:
Invoke-Command -Session $session -ErrorAction Stop -ErrorVariable $Error -Scriptblock {ls }
but this wont work unless -credential is passed (Invoke-Command on target)
Invoke-Command -Session $session -ErrorAction Stop -ErrorVariable $Error -Scriptblock {Invoke-Command -computername $Env:COMPUTERNAME -Credential $Cred -ScriptBlock {ls} }
the same way what i want to achieve causes access denied problem (starting a process)
Invoke-Command -Session $session -ErrorAction Stop -ErrorVariable $Error -Scriptblock {[System.Diagnostics.Process]::Start("C:\Myprocess.exe", $localArgs, "UserName", $credential.Password, "MyDomain")}
Invoke-Command -Session $session -ErrorAction Stop -ErrorVariable $setError -Scriptblock {$Domain = "domain";$PassSec = ConvertTo-SecureString $( "password") -AsPlainText -Force ; $Cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $($domain + "\" + "userName"),$passSec; Invoke-Command -computername $Env:COMPUTERNAME -Credential $Cred -ScriptBlock {C:\Myprocess.exe } }