How to remote to the computer itself with powershell - powershell

Now I need to run scripts on remote machines to do some deployment work by using:
Invoke-Command -ComputerName $hostName -Credential $cred -ScriptBlock $scriptBlock
And if the $hostName is the computer that calls this command, it reports:
message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (myMachineName:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
I want to run the command in a unified way no matter it is a remote or the local machine.
Updated:
I'm using using a machine in Azure. this command works:
Invoke-Command -ComputerName XXX -Credential $cred -ScriptBlock $scriptBlock
But this one not:
Invoke-Command -ComputerName XXX.cloudapp.net -Credential $cred -ScriptBlock $scriptBlock
Can anybody help?

Pass localhost as the computer name:
Invoke-Command -ComputerName localhost -Credential $cred -ScriptBlock $scriptBlock
Using the hostname of the computer should also work, as mentioned by #CB. in the comments to the question:
Invoke-Command -ComputerName $env:COMPUTERNAME -Credential $cred `
-ScriptBlock $scriptBlock
If you need the FQDN elsewhere and just want to remove the domain part for the Invoke-Command statement you can remove it like this:
Invoke-Command -ComputerName ($hostname -replace '\..*') -Credential $cred `
-ScriptBlock $scriptBlock
To handle the target computer name depending on whether or not the given hostname is the name of the local host you could do something like this:
$server = if (($hostname -replace '\..*') -eq $env:COMPUTERNAME) {
'localhost'
} else {
$hostname
}
Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock $scriptBlock
Note that either way WinRM must be enabled on the local computer for this to work.

Related

How to run multiple commands via Invoke-Command on remote server

In the below example, only the Get-Process in my scriptblock is being executed. "deh" does not print for some reason
Invoke-Command -ComputerName mycomputer -Credential $mycreds -ScriptBlock {
Get-Process
Write-Host "deh"
}
If I remove -ComputerName and execute on local, then it runs both commands just fine.
EDIT:
Here I am trying to execute IIS cmdlets against remote server. The following command works
Invoke-Command -ComputerName mycomputer -ScriptBlock {
Trace-Command CommandDiscovery {
Import-Module webAdministration
Start-WebAppPool -Name DefaultAppPool
} -PSHost
}
but this does not work
Invoke-Command -ComputerName mycomputer -ScriptBlock {
Import-Module webAdministration
Start-WebAppPool -Name DefaultAppPool
}
what is special about Trace-Command that it is helping Start-WebAppPool to work? this is really odd and I can't explain why this functionality..
No, the Invoke-Command cmdlet takes a scriptblock where you can put multiple commands. You should also be able to see the Write-Host output.
You can do a Trace-Command on the remote machine via Invoke-Command to see what is happening. I'm not able to reproduce this.
Invoke-Command -ComputerName mycomputer -Credential $Creds -ScriptBlock { Trace-Command CommandDiscovery {get-process;write-host 'deh'} -PSHost }
Try to separate the commands using a semicolon:
Invoke-Command -ComputerName mycomputer -Credential $mycreds -ScriptBlock {
Get-Process ;
Write-Host "deh"
}

How to use invoke-command in powershell, to run a script on remote machine

Is it possible to use Invoke-Command in PowerShell to run a script on a remote machine?
I have tried :
Invoke-Command -ComputerName $MyPC -Credential $mycreds -ScriptBlock {
& "C:\Users\MyPC\Desktop\scripts\Script1.ps1"
}
which returns
script1.ps1 is not recognized as the name of a cmdlet
The scenario here is, I have some scripts on a remote folder, and I need to use Invoke-Command or some other ways to run the script on a remote machine.
Also, how to write if I want to pass some parameters for script1.ps1? Thanks in advance!
Instead of this:
Invoke-Command -ComputerName $MyPC -Credential $mycreds -ScriptBlock {& "C:\Users\MyPC\Desktop\scripts\Script1.ps1"}
Try this:
Invoke-Command -ComputerName $MyPC -Credential $mycreds -FilePath C:\Users\MyPC\Desktop\scripts\Script1.ps1
to avoid confusion with filepaths on local machines/remote machines; i always run stuff from smb-shares; you can enter UNC as filepath... eg:
-FilePath \server\Netscripts\script.ps1

Privileges ACLs error when run remotely. invoke-command

I have a very simple script that works perfectly fine on a server, where I log on into the server and run it.
invoke-command -scriptblock { & snacfg workstation Computer /delete}
However, when I try to do it remotely, I receive "You do not have the privileges required to set system ACLs on files."
invoke-command -ComputerName SERVER -scriptblock {snacfg workstation COMPUTER /print} -Credential ""
I have also tried to call it remotely but get the same error message.
Start-Process powershell.exe -ArgumentList \\SERVER\c$\users\USERNAME\desktop\SCRIPT.ps1 -Credential ""
Any ideas?
Thanks.
You should probably leave the -Credential "" away, By adding this you bassicly telling it to run without an account I think. So either Remove it entirely so it will be run under the account of the current user, or declare the credentials like in the following 2 examples.
Option 1
$creds = Get-Credential
Invoke-Command -ComputerName Server -ScriptBlock { snacfg workstation computer /print } -Credential $creds
Option 2:
$pwd = ConvertTo-SecureString "ThePassword" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ("TheUsername", $pwd)
Invoke-Command -ComputerName Server -ScriptBlock { snacfg workstation computer /print } -Credential $creds

Need to remote access second hops via powershell with invoke-command

I struggle a lot of time regarding this problem now and asked already in another forum, which helped to approach to the solution but finally I didn't achieve it.
I "simply" need to gather information about hosts inside clouds here in our company with the help of a powershell script. You can reach the clouds via a jumphost from the local network, the jumphost is a part of the cloud as well. Then from the jumphost you can reach all cloudhosts.
So I have tried this with 2 pssessions and used invoke-command (same password for jumphost and cloudhost):
$cred = Get-Credential ad\username -Message "Please insert the password for the jumphost and the cloudhost"
$session = New-PSSession -ComputerName jumphost -Credential $cred
$cldhost = Read-Host "Please insert the name of the cloudhost"
$script = {
Param (
$Credential,
$cloudhost
)
$ses = New-PSSession -ComputerName $cloudhost -Credential $Credential
Invoke-Command -Session $ses -ScriptBlock { Get-ChildItem C:\ }
Remove-PSSession $ses
}
Invoke-Command -Session $session -ScriptBlock $script -ArgumentList $cred, $cldhost
Remove-PSSession $session
But this always gives me the output of C:\ of the jumphost and not of the cloudhost.
In the other forum I was advised to use credssp or delegated sessions.
CredSSP is not possible here, because I get the error that the SPN is missing in the AD-account and I'm not allowed to add one and the delegated sessions don't help me, because I have admin rights on the jumphost and the cloudhost and don't need to delegate something.
But anyway I think it's not a problem of the credentials, because I get no "Access denied" error or something else and enter-pssession to the jumphost and from there invoke-command to the cloudhost works without a problem, but I can't use this in a script.
Something seems to be wrong in the logic of the nested pssessions code...
Do you have any idea to make this work proper here?
delegated admin rights:
http://blogs.technet.com/b/heyscriptingguy/archive/2014/04/03/use-delegated-administration-and-proxy-functions.aspx
CredSSP:
http://blogs.technet.com/b/heyscriptingguy/archive/2012/11/14/enable-powershell-quot-second-hop-quot-functionality-with-credssp.aspx
Thanks a lot,
Marc
By the way:
I've tried to use CredSSP, because it is recommend to use it for second hops:
Enable-WSManCredSSP -Role Client -DelegateComputer jumphost -Force
$cred = Get-Credential ad\username -Message "Please insert the password for the jumphost and the cloudhost"
$session = New-PSSession -ComputerName jumphost -Credential $cred
Invoke-Command -Session $session -ScriptBlock {Enable-WSManCredSSP -Role Server –Force; Set-Item wsman:\localhost\client\trustedhosts -value localcomputer -Force; Restart-Service winrm -Force}
$session2 = new-PSSession -ComputerName jumphost -Credential $cred -Authentication Credssp
After entering this last command I get the following error:
The WinRM client cannot
process the request. A computer policy does not allow the delegation of the user credentials to the target computer because the
computer is not trusted. The identity of the target computer can be verified if you configure the WSMAN service to use a valid
certificate using the following command: winrm set winrm/config/service '#{CertificateThumbprint="<thumbprint>"}' Or you can
check the Event Viewer for an event that specifies that the following SPN could not be created: WSMAN/<computerFQDN>. If you find
this event, you can manually create the SPN using setspn.exe . If the SPN exists, but CredSSP cannot use Kerberos to validate
the identity of the target computer and you still want to allow the delegation of the user credentials to the target computer,
use gpedit.msc and look at the following policy: Computer Configuration -> Administrative Templates -> System -> Credentials
Delegation -> Allow Fresh Credentials with NTLM-only Server Authentication. Verify that it is enabled and configured with an SPN
appropriate for the target computer. For example, for a target computer name "myserver.domain.com", the SPN can be one of the
following: WSMAN/myserver.domain.com or WSMAN/*.domain.com. Try the request again after these changes. Weitere Informationen
finden Sie im Hilfethema "about_Remote_Troubleshooting".
In Zeile:1 Zeichen:13
+ $session2 = new-PSSession -ComputerName jumphost -Credential $cred -Aut ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportE
xception
+ FullyQualifiedErrorId : -2144108124,PSSessionOpenFailed
I do not know what to avtivate further to use CredSSP, anyway it would be better to make it work without CredSSP.
Ok additionally:
It should work with delegated sessions, I have tried the following:
on the Jumphost:
Register-PSSessionConfiguration -Name PowerShell.Session -SessionType DefaultRemoteShell -AccessMode Remote -RunAsCredential 'ad\username' -ShowSecurityDescriptorUI –Force
And then granted access to the user 'ad\username' (Invoke and Read access).
After that I was able to use the session configuration on the jumphost with the follwoing commands:
$cred = Get-Credential ad\username -Message "Please enter the password for jumphost"
$session = New-PSSession -ConfigurationName PowerShell.Session -ComputerName jumphost -Credential $cred
So the session was connected and I entered my other commands:
$cldhost = Read-Host "Please enter the cloudhost name"
$script = {
Param (
$Credential,
$Hostname2
)
$ses = New-PSSession -ComputerName $Hostname2 -Credential $Credential
Invoke-Command -Session $ses -ScriptBlock { Get-ChildItem C:\ }
Remove-PSSession $ses
}
Invoke-Command -Session $session -ScriptBlock $script -ArgumentList $cred, $cldhost
Remove-PSSession $session
Unfortunately I get the output of Get-ChildItem C:\ of the jumphost again and not the output of the cloudhost...
Do you have any further idea? Is maybe the $script{} part somewhere wrong?
Finally it works:
$cred = Get-Credential ad\username -Message "Please insert the password for the jumphost"
$session = New-PSSession -ComputerName jumphost -Credential $cred
$cldhost = Read-Host "Please insert the cloudhost name"
$script = {
Param (
$Credential,
$Hostname2
)
$ses = New-PSSession -ComputerName $Hostname2 -Credential $Credential
Invoke-Command -Session $ses -ScriptBlock { Get-ChildItem C:\ }
Remove-PSSession $ses
}
Invoke-Command -Session $session -ScriptBlock $script -ArgumentList $cred, $cldhost
Remove-PSSession $session
This means I do not need the delegated sessions or CredSSP. But anyway, it works as well by manual setting the delegated configuration on the jumphost and then adding the users who should be able to connect to the session configuration in the pop-up -ShowSecurityDescriptorUI and delete the default users "interactive user" and local administrators:
Register-PSSessionConfiguration -Name PowerShell.Session -SessionType DefaultRemoteShell -AccessMode Remote -RunAsCredential 'ad\username' -ShowSecurityDescriptorUI –Force
If you now connect to the session configuration with a above specified user the commands will be executed in context of the user you have specified under -RunAsCredential.
It is also working directly from the local host, but you have to use -SecurityDescriptorSddl and this requires a function which deletes the default credentials for the session configurations and adds the new credential with ACLs automatically...means a lot of work.
Thanks a lot for the help!
Marc

Get-WmiObject with credential fails when within Start-Job scriptblock

I am successfully retrieving some information from Windows 2000 machines using the Get-WmiObjet cmdlet. These machines are not part of our domain so I am using the -Credential parameter to pass local administrator credentials.
I am now trying to run several WMI queries in parallel using Start-Job but I can't get even one query to work.
When I run the following:
Start-Job -initializationscript {$cred = get-credential -credential administrator} -scriptblock {gwmi win32_computersystem -ComputerName 10.1.2.3 -Credential $cred}
a job is created, I am prompted for the credentials, but the job never completes, its state is always "Running".
Of course:
C:\>$cred = Get-Credential -credential administrator
C:\>gwmi win32_computersystem -ComputerName 10.1.2.3 -Credential $cred
works just fine.
How do I get Get-WmiObject to run successfully within Start-Job with alternate credentials?
Thanks for your help.
Try this:
$cred = Get-Credential -Credential Administrator
Start-Job -scriptblock {Param ($cred) gwmi win32_computersystem -ComputerName 10.1.2.3 -Credential $cred} -ArgumentList $cred
Looks like the background job is blocked for input and has been running forever for that reason.