psexec powershell output - powershell

I try remote execute powershell script like this:
psexec -i \\host -u user -p pass PowerShell C:\tst\tst.ps1
Source code for tst.ps1:
$TempLogFilePath = "$(Get-Date -u "%Y-%m-%d")-LogFileEventLog.log"
Start-Transcript -Path "$TempLogFilePath" -Append
echo (Get-Date –f o)
Stop-Transcript
Exit 0
When a run command to remote execute this script, script locate on remote machine, in local machine in output nothing. Command running in cmd.exe. How i can get output to local console?

PsExec.exe \\host -u domain\user -p pass cmd /c "echo . | %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe C:\WINDOWS\system32\Hello.ps1"
This construction help you to run remote powershell script, but script should be locate on remote computer.
and second construction
Param(
[alias("sp")]
[string]$script_path,
[alias("u")]
[string]$user_name,
[alias("p")]
[string]$password,
[alias("h")]
[string]$host_name
)
$pass = convertto-securestring $password -asplaintext -force
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user_name,$pass
invoke-command -credential $mycred -computername $host_name -filepath $script_path
but i don't know how i can pass args string for execute remote script with param

Related

Powershell remote execution of Oracle installer Silent from unc

Meanwhile I've read and tried so many options and none of them worked for me.
I need to run a command on a remote machine that will install an application.
The setup.exe is an Oracle installer and is able to accept silent parameters.
"\\SVR1\Share\remote application Install\install\Setup.exe" -silent -force -nowait -waitforcompletion PACKAGE_NAME=abcde INSTALL_MODE=Typical ORACLE_HOME=C:\some_dir ORACLE_HOME_NAME=some_dir_Client1 APP_USER=itsmeagain APP_PASSWORD=surexxx
When I paste this command in a cmd it works as expected
When I put this in a ps1 script and run it, it works too:
cmd /c "\\SVR1\Share\remote application Install\install\Setup.exe" -silent -force -nowait -waitforcompletion PACKAGE_NAME=abcde INSTALL_MODE=Typical ORACLE_HOME=C:\some_dir ORACLE_HOME_NAME=some_dir_Client1 APP_USER=itsmeagain APP_PASSWORD=surexxx
However trying to run this 1 line script from a remote computer, it fails with: [Start-Process], InvalidOperationException
$svr="mach1"
$cmdFile="install.ps1"
$RemDir = "\\${svr}\C$\All_files\Scripts\"
$fn = "${RemDir}\${cmdFile}"
$password = ConvertTo-SecureString "${pazwd}" -AsPlainText -Force
# can't change the remote dir without spaces
"cmd /c `"\\SVR1\Share\remote application Install\install\Setup.exe`" -silent -force -nowait -waitforcompletion PACKAGE_NAME=abcde INSTALL_MODE=Typical ORACLE_HOME=C:\some_dir ORACLE_HOME_NAME=some_dir_Client1 APP_USER=itsmeagain APP_PASSWORD=surexxx " | Out-File -FilePath $fn
$cred = New-Object System.Management.Automation.PSCredential($user,$password)
$sb = { Start-Process -FilePath "${LocalDir}\${cmdFile}" }
Invoke-Command -ComputerName $svr -Credential $cred -ScriptBlock $sb
Suggestions? what Am I doing wrong here?

using cmd in powershell properly

at the moment i install a programm to a remote machine with batch. thats already working fine.
but how can i use or "convert" the batch command below in powershell using the specific command for the prgramm to install it silent on the remote machine?
this is my batch code.
set /p target=hostname
echo.
copy /z "\\server1\tool.exe" "\\%target%\C$\temp"
echo.
PsExec.exe \\%target% cmd /c "\\%target%\C$\temp\tool.exe" /verysilent
$target=hostname
Copy-Item -Path "\\server1\tool.exe" -Destination "\\$target\C$\temp"
Invoke-Command -ScriptBlock \\%target%\C$\temp\tool.exe -ComputerName $target -credential (USERNAME)
for the Invoke-Command -Scriptblock is the command you want to run, -ComputerName is the computer you want to start a process on, -Credential is the username to use to run the command. You will automatically be prompted to enter your password.
Thanky guys for your answers.
i did like that
$target = Read-Host "hostname"
Copy-Item -Path "\\server1\tool.exe" -Destination "\\$target\C$\temp"
PsExec.exe \\$target -s winrm.cmd quickconfig -q
Invoke-Command -ComputerName $target -ScriptBlock {
cmd /c "C:\temp\tool.exe" /verysilent
}

Executing CMD command remotely

I need to execute some commands remotely on computers and receive back input, to prevent calling every user and remote desktop to use CMD.
What I need to do:
Run CMD as admin, and run the two lines below and review the results. (On 30+ computers)
cd "c:\Program Files\Tenable\Nessus Agent"
nessuscli agent status --local
I tried:
wmic /node:COMPUTERNAME process call create "cmd.exe /c start"
It worked on my computer, but I think it opened the command prompt on the other persons computer when I tried this.
winrs -r:COMPUTERNAME CMD
WINRM apparently isn't enabled and I don't want to enable it if it's not already enabled.
$PC = (Read-Host "Enter Computer Name").ToUpper()
$PC cmd.exe --% /k cd "c:\Program Files\Tenable\Nessus Agent" & nessuscli agent status --local
write-host -f WHITE "Operation Complete."
I couldn't figure out how to make it work with a Powershell script in ISE.
I was able to run the below one from Powershell x86 as admin on my computer, but not sure how I would replicate to run it on an external computer.
cmd.exe --% /k cd "c:\Program Files\Tenable\Nessus Agent"
nessuscli agent status
EDIT
I created a .bat file and was able to launch it as admin, but it still requires input from the user to accept the cmd runas admin. Then I cannot see the results of the CMD on my end.
$PC = (Read-Host "Enter Computer Name").ToUpper()
#Change $xWare to your folder
[string]$RemoteStagingPath = '\\' + $PC + '\C$\Intel'
$xWare = "C:\Users\NAME\Desktop\"
$password= convertto-securestring $passwordTextBox.Text -asplaintext –force
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $userTextBox.Text,$password
$script = "C:\intel\cmd.bat"
#Runs Nessus
CP $xWare\cmd.bat $RemoteStagingPath
Start-Process powershell -Credential $credential -ArgumentList "-noprofile -command &{Start-Process $script -verb runas}"
write-host -f WHITE "Operation Complete."

Invoke-AzVMRunCommand and Start-Process under specific user on remote VM using Azure Runbook

I need to run Start-Process on a remote VM with specific user account using Azure Powershell Runbook
function Install-Postgres {
$username = "aact-import-vm1\aact-importer"
$password = "ChangeMe!"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList `
#($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
write-output $cred
# run pg installer
Start-Process "C:\Program Files\WindowsPowerShell\Modules\Install-Postgres\postgresql.exe" -ArgumentList `
"--mode unattended", "--unattendedmodeui none",`
"--prefix `"C:\Program Files\PostgreSQL\10`"", "--datadir `"C:\Program Files\PostgreSQL\10\data`"",
"--superpassword `"ChangeMe!`"",`
"--servicename `"postgres`"", "--serviceaccount `"postgres`"", "--servicepassword `"ChangeMe!`""`
-Wait -Credential $cred;
}
$script = Get-Content Function:\Install-Postgres
Out-File -FilePath Install.ps1 -InputObject $script
#Note that the -ScriptPath should not point to the remote path(in remote vm), it should point to the local path where you execute the command Invoke-AzureRmVMRunCommand
$output = Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -Name $vmName -CommandId 'RunPowerShellScript' -ScriptPath Install.ps1
write-output $output.Value
#after execution, you can remove the file
Remove-Item -Path Install.ps1
The script above produces the following error:
Start-Process : This command cannot be run due to the error: Access is denied.
If I run the script above without specific credentials the postgres installer produces this error in the log:
Executing icacls "C:\Windows\Temp/postgresql_installer_1ef9b3f2c6" /T /Q /grant "WORKGROUP\aact-import-vm1$:(OI)(CI)F"
Script exit code: 1332
Script output:
Successfully processed 0 files; Failed processing 1 files
Script stderr:
WORKGROUP\aact-import-vm1**$**: No mapping between account names and security IDs was done.
Please notice that there is symbol $ instead of user name.
However, if I run it on the VM it works fine and produces this line in the log:
Executing icacls "C:\Users\aact-importer\AppData\Local\Temp\2/postgresql_installer_2662c862ff" /T /Q /grant "aact-import-vm1\aact-importer:(OI)(CI)F"
Script exit code: 0
As far as I can see, If I run runbook script remotely without credentials it runs under NTAUTHORITY\SYSTEM that's why there is symbol $ instead of user name in the postgres installer log. If I run it locally it uses proper user and everything works fine.
The question is: how can I specify a user account to run Start-Process on the remote VM?
Same question on msdn https://social.msdn.microsoft.com/Forums/en-US/a7fa0ca8-5cba-42bb-8076-9a8d4a654beb/invokeazvmruncommand-and-startprocess-under-specific-user-on-remote-vm-using-azure-runbook?forum=azureautomation#a7fa0ca8-5cba-42bb-8076-9a8d4a654beb
For those who are interested:
After investigation with MS support they confirmed that runbook (not hybrid) always runs under NTAUTHORITY\SYSTEM

Powershell Script Wrapper for Running as Admin

I am writing a script to deploy through group policy. The script deletes a number of registry settings to fix an issue we have on our build of Windows. The script needs to run as an administrator as the keys exist in hives that require admin rights to delete.
Because GP runs powershell scripts as the logged on user, I am looking at creating a wrapper which will read an encrypted password for the local user account and then run the script with it.
My script is able to read the credential, but I am getting errors when running the start-process command. If I try and reference the script it will give the error that the path doesn't exist, even though you can dump the contents using cat .
I then tried reading it into a variable and running powershell with the -command argument. If I do this I get an error.
"Start-Process : This command cannot be run due to the error: The parameter is incorrect"
I understand that I need to enclose the code in braces, but I am not sure how this is done as concatenating them to the string doesn't work.
if($connected) {
$Encrypted = Get-Content <PATH TO PASSWORD FILE>
$pass = ConvertTo-SecureString -String $Encrypted -Key (1..16)
$user = <MY ADMIN ACCOUNT>
$Credential = New-Object System.Management.Automation.PSCredential $user, $pass
echo $(pwd)
echo $(cat <PATH TO SCRIPT>)
$code = $( cat <PATH TO SCRIPT> )
#Invoke-Command -ScriptBlock {$code} -Credential $Credential
#Start-Process powershell.exe <PATH TO SCRIPT> -Credential $Credential
Start-Process powershell.exe -ArgumentList "-command $code" -Credential $Credential
}
I just need a way of executing the code in my second script, but I can't work out how to do this as it's not behaving as expected. Sorry, as I am sure I am missing something obvious.