PowerShell Invoke-Command with Start-Process outputs different result - windows

I have an update script for running the Dell Command Update tool. In short dcu-cli.exe. The thing now is than when i run the same script code on the computer local then everything runs OK but when i run the exact same code in a script with invoke-command(and yes i have full admin rights) than the exitcode is 2 meaning An unknown application error has occurred instead of 0 (everything OK)
It is a very large script so i created a new one to debug this. This is the shorted code:
Invoke-Command -ComputerName "MyComputer" -ScriptBlock {
$ExitCode = 0
#Declare path and arguments
$DcuCliPath = 'C:\Program Files (x86)\Dell\CommandUpdate\dcu-cli.exe'
$DellCommand = "/applyUpdates -autoSuspendBitLocker=enable -outputLog=C:\Dell_Update.log"
#Verify Dell Command | Update exists
If (Test-Path -Path $DcuCliPath) {
$objWMI = Get-WmiObject Win32_ComputerSystem
Write-Host ("Dell Model [{0}]" -f $objWMI.Model.Trim())
$serviceName = "DellClientManagementService"
Write-Host ("Service [{0}] is currently [{1}]" -f $serviceName, (Get-Service $serviceName).Status)
If ((Get-Service $serviceName).Status -eq 'Stopped') {
Start-Service $serviceName
Write-Host "Service [$serviceName] started"
}
#Update the system with the latest drivers
Write-Host "Starting Dell Command | Update tool with arguments [$DellCommand] dcu-cli found at [$DcuCliPath]"
$ExitCode = (Start-Process -FilePath ($DcuCliPath) -ArgumentList ($DellCommand) -PassThru -Wait).ExitCode
Write-Host ("Dell Command | Update tool finished with ExitCode: [$ExitCode] current Win32 ExitCode: [$LastExitCode] Check log for more information: C:\Dell_Update.log")
}
}
When i remove the Invoke-Command -ComputerName "MyComputer" -ScriptBlock { and then copy + run the script local on the PC then the exitcode = 0
What i also noticed than when i run the command via 'Invoke-Command' then there is also no log file created as i passed along in the arguments... So my best guess is something is going wrong with local an remote paths?
So what am i missing? I'm guessing it is something simple but i spend several hours to get this running without any luck...

Try running it this way. You should be able to see any output or error messages. I typically add to the path first rather than using & or start-process.
invoke-command mycomputer {
$env:path += ';C:\Program Files (x86)\Dell\CommandUpdate';
dcu-cli /applyUpdates -autoSuspendBitLocker=enable -outputLog=C:\Dell_Update.log }
Using start-process inside invoke-command seems pretty challenging. I can't even see the output of findstr unless I save it to a file. And if I didn't wait the output would be truncated. By default start-process runs in the background and in another window. There's a -nonewwindow option too but it doesn't help with invoke-command.
invoke-command localhost { # elevated
start-process 'findstr' '/i word c:\users\joe\file1' -wait -RedirectStandardOutput c:\users\joe\out }

#js2010, thanks for your additional help. Unfortunately this didn't helped either.
So i did some more debugging and it turns out it was a bug in the dcu-cli version running on my test machine, DOH...!!
On the test machine version 3.1.1 was running and on another machine version 4.0 was running and that worked fine via remote Powershell. So i looked for the release notes, which i found here: https://www.dell.com/support/kbdoc/000177325/dell-command-update
And as you can see in version 3.1.3 there was this fix:
A problem was solved where dcu-cli.exe was not executed in an external interactive session of PowerShell.

Related

powrshell command does not run when I run the entire script

I wrote a ps1 script to automate some package installation but the strange part is when I run the command snippet for executing the .exe file for SEP (Symantec Endpoint Protection) , it is executing fine , but when I execute the entire script , it does run the command snippet.
Iam only running a simple .exe file , and even if I run it manually , it does not show any installer , rather it installs silently in the background.
So in the script, Iam only running the .exe file, thats it .
Should I be giving any wait time or any other inputs ?
Start-Process -Wait -FilePath "C:\Temp\Symantec-Windows\SEP 14.3.3384.1000 x64.exe" -passthru
$SymVersion = Get-WmiObject -Class Win32_Product -ComputerName $hostname | Where-Object -FilterScript {$_.Name -eq "symantec endpoint protection"} | Format-List -Property version, InstallState, name
echo $SymVersion
if($SymVersion)
{
echo 'Symantec is successfully installed' -ForegroundColor Green
}
else
{
echo 'Symantec is not successfully installed' -ForegroundColor Red
}
The symantec antivirus exe files are made for silent installations. If you want to proceed with GUI mode, better unzip the file and use MSI file with arguments. With your current script,Its better to check the process is exited with code 0. The following code is not tested.
$process = Start-Process -FilePath "C:\Temp\Symantec-Windows\SEP 14.3.3384.1000 x64.exe" -passthru -Wait
if($process.ExitCode -ne 0)
{
throw "Installation process returned error code: $($process.ExitCode)"
} else { Write-Host "Installation Successful"}

Scheduled Task succesfully completes but doesn't get past import-csv

I'm trying to run below code in an automated scheduled task.
Whether I run this task manually or automated it is not working. When the option 'Run only when user is logged in' is set I at least see a PowerShell window opening, and I do see the jobs getting started. However, when the PS window closes the jobs are not visible (not completed, failed, nothing).
The logging shows the script runs till the import-csv command. I have put the CSV in the C: map, and I run the automated task as the logged in user and on highest privilege.
Why doesn't it get past import-csv? When I run this script in i.e Powershell ISE it works like a charm.
Running program
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Arguments:
–NoProfile -ExecutionPolicy Unrestricted -File "C:\Users\usr\Desktop\Scripts\script.ps1"
Start-in:
C:\Users\usr\Desktop\Scripts
Write-Host "Starting script"
$maxItems = 8
$iplist = import-csv "C:\Create.csv.txt"
Write-Host "Opened $($iplist[0])"
For ($i=0; $i -le $maxItems; $i++) {
Write-Host $iplist[$i].DisplayName
Start-Job -ScriptBlock {
Param($displayName)
try{
Start-Transcript
Write-Host "Found and started a job for $($displayName)"
Stop-Transcript
}
Catch{
Write-Host "Something went wrong "
Stop-Transcript
}
} -ArgumentList $iplist[$i].DisplayName
}
UPDATE:
The PS window closed before it got to do anything. The answer in this page send me in the right direction. The full fix I used to get this working:
Task Scheduling and Powershell's Start-Job
First, to prevent the powershell window from closing, run add the following line to the bottom of the script:
Read-Host 'Press Any Key to exit'
Second, if you run into issues with params, try explicitly naming the param with a flag:
$iplist = Import-csv -LiteralPath "C:\Create.csv.txt"
Third, make sure that you explicitly declare the delimiter being used if different than a comma.

How do you run Cleanmgr.exe remotely?

I'm having some trouble getting Clean Manager on Windows 10 to run remotely. I've seen a few different things were you can edit the registry and modify the /sageset or /sagerun to be specific things then run it remotely, but it seems no matter what I do the CleanMgr runs locally on my machine rather than running remotely.
I believe this is the closest I've gotten to get it to run remotely... It seems to still just run locally on my machine though.
Any ideas?
( All variables are set before this portion of the script, this is just a small portion of what's going on that I'm stuck on )
## Starts cleanmgr.exe
Function Start-CleanMGR {
Write-Host "Please provide your A-Account details to continue with this cleanup."
$creds = Get-Credential
Enter-PSSession -ComputerName $computername -Credential $creds
try {
$cleanmgr = Start-Process -Credential $creds -FilePath "C:\Windows\System32\cleanmgr.exe" -ArgumentList '/verylowdisk' -Wait -Verbose
if ($cleanmgr) {
Write-Host "Clean Manager ran successfully! " -NoNewline -ForegroundColor Green
Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
}
}
catch [System.Exception] {
Write-host "Cleanmgr is not installed! To use this portion of the script you must install the following windows features:" -NoNewline -ForegroundColor DarkGray
Write-host "[ERROR]" -ForegroundColor Red -BackgroundColor Black
}
} Start-CleanMGR
PowerShell always runs in the user context of the user who started the session. This is by design.
You can not run a GUI based application remotely using PowerShell. It is a Windows security boundary.
To run GUI apps, someone must be logged on, and you cannot use PowerShell to run code as the logged-on user.
You are also prompting for info, so, someone must be logged on.
If you are expecting a user to prived info, then you need to:
Create the script
Deploy the script to the user's machine or a files share from wich it
can be ran
Tell the user how to do it or create a batch file they would double
click to run the PowerShell script
Or
Set the script to run as a scheduled task at log on or at some point during the day, as the user credentials.
Variables have the scope and you cannot use local variables in a remote context unless they are scoped for that.
About Remote Variables
Using local variables
You can use local variables in remote commands, but the variable must
be defined in the local session.
Beginning in PowerShell 3.0, you can use the Using scope modifier to
identify a local variable in a remote command.
The syntax of Using is as follows:
$Using:<VariableName>
Still, the remote variable is not something you will do in your use case since you cannot do what you are after natively with PowerShell. You'll need a 3rdP tool like MS SysInternals PSExec to run code remotely as the logged-on user.
Using PsExec
Usage: psexec [\computer[,computer2[,...] | #file]][-u user [-p
psswd][-n s][-r servicename][-h][-l][-s|-e][-x][-i [session]][-c
executable [-f|-v]][-w directory][-d][-][-a n,n,...] cmd
[arguments]
-i Run the program so that it interacts with the desktop of the specified session on the remote system. If no session is specified the
process runs in the console session.
-u Specifies optional user name for login to remote computer.
I suggest that you use Invoke-Command
Function Start-CleanMGR ($computername, $creds) {
Invoke-Command -ComputerName $computername -Credential $creds -ScriptBlock {
try {
$cleanmgr = Start-Process -FilePath "C:\Windows\System32\cleanmgr.exe" -ArgumentList '/verylowdisk' -Wait -Verbose
if ($cleanmgr) {
return "Clean Manager ran successfully!"
}
}
catch [System.Exception] {
return "Cleanmgr is not installed! To use this portion of the script you must install the following windows features:"
}
}
}
Start-CleanMGR -computername "remotehost" -creds (Get-Credential)
As long as you execute cleanmgr.exe under a user account that has local admin rights, everything will work. Running cleanmgr.exe under the SYSTEM account, E.G. running from the Run Script Tool in SCCM/MECM will not work unless the script first opens a separate shell (DOS/PS) under a user that has local admin rights...even the cleanmgr.exe /verylowdisk will not run under the SYSTEM account.

Powershell Crash after couple of hours

I'm experiencing with weird case with my Powershell script.
I have written a script that's execute an .exe file
this exe runtime is about 3 hours but constantly crashing after 2 hors (1-2 minutes more or less)
I have break my head try to figure out why the process crashing
eventually I found that the .exe crashing because the powershell crashing.
Here is the process execution command:
$Proc = Start-Process -FilePath $ExePath -ArgumentList $Arguments -NoNewWindow -PassThru
$Proc | Wait-Process -Timeout 28800 -ea 0 -ev timeouted
After I realized this issue cased by the Powershell I have enabled windows powershell logging and find an error message "the pipeline has been stopped"
The script need perform more actions after the process ends and get its exit code, that's why I used the -PassThru flag.
I have tried to run it without using the PassThru flag or the Process-Wait command, the result stayed the same (the process crashed after 2 hours but there wasn't log with the message "The pipeline has been stopped")
Important points:
the .exe file is soured with try;catch blocks with logger but did not logged any thing when crashing- this is not a runtime error in the .exe file
When running the .exe independently from the command line its finish successfully after ~3 hours
The Powershell script run with Administrator privileges
The exe is not casing the crashing due to high CPU/Memory/Disk usage
I will follow up once I will have more updates.
Thanks for all the helpers.
Your help is much appreciated!
In my opinion the Start-Process cmdlet is good for quick things. But, it leaves a lot to be desired when trying to debug why an exe isn't behaving.
To work around this in your case it might be useful to use .Net objects to redirect and change certain things about your instantiation. I put an example function below that I've used when having trouble debugging exe runs.
function Start-Exe
{
param
( [string]$exePath, [string]$args1 )
$returnVal = $false
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $exePath
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = $args1
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
$exitCode = $p.ExitCode
#OutputFile can be some log file, or just use write-host to pump to console
#$stdout | Add-Content $global:OutputFile
#$stderr | Add-Content $global:OutputFile
return $exitCode
}
You can try it without using Wait-Process and see if it is reproducible.
Start-Process with -Wait parameter .
or Create it in a Job without -Wait and wait for the Job using Wait-.Job cmdlet
I had the same symptom when trying to execute an 8 hour process, it would always die after 2 hours, you need to clear the powershell IdleTimeout.
This answer helped me

Stuck command in Powershell but not in Cmd.exe

i'm facing a problem, my powershell script have a very strange comportement.
There is a little piece of a big script :
Write-Host "Installation in progress..."
Invoke-Command -Session $session -ThrottleLimit 64 -ScriptBlock {.\XenDesktopServerSetup.exe /QUIET /CONFIGURE_FIREWALL /components $using:componentparam /nosql }
Write-Host "Installation completed"
Sometimes even if the execution of XenDesktopServerSetup.exe is finished my script doesn't pass to the next command Write-Host "Installation completed"
I need to click somewhere in the shell or break the script with CTRL+C to see the end of my script;
I tried to change ThrottleLimit, but i doesn't have effect.
I'm using Powershell V4.0.
There is only one server in $Session.
EDIT :
I tried this command directly on my server, i opened a PS Shell and executed :
.\XenDesktopServerSetup.exe /QUIET /CONFIGURE_FIREWALL /components CONTROLLER /nosql
I had the same problem !
But when i tried the same command in Cmd.exe, it works perfectly and everytime !
How can i execute this command in Cmd.exe ? I want something like this :
Write-Host "Installation in progress..."
Invoke-Command -Session $session -ThrottleLimit 64 -ScriptBlock {Cmd.exe .\XenDesktopServerSetup.exe /QUIET /CONFIGURE_FIREWALL /components $using:componentparam /nosql }
Write-Host "Installation completed"
This shows us that there is a difference between cmd.exe and powershell in how PS make the call of .exe file, but I don't understand at all why it works in cmd.exe but not in powershell
Thanks for your suggestions
Are you sure all of the remote servers are done? You could use the -AsJob parameter and then periodically inspect the state of each job using Get-Job. Retrieve output with Receive-Job. You can even wait for all to finish with a timeout using Wait-Job $jobs -Timeout 120
This is how i resolved it, I tested it a lot and i don't have any issue :
Write-Host "Installation in progress..."
Invoke-Command -Session $session -ScriptBlock {$Components = $using:componentparam}
Invoke-Command -Session $session -ScriptBlock {Invoke-Expression "cmd /C '$IsoLetter\x64\XenDesktop Setup\XenDesktopServerSetup.exe' /QUIET /CONFIGURE_FIREWALL /components $Components /nosql" }
Write-Host "Installation completed"
What do you think? I think the problem is in the .exe file.. there is something wrong with.
But finally i solved it by using Invoke-expression and cmd /C

Resources