Run Remote PS script to deploy software - powershell

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.

Related

AzureDevops Pipelines Powershell Script New-PsSession Error

I'm trying to use a simple powershell script. I have such a script file like test.ps1 and its content is as follows.
$Session = New-PSSession -ComputerName MYPRSNLCMPTR
Copy-Item "C:\MyFolder" -Destination "C:\" -ToSession -Recursive
When I right click the test.ps1 and run with the powershell. The script is working. Copying folder on my local computer to remote computer.
When I add this script as a task in azuredevops pipeline this script gives me such an error like this:
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-
PSSession], PSRemotin
gTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Does anyone have any idea what could be the cause? What am I missing?

How to Install Windows Updates on Remote Computer with PowerShell

I'm trying to install Windows Updates on a Remote Computer with this command:
$InstallSplat = #{
AcceptAll = $true
SendReport = $true
IgnoreReboot = if ($Reboot) { $false } else { $true }
PSWUSettings = #{
SmtpServer = "my mail server"
From = "myfrom <myfrom#myfrom.com>"
To = "myto <myto#myto.com>"
Port = 25
}
}
Invoke-Command -ComputerName $_ -Credential $cred -AsJob -ArgumentList $InstallSplat -ScriptBlock {
param([hashtable]$InstallSplat)
Import-Module PSWindowsUpdate
Install-WindowsUpdate #InstallSplat
$Error | out-file C:\install\installwinupdate.log -Append
}
I pass a credential Object with domain admin privileges in $cred but I still always get this error
Install-WindowsUpdate : Access denied (Ausnahme von HRESULT: 0x80070005 (E_ACCESSDENIED)) In Zeile:4 Zeichen:25
+ Install-WindowsUpdate #InstallSplat
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-WindowsUpdate], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,PSWindowsUpdate.GetWindowsUpdate
The Command Install-WindowsUpdate itself does not have a credential parameter I could use. The Command needs to run in an elevated PowerShell, but I use an elevated PowerShell when starting this command on my Computer.
I Also tried creating a New-PSSession with my $cred and run Invoke-Command -Session $session instead of Invoke-Command -ComputerName $_ with the same result.
Does anybody know what's happening here? Why do I get Access denied?
It can't have anything to do with passing the $InstallSplat because the same thing happens if I don't pass any parameter at all and write the parameters and their Values directly at the command instead of splatting.
The Problem was, that you can't Download or Install Updates on a machine from another remote machine. Here's a list what you can or can't do remotely when it comes to Windows Updates
The solution is, to create a scheduled task on each server you want to install updates from a remote script, and start that task.
luckily, when you use the PSWindowsUpdate module, you don't have to do that yourself, you can just use Invoke-WUJob (formerly Invoke-WUInstall) which does the trick for you.
I used it like so ($ServerData.Value contains a list of my Servers) and it works like a charm. It creates a scheduled task on each server, and runs them immediately, if you add the -RunNow Parameter.
invoke-WUJob -ComputerName $ServerData.Value -Script { Import-Module PSWindowsUpdate ; Install-WindowsUpdate -AcceptAll -SendReport -IgnoreReboot -PSWUSettings #{From='xy';Port=25;SmtpServer='xy';To='xy'} | Out-File C:\install\PSWindowsUpdateLog.txt -Append} -Confirm:$false -verbose -RunNow
Note that what you specify as a script block in -Script will be pasted to -Command " <here> " in your scheduled task, so you should work with ' inside -Script.

PowerShell StartProcess: invalid handle

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;

Run a powershell script with different credentials

I'm trying to run a powershell script to search for a network drive for a certain file. In my testing, I've found that my script works perfectly fine, however the network drive I need to search require my Domain Admin logon.
I have
Start-Process powershell.exe -Credential "domain\adminusername" -NoNewWindow -ArgumentList "Start-Process powershell.exe -Verb runAs"
as the very first line of my script, but whenever I run the script I get this error:
Start-Process : This command cannot be run due to the error: The directory
name is invalid.
At Path\to\script.ps1:1 char:1
+ Start-Process powershell.exe -Credential "domain\adminusername" -NoN ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process],
InvalidOperationException
+ FullyQualifiedErrorId :
InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
What directory name is it talking about? If I move the script to the actual network drive, I still get the same error. How do you run a script as a different user?
You could use the net use command to gain access or the new-psdrive command instead. Another option would be to start-process a cmd prompt and use runas within it. Also, you may need to include the full path of powershell.exe or add it to the path variable. %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

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