Can I start a remote powershell session from a remote session? - powershell

I am able to successfully remote into one of the machines (ComputerA) in our enterprise at work using the following command
Enter-PSSession
Now can i start a new Enter-PSSession within this session to ComputerB? I am not able to do it. I get the following error:
Remote host method PushRunspace is not implemented.
+ CategoryInfo :
+ FullyQualifiedErrorId : System.Management.Automation.Remoting.PSRemotingDataStructureException,Microsoft.PowerSh
ell.Commands.EnterPSSessionCommand
I am able to start a session from a powershell prompt on ComputerA to ComputerB.
Is this even possible?
Thanks.

Enter-PSSession inside another interactive session is not supported. Instead, try Invoke-Command to run commands on a remote computer while being in an interactive session.
PS C:\> Enter-PSSession -ComputerName Server-02
[Server-02]: PS C:\> Invoke-Command -ComputerName Server-03 -ScriptBlock { GCI C:\ } -Credential (Get-Credential)

Related

invoke-command with a parameter accessing UNC

I am trying to generate some IDs using a adobe tool called adobe-licensing-toolkit.exe.
I need to run the command remotely in 100 computers.
Executing the command manually works flawless
C:\temp\adobe-licensing-toolkit.exe -c -f \\XXXXXXX\c$\temp\IDs.csv
Adobe Licensing Toolkit (1.1.0.98)
Operation Successfully Completed
Now I tried to replicate that using remote PS without success. I think it is a matter of parameters.
The following command ends correctly but it generates the file locally in the remote computer.
Invoke-Command -ComputerName $comp -ScriptBlock { param($whatToDo,$targetCSV) &('C:\TEMP\adobe-licensing-toolkit.exe') --$whatToDo --$targetCSV "C:\temp\ID.csv"} -ArgumentList "generateChallengeKey","filepath"
If I try to use the UNC in the parameter, the result is Operation failed.
Invoke-Command -ComputerName $comp -ScriptBlock { param($whatToDo,$targetCSV) &('\\XXXXXXXX\c$\TEMP\adobe-licensing-toolkit.exe') --$whatToDo --$targetCSV "C:\temp\ID.csv"} -ArgumentList "generateChallengeKey","filepath"
I also tried to add path in the parameter. In that case is powershell who complains.
Invoke-Command -Session $Server01 -ScriptBlock { param($whatToDo,$targetCSV) &('C:\TEMP\FRL\adobe-licensing-toolkit.exe') --$whatToDo --$targetCSV } -ArgumentList #("generateChallengeKey","filepath \\XXXXXXX\c$\temp\ID.csv")
unknown option -- filepath \\XXXXX\c$\temp\ID.csv
+ CategoryInfo : NotSpecified: (unknown option ...c$\temp\ID.csv:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : XXXXXXX
I have the feeling that the issue is in the way parameter is passed but I haven't managed to find the solution.
The exe file is already present in all target computers.
Any suggestion?
Thanks
I would presume you have toolkit present in all remote computer in path: "C:\TEMP\adobe-licensing-toolkit.exe". You can simply use
Invoke-Command -ComputerName $comp -ScriptBlock { & "C:\TEMP\adobe-licensing-toolkit.exe" -c -f \\XXXXX\$env:Computername-IDs.csv}
Adding $env:Computername in share path would generate unique file for each computer.

Powershell VSCode invoke-command from localhost different user for SCCM

Because VSCode is not able to run a powershell console and debug it as a different user i am trying to get arround it with invoked credentials like this:
Start-Service -Name "WinRM"
$cred = Get-Credential -Credential domain\myuser
Invoke-command -Credential $cred -Computer "localhost" -scriptblock {
Import-Module "$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
Set-Location 'XXX:' # my sccm site code
Import-CMComputerInformation -CollectionName "All Systems" -ComputerName "TestComputer" -MacAddress "00:00:00:00:00:69"
}
If i start it in the debugger of VSCode (F5) it starts but cant connect then to the SCCM Server infrastructure. Could someone help me to solve this issue?
Error:
Cannot find drive. A drive with the name 'XXX' does not exist.
+ CategoryInfo : ObjectNotFound: (XXX:String) [Set-Location], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
+ PSComputerName : localhost
This command cannot be run from the current drive. To run this command you must first connect to a Configuration Manager drive.
+ CategoryInfo : DeviceError: (Microsoft.Confi...ormationCommand:ImportComputerInformationCommand) [Import-CMComputerInformation], InvalidOperationException
+ FullyQualifiedErrorId : CommandCannotExecuteFromCurrentDrive,Microsoft.ConfigurationManagement.Cmdlets.Oob.Commands.ImportComputerInformationCommand
+ PSComputerName : localhost
If i logoff from my machine and login with my admin credentials and execute everything in the invoke-command scriptblock it works.
As i am not allowed to work like this by our company policy's is there maybe a alternative way or something i can do to use the visual studio code debugger?
Have you logged onto the SCCM site server interactively with the credentials you are using and opened the console at least once? I believe this initial first opening is required before the drive is accessible remotely...

Running a remote cmd command in PowerShell

I uploaded some files to a remote host with PowerShell, by FTP. On this host runs Windows 7 Embedded.
It turns out there is EWF (Enhanced Write Filter). So after a restart the uploaded files were gone. For saving the changes it needs commit them in cmd (at the remote host) by: ewfmgr d:-commit How can I include this command in my PowerShell code?
The code:
Enable-PSRemoting -Force
Set-Item wsman:\localhost\client\trustedhosts -Value * -Force
Restart-Service WinRm
Test-WSMan $line
Invoke-Command -ComputerName $line -scriptblock {cmd.exe /c "ewfmgr d: -commit"} -credential $FTPCredential
When I run Enable-PSRemoting -Force manually on the remote computer, it works, but it is uncomfortable and take lots of time. Is there another way to do this once for many hosts simultaneously?
Example-Code:
$session = New-PSSession -ComputerName yourRemoteComputer
Invoke-Command -Session $session -Scriptblock {ewfmgr d: -commit}
Remove-PSSession -Session $session
You have to enable Powershell Remoting on your host to invoke a command like this (https://technet.microsoft.com/en-us/library/ff700227.aspx)
If you need to transmit Credentials to your remote host, you can add the -Credential-Parameter to New-PSSession. This article describes how to add valid Credentials to your script (https://technet.microsoft.com/en-us/library/ff700227.aspx)
Greetings, Ronny

Access is Denied when Reset-ComputerMachinePassword is run through Invoke-command

I'm using the following command to reset a remote machine'
s password.
$user="Domain\domainadmin";
$pass="dapassword" | ConvertTo-SecureString -AsPlainText -Force;
$creds=New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $pass;
Invoke-Command -Credential $creds -ComputerName "DomainControllerMachine" -ScriptBlock{
$ComputerName = #"
SomeRemoteHost
"#
Import-Module ActiveDirectory;
Reset-ComputerMachinePassword -Server ${ComputerName};
}
I keep getting 'Access is denied' error.
This command cannot be executed on target computer('DomainControllerMachine') due to following error: Access is
denied.
+ CategoryInfo : InvalidOperation: (DomainControllerMachine:String) [Reset-ComputerMachinePasswor
d], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.ResetCompute
rMachinePasswordCommand
The account I use has all levels of access to the ActiveDirectory. So there won't be a issue with the credentials used for authentication.
If I run the same command on the 'DomainControllerMachine' (logged in as same user) it works fine.
Import-Module ActiveDirectory;
Reset-ComputerMachinePassword -Server "SomeRemoteHost";
Even the whole invoke-command block above just works without complaining on the DomainControllerMachine.
But when I do it remotely through Invoke-Command, or Enter-PSSession I get that dreaded access denied error..
I've also tried using CredSSP after setting up the WSManCredSSP (Client, delegation and Server) on the machines with no luck.
I may have missed something, or is there a better way to handle such a case?
It looks to me like you are running the Reset-computermachinepassword command on the domaincontroller. As far as I know it should be run on the computer that needs to be reset with the DC name in the -server field.
To do this you would need to run the command on the computer that needs it's credentials reset:
Reset-Computermachinepassword -server "DomainControllerMachine" -credential $PScredential
You can try to do it remotely with a PSsession if the computer has powershell remoting enabled. You will need to specify a different authentication method to reach a computer that has lost it's trust with the domain.
You can use Credssp but this will only work if your GPO allows delegating your credentials to the target computer.
Or you can use Basic authentication. But for that to work the Target must accept unencrypted traffic.
The command to do it remotely would probably look something like this:
$session = new-PSSession "targetcomputer" -Authentication Basic -Credential "Domain\domainadmin"
Invoke-Command -Session $session -scriptblock {Reset-Computermachinepassword -server "Domain\domainadmin"}

Running a Setup.exe from a network share, via Invoke-Command in Powershell

PSEXEC started to give me some trouble, and I decided to recode in PowerShell.
This batch command used to work for me, before PSEXEC started messing things up:
psexec -accepteula \\<ServerToBeUpdated> -u <User> -p <Password> cmd /c "\\<ServerWithInstallationFile>\SystemEnv\Bin\Setup.exe /silent /Update"
I'm trying to do this with Invoke-Command in Powershell, but with no luck so far.
I've tried many combinations, and googled a lot, and overall it seems that PowerShell is not fond of the UNC path I'm trying to install from.
Here is what I've got:
Invoke-Command -ComputerName <ServerToBeUpdated> -ScriptBlock { Start-Process -FilePath "\\<ServerWithInstallationFile>\SystemEnv\Bin\Setup.exe" -ArgumentList "/update /silent" -wait }
I get this error message:
This command cannot be run due to the error: Access is denied.
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
+ PSComputerName : DE5441
Some people say that the setup.exe has be copied locally on the remote server. But this does not seem to be an option for me, mainly for two reasons.
My setup.exe identifies that it is not in the right path, then it kills the local the setup.exe process, and automatically starts a new setup.exe from the UNC path.
I also need the ExitCode from my setup.exe, which gets lost when the "killing" starts as mentioned in reason number 1.
As a final note, I did grant access for PowerShell to run remotely with the Enable-PSRemoting command, and I also get expected results from this simple test:
Invoke-Command -ComputerName <ServerToBeUpdated> -ScriptBlock { Hostname }
You are experiencing a so called double-hop authentication issue. If using normal authentication you will not be able to authenticate to a second computer from the machine you are invoking the command on.
To solve this you can use CredSSP.
To enable CredSSP on the machine that is being called:
Enable-WSManCredSSP -Role Server -force
To enable CredSSP on the client:
Enable-WSManCredSSP -Role Client -DelegateComputer server.domain.com -force
The -delegateComputer parameter expects a FQDN but also takes wildcards.
After enabling CredSSP you can use it to invoke your command with the parameter -authentication CredSSP