Starting a process remotely in Powershell, getting %ERRORLEVEL% in Windows - powershell

A bit of background:
I'm trying to start and stop some performance counters remotely at the start of a test, then stop them at the end of the test. I'm doing this from an automated test framework from a Win2003 machine, the test framework executes commands without launching a console, some of the system under test is running Win2008. I've written scripts to choose the performance counters based on roles assigned to the servers.
My problem(s):
logman can't start or stop counters on machines that run a later version of the OS.
psexec can be used to run logman remotely, but psexec likes to hang intermittently when run from the test framework. It runs fine manually from the command line. I'm guessing that this is because the calling process doesn't provide a console, or some similar awkwardness. There's not much I can do about this (GRRRR)
I wrote a PowerShell script that executes logman remotely using the WMI's win32_process and called it from a batch script, this works fine. However, the test framework decides pass and fail scenarios based on the %ERRORLEVEL% and the content of stderr, but WMI's win32_process does not give me access to either. So if the counters fail to start, the test will plough on anyway and waste everyone's time.
I'm looking for a solution that will allow me to execute a program on a remote machine, check the return code of the program and/or pipe stderr back to the caller. For reasons of simplicity, it needs to be written in tools that are available on a vanilla Win2k3 box. I'd really prefer not to use a convoluted collection of scripts that dump things into log files then reading them back out again.
Has anyone had a similar problem, and solved it, or at least have a suggestion?

For reasons of simplicity, it needs to
be written in tools that are available
on a vanilla Win2k3 box. I'd really
prefer not to use a convoluted
collection of scripts that dump things
into log files then reading them back
out again.
PowerShell isn't a native tool in Windows 2003. Do you still want to tag this question PowerShell and look for an answer? Anyway, I will give you a PowerShell answer.
$proc = Invoke-WmiMethod -ComputerName Test -Class Win32_Process -Name Create -ArgumentList "Notepad.exe"
Register-WmiEvent -ComputerName test -Query "Select * from Win32_ProcessStopTrace Where ProcessID=$($proc.ProcessId)" -Action { Write-Host "Process ExitCode: $($event.SourceEventArgs.NewEvent.ExitStatus)" }
This requires PowerShell 2.0 on the system where you are running these scripts. Your Windows 2003 remote system does not really need PowerShell.
PS: If you need a crash course on WMI and PowerShell, do read my eGuide: WMI Query Language via PowerShell

Related

Do PowerShell ISE scripts produce system calls altering the entire OS down to the kernel?

I'm a complete rookie to programming. I will say so much off the bat: please go easy on me. I simply want to know what happens on a system-wide level when I run a script through the PowerShell ISE program. If I run something in an IDE, I have always assumed that no system calls are made, meaning the script isn't communicating with the kernel or making actual changes to the OS. To the contrary, the script is simply being run in a sandboxed environment, as a test run for lack of better terms. I use the term sandboxed loosely here.
If I am on the mark here regarding how an IDE works, does PowerShell also work the same way. If I am incorrect overall with all of my observations, please correct me. I'm just a tad bit beyond the phase of a script kiddie. I can write simple Bash scripts and execute PowerShell commands but I am miles behind the talent of a developer or full-time programmer. Looking for an answer from a veteran to a rookie here.
The PowerShell ISE is called an Integrated Scripting Environment. It can be thought of as a stripped down Visual Studio or maybe instead an enlightened Notepad with a paired PowerShell console.
In any case, and maybe someone will chime in with the true history of the ISE here, the PowerShell console is just as effective and powerful as the Linux Bash Shell, or the Windows Command Prompt.
Commands you run in PowerShell use underlying Windows APIs or dotnet namespaces which can absolutely change the system.
For instance, you can start and stop services or even disable them, if you've got the permissions and are running as an administrator. That's definitely changing the underlying system.
Set-Service -Name Spooler -StartupType Disabled
You can also change registry keys you definitely should not be touching.
#Disable Windows Update
Set-ItemProperty -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate -Name AU -Type DWord -Value "NoAutoUpdate"
Having permission to do these things depeneds on what your account can do. If you're running as a standard Windows user without admin rights, these calls will fail.
If you run the ISE or PowerShell without 'Run As Administrator', these calls will fail.
However, if you are an admin, and run PowerShell or the ISE as an Admin, you have effectively taken both safeties off and can now freely ventilate your foot.
Same goes for if you're running with a powerful Active Directory or Azure account. Only use those credentials when you need them, or your inevitable accidents will be truly remarkable, swift and terrible.

Programs running on Hyper-V with Invoke-Command hang

I'm trying to run my software on Hyper-V VM using powershell Invoke-Command, without success. Host OS -Windows 10. Guest OS - also Windows 10. VM Generation 1.
I did some simple experiments and found out this:
If I run
Invoke-Command -VMName MY_VM -Credential $Cred -ScriptBlock { calc }
then I can see launched calc.exe on the guest system right with UI.
But if I run mspaint or any non-Microsoft program, nothing happens. The program just hangs in the VM TaskManager without any effect.
I also tried to run several different programs using CLI calling Invoke-Command several ways, but got the same result.
What could be the problem?
The basic answer is that powershell remote connections (or any remote connection like rdp, ssh, etc) take place in a separate logon session, and can't really interact with each other.
There are two reasonable ways to do this:
Use PsExec - part of the microsoft sysinternals tools group.
# List sessions - note the session ID of the session you want the process to start in
quser /server:$computername
# Run a process remotely, specifying the logon ID
PsExec.exe -s -i $ID notepad.exe
Use a scheduled task that runs when you are logged in and is visible. You can do this with powershell's various New-ScheduledTask commands to create one, or follow this guide by Scripting Guy! using WMI Win32_ScheduledJob methods.
See use powershell to start a gui program on a remote machine for more details on both options, and a well-written description of why it's hard to do in windows.

Powershell closes on executing exe

I am trying to run and .exe in C:programfiles(x86)
I can launch it directly from the filepath. If I run in powershell just closes. No feedback.
Running powershell 5.1.17134 Rev 590
Start-Process -FilePath "C:\Program Files (x86)\App\App.exe"
I tried running powershell -NoExit and then start-process but it returns without any feedback.
If I run it on same machine in Powershell 6.1.0 preview - it runs fine. No issue. How can I track down whats causing this to 1) not run 2)close powershell.
Thanks,
This answer makes a general point. It doesn't solve your problem, if using Start-Process truly crashes the calling PowerShell window.
If C:\Program Files (x86)\App\App.exe is a console application that you want to run in the current console window, do not use Start-Process to invoke it.
Instead, invoke it directly.
Given that its path contains spaces and special characters (( and )), you need to:
quote it
invoke it with &, PowerShell's call operator.
PS> & 'C:\Program Files (x86)\App\App.exe'
Note:
The use of & with a command specified in a quoted string and/or via a variable reference is a syntactic necessity, given that PowerShell has two distinct parsing modes - see about_Parsing.
Invoking a console application directly:
ensures its synchronous execution
That is, control isn't returned to the caller until the application has terminated.
connects its standard output streams - stdout and stderr - to the equivalent PowerShell streams.
That is, you can capture or redirect the application's success output and/or error output, as needed.
You have an interactive shell. You spawn this new process - then your shell closes?
Clearly it is terminating its parent process, and clearly pwsh is doing something different.
I don't think this is truly a powershell question, it's a windows internals one. The suite of tools to use is Sysinternals. The first thing I'd try - and I'd do this on cmd, powershell and pwsh to establish a basis for comparison - is run Process Monitor with a filter on your app's path. Something in its last actions may prove illuminating. Process Explorer may also be useful.
Are you in a corporate environment? I have agents on my machine that kill processes based on heuristics. That can do things like this.
There may be a workaround based on how you invoke the app;
try mklement0's suggestion
try invoking through WMI; this does not provide your powershell process as a parent process: Invoke-WmiMethod -Class win32_process -Name create -ArgumentList "PathToApp.exe"
try invoking via cmd.exe if you are constrained by what's on your target machines
I do think this is off-topic, though.

Unable to get required information from remote machines using powershell invoke-command

I am developing a tool which uses powershell script to search for new windows updates for the machine. Currently by using the 'invoke-command' i am remotely accessing the various build controllers,virtual machines and hosts and running this powershell script. But invoke-command is unable to fetch the update details every time whenever it is executed.
the usage of invoke-command as follows:
invoke-command -computername buildcontroller1 -filepath searchupdates.ps1 -credential $myceredential
if i run this command, 1st time i will get the output, but when again if i run this command after 2 to 3 hours or after 1 day,its not retrieving the update details.
can anyone please tel me the reason for this.
I cannot tell you the reason for this.
I suspect the reason for needing to ask is an absence of error handling in the searchupdates.ps1 script.

powershell - launching local apps fast

I am building a kiosk type config script on low-spec hardware.
At the end of the script, it runs the various apps for the user to interact with. I currently use a plain Invoke-Command "path\to\app.exe". I want to get the interface up and running as quickly as possible. I want to launch the apps asynchronous.
I know there is start-job, and the -asJob flag in Invoke-Command, but they don't seem to work with launching visual apps. Is there a way to do this?
Windows subsystem (visual) EXEs start asynchronously by default. And you don't need Invoke-Command to invoke an exe. If you exeute notepad.exe like so:
PS> Notepad
PS>
Note that the PowerShell prompt returns immediately while notepad is still running. The same applies in a script.