PowerShell StartProcess: invalid handle - powershell

I'm trying to install google chrome on a remote machine through powershell.
This is what I'm trying to do (I've pretty much just scraped this together from a couple of other posts on various sites):
$Path = $env:TEMP;
$Installer = "chrome_installer.exe";
(new-object System.Net.WebClient).DownloadFile('http://dl.google.com/chrome/install/375.126/chrome_installer.exe', "$Path\$Installer");
Start-Process -FilePath $Path\$Installer -Args "/silent /install" -Verb RunAs -Wait;
Remove-Item $Path\$Installer
it's failing on the fourth line:
Start-Process -FilePath $Path\$Installer -Args "/silent /install" -Verb RunAs -Wait;
with the error:
Start-Process : This command cannot be run due to the error: The handle is
invalid.
At line:1 char:2
+ Start-Process -FilePath $Path\$Installer -Args "/silent /install" -V ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOp
erationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.C
ommands.StartProcessCommand
I'm quite inexperienced with PowerShell and I'm having a hard time figuring out what the "handle" in the error is.
Any help is appreciated :)
EDIT:
with a try/catch { $_ | FL * -Force} around the failing command it gives this output:
PSMessageDetails :
Exception : System.InvalidOperationException: This command cannot
be run due to the error: The handle is invalid.
at System.Management.Automation.MshCommandRuntime.Th
rowTerminatingError(ErrorRecord errorRecord)
TargetObject :
CategoryInfo : InvalidOperation: (:) [Start-Process],
InvalidOperationException
FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands
.StartProcessCommand
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, <No file>: line 4
PipelineIterationInfo : {}
With catching $_.Exception instead, it gives:
Message : This command cannot be run due to the error: The handle is
invalid.
Data : {}
InnerException :
TargetSite : Void ThrowTerminatingError(System.Management.Automation.ErrorR
ecord)
StackTrace : at System.Management.Automation.MshCommandRuntime.ThrowTerm
inatingError(ErrorRecord errorRecord)
HelpLink :
Source : System.Management.Automation
HResult : -2146233079

Elevation
The script would need elevation. To read about remote elevation:
https://ss64.com/ps/syntax-elevate.html
If you use Invoke-Command to run a script or command on a remote
computer, then it will not run elevated even if the local session is.
This is because any prompt for elevation will happen on the remote
machine in a non-interactive session and so will fail.
Using Enter-PSSession to start a whole new session will support
elevation if you specify CredSSP, which enables the delegation of user
credentials:
New-PSSession ss64dom.com -Auth CredSSP -cred ss64dom\user64
Zone identifier
The script could be hampered by the Internet Zone Identifier marker.
Source: http://woshub.com/how-windows-determines-that-the-file-has-been-downloaded-from-the-internet/
In PowerShell 3.0, you can display the list of files with
Zone.Identifier stream in a directory using this command:
Get-ChildItem -Recurse | Get-Item -Stream Zone.Identifier
-ErrorAction SilentlyContinue | Select-Object FileName
The attribute is removed as follows:
Remove-Item .\install-file.exe -Stream Zone.Identifier
In Windows PowerShell 4.0, you can delete Zone.Identifier using a
separate cmdlet:
Unblock-File install-file.exe
Addendum:
Remove-Item will raise an error if it does not find the alternate stream. Therefore use:
Remove-Item $Path\$Installer -Stream Zone.Identifier -ErrorAction SilentlyContinue

As far as I can tell, it comes down to the fact that in Azure Web App environments, you don't have permissions to install applications freely.
I guess management of the environment is restricted so they can guarantee a certain level of service.
You can read more about it here:
https://learn.microsoft.com/en-us/azure/app-service/choose-web-site-cloud-service-vm

try double-quoting the FilePath you are feeding the Start-Process command, OR use $(Join-Path $Path $Installer)
Right now you are escaping the $ for $Installer, so the path to the file cannot be resolved.
Start-Process -FilePath "$Path\$Installer" -Args "/silent /install" -Verb RunAs -Wait;
# OR (even better I think)
Start-Process -FilePath $(Join-Path $Path $Installer) -Args "/silent /install" -Verb RunAs -Wait;

Related

Wireguard powershell script not working only on Windows 7, rest windows OS working fine

I am using following code to download Wireguard .msi version, installing and creating tunnel with .conf file but the issue is its not working on Windows 7.
Basically When I execute PowerShell Script on Windows 7 the issue is its not even downloading wireguard .msi sometimes and if it download then it do not get install.
Start-Process msiexec.exe -ArgumentList '/q', '/I', 'wireguard-amd64-0.5.3.msi' -Wait -NoNewWindow -PassThru | Out-Null
Start-Process 'C:\Program Files\WireGuard\wireguard.exe' -ArgumentList '/uninstallmanagerservice' -Wait -NoNewWindow -PassThru | Out-Null
Start-Process 'C:\Program Files\WireGuard\wireguard.exe' -ArgumentList '/installtunnelservice', "$destinationConf" -Wait -NoNewWindow -PassThru | Out-Null
$source = "download.wireguard.com/windows-client/wireguard-amd64-0.5.3.msi" defines a local path. Use https:// prefix to define a web source.
Self-explained by running following script:
$source = "download.wireguard.com/windows-client/wireguard-amd64-0.5.3.msi"
$destinationWireguard = ".\wireguard-amd64-0.5.3.msi"
$webClient = [System.Net.WebClient]::new()
$webClient.DownloadFile($source, $destinationWireguard)
$source = "https://download.wireguard.com/windows-client/wireguard-amd64-0.5.3.msi"
$webClient.DownloadFile($source, $destinationWireguard)
Get-Item $destinationWireguard | Select-Object -ExpandProperty FullName
Result (note the self-explaining error message):
PS D:\PShell> D:\PShell\SO\73673275.ps1
Exception calling "DownloadFile" with "2" argument(s): "Could not find a part of the
path 'D:\PShell\download.wireguard.com\windows-client\wireguard-amd64-0.5.3.msi'."
At D:\PShell\SO\73673275.ps1:4 char:1
+ $webClient.DownloadFile($source, $destinationWireguard)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
D:\PShell\wireguard-amd64-0.5.3.msi
PS D:\PShell>

powershell script fails: This command cannot be run due to the error: %1 is not a valid Win32 application

Trying to write my first powershell script to trigger an MSI.
The msi file is located in the same folder as the ps file.
Problem
I'm getting the error message in the title when i try to run.
PS C:\Users\jj\source\github\electron\j> .\test.ps1
Start-Process : This command cannot be run due to the error: %1 is not a valid Win32 application.
At C:\Users\jj\source\github\electron\j\test.ps1:12 char:1
+ Start-Process .\node-v12.18.4-x64.msi -Wait -NoNewWindow
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
Yay. Install script executed successfully
Code
This is what the code looks like:
$DataStamp = get-date -Format yyyyMMddTHHmmss
$logFile = '{0}-{1}.log' -f $file.fullname,$DataStamp
$MSIArguments = #(
"/i"
('"{0}"' -f $file.fullname)
"/qn"
"/norestart"
"/L*v"
$logFile
)
Start-Process .\node-v12.18.4-x64.msi -ArgumentList $MSIArguments -Wait -NoNewWindow
Write-Host "Yay. Install script executed successfully"
What I've tried
I've tried triggering the msi directly from the powershell command line and it works fine.
Also removed all the commandline options in the ps file... but it still fails.
Lastly tried this for the start process command:
Start-Process -FilePath "$.\node-v12.18.4-x64.msi" -ArgumentList $MSIArguments -Wait -NoNewWindow
Any tips would be appreciated.
Thanks.

Run Remote PS script to deploy software

I am trying to run a powershell script to deploy an MS Access solution to multiple desktops. I have my script on a server share and I have tried to run it with out success. I have used the invoke-command to try and run the script and get this error message
Access is denied
+ CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException
+ PSComputerName : TESTVM-PC
I have also run all the psremoting commands and also tried the "Multi-hop" command. All with no success.
I have also tried to run the actual code in the script and it does not work.
Invoke-Command -Computer Dpierson-pc -Credential (get-credential) -ScriptBlock {
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force -Verbose
Copy-Item "\\Some\Bogus\Place\Access\*" C:\ -Recurse -Force -Verbose
Start-Process -FilePath "C:\Setup.exe" -PassThru -Verbose
Start-Sleep 30
Stop-Process -name Ninite -Force -Verbose
}
All I get is that the file setup could not be run because it does not exist. and the process then of course cannot be stopped as it does not exist. The credentials are my own and I am a domain admin. Any help would be appreciated. I have thought of making it batch file that I run via a group policy but that is the last thing I want to try as I plan on having more of these in the future.
P.S. I ran the " Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force -Verbose" on the machine locally as well.

Powershell: Running a .msc applet as another user

I'm currently writing a powershell script that asks for a single set of admin credentials, and uses those to run relevant applications, pulled from a network-hosted CSV. When I try to run
Start-Process $tools[$userInput-1].path.toString() -credential $credential
(where $tools is returning "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc") I get the error below
Start-Process : This command cannot be executed because the input "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc" is an Invalid Application. Give a valid application and Run your command again.
At line:1 char:14
+ Start-Process <<<< "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc" -credential
Get-Credential
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
If I need to, I'll just write a .bat file and run that, but I'd rather avoid that whenever possible.
And the reason I'm not using Invoke-Item is because it can't take -Credential, even if the man file says otherwise.
.msc is a saved console file, the host of which is mmc, so to start this from powershell you could use syntax similar to the following:
$mmcPath = "C:\Windows\System32\mmc.exe"
$mscPath = "C:\Program Files\Microsoft\Exchange Server\V14\Bin\Exchange Management Console.msc"
Start-Process -FilePath $mmcPath -ArgumentList $mscPath

Start-Process : Process with an Id of 5344 is not running

PS C:\> start regedit -ArgumentList '/S', 'D:\resources\hawk_config.reg' -Wait
Start-Process : Process with an Id of 5344 is not running.
At line:1 char:6
+ start <<<< regedit -ArgumentList '/S', 'D:\resources\hawk_config.reg'
+ CategoryInfo : NotSpecified: (:) [Start-Process], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.StartProcessCommand
I can't figure out what it is. Any ideas?
Doesn't the /S parameter cause regedit to exit as soon as it's merged the .reg file? I suspect the error you are getting is because regedit has already exited before Start-Process has a chance to call Process.WaitForExit() on the process object. Take a look at the bowels of the error by running $error[0] | Format-List * right after the command. WaitForExit() will throw a SystemException if the process has already exited. I can't repro this on PowerShell v3. Perhaps they fixed an issue with this cmdlet.
As a workaround you could try:
$p = start-process regedit -ArgumentList '/S', 'D:\resources\hawk_config.reg' -passthru
$p.WaitForExit()
WaitForExit() will throw a SystemException if the process has already exited.
I get this same thing randomly in a PS script that uses start-process in a loop. never on the same iteration, sometimes never at all. this would explain that behavior perfectly. Random asynchronous timing of threads and processes.
I tried the suggested error message dump and it looks like it confirms the idea that the process is finishing before WaitForExit() gets to see it:
Start-Process : Cannot process request because the process (38152) has exited.
$result = start-process <<<< -filepath $compiler -argumentlist $argstr -nonewwindow -passthru -wait
CategoryInfo : NotSpecified: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand