Enter pssession as admin

Enter pssession as admin DEFAULT

Powershell New-PSSession Access Denied - Administrator Account

There is a possible answer to this at the end, but a bit of background may help so I'm starting with that.

Intro

It is important to note that my answer is only related to loopback () sessions. It does not address problems with remote sessions.

Loopback sessions are useful as they enable a user with administrator rights to invoke user commands or scripts on the local host. An example of this is a toast message to a logged in user from a system monitoring program run under the System user. (Yes, there may be better ways of doing this but that's not what is being discussed here).

Background

I had exactly the same problem with exactly the same results as what is shown in the updates section of @Piotr's original question. I searched extensively on Google for an answer, but this yielded no working answers—even though a few people were reporting very similar issues.

Specs

As most people using Powershell remoting seem to not have this problem, it may be related to my machine's specs:

  • Windows 10 Home Version 1803.
  • Private network using WiFi connection

Possible Answer

The option worked for me, but I don't know why yet. It is confirmed to work for the PowerShell commands and , and may work for others as well.

Examples

To configure PowerShell remoting, the following command is needed once—though it will not harm anything if it is repeated. It will only work on private (not public) networks.

The following examples don't require an entry in Trusted Hosts.

is the computer name ==

= dot alias for

The IPv4 Address of the computer (, in my case) will only work if it is included in Trusted Hosts. The option isn't needed in this case.

Note that including and its other aliases in Trusted Hosts doesn't work in the above example ( is needed).

Sours: https://stackoverflow.com/questions/43190429/powershell-new-pssession-access-denied-administrator-account

How-to: Run with elevated permissions

Some PowerShell cmdlets and Windows commands such as REG ADD and SUBINACL have to be run from an elevated prompt, there are several ways of doing this.

It is possible to right click Powershell.exe (or it's Start menu shortcut) and run it 'As Admin'.
Shortcuts can be edited to always run as Admin - Properties | Shortcut | Advanced then tick "Run as administrator".

To elevate a script from a (non-elevated) PowerShell command line:

PS C:\> Start-Process powershell -ArgumentList '-noprofile -file MyScript.ps1' -verb RunAs

To run (and optionally elevate) a PowerShell script from a CMD shell, see the PowerShell.exe page.

A set of commands can also be saved in a scriptblock variable, and then passed to a new (elevated) PowerShell session:

Start-Process -FilePath powershell.exe -ArgumentList $code -verb RunAs -WorkingDirectory C:

To run an entire PowerShell session 'As Admin' from an existing PowerShell (non-elevated) session:

PS> Start-Process powershell.exe -Verb runAs

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

Testing for Elevation

A function that will return $True if the current session is running elevated or $False if not:

function isadmin { # Returns true/false ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator") }

To ensure a script is only run As Admin, add this to the beginning

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Echo "This script needs to be run As Admin" Break }

In PowerShell v4.0 the above can be simplified by using a #Requires statement:
#Requires -RunAsAdministrator

Self-Elevating script

If a script needs to be run elevated, then you can ensure it will only ever be run elevated by including the logic within the script.

If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { # Relaunch as an elevated process: Start-Process powershell.exe "-File",('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs exit } # Now running elevated so launch the script: & "d:\long path name\script name.ps1" "Long Argument 1" "Long Argument 2"

Scheduled Tasks

If a scheduled task invokes a UAC prompt, then the task may fail to run unattended, to prevent this make sure that you select the 'Run With Highest Privileges' check box, (or run Set-ScheduledJobOption -RunElevated )

Elevate Scheduled task

When a script is run with elevated permissions several aspects of the user environment will change: The current directory, the current TEMP folder and any mapped drives will be disconnected.

Windows Explorer Context Menu

To add a "Run as Administrator" context menu for .ps1 files, run this from an elevated PowerShell prompt:

PS C:\> New-Item -Path "Registry::HKEY_CLASSES_ROOT\Microsoft.PowershellScript.1\Shell\runas\command" ` -Force -Name '' -Value '"c:\windows\system32\windowspowershell\v1.0\powershell.exe" -noexit -file "%1"'

“Winners make a habit of manufacturing their own positive expectations in advance of the event” ~ Brian Tracy

Related PowerShell Cmdlets:

PowerShell.exe - Launch a PowerShell session/run a script.
VBScript: Run with Elevated Permissions
ElevationToolkit - Command-Line UAC Elevation Utility from Bill Stewart.


 

Copyright © 1999-2021 SS64.com
Some rights reserved

Sours: https://ss64.com/ps/syntax-elevate.html
  1. Fisher price plastic rocking horse
  2. Heart with airplane tattoo meaning
  3. El gran combo album covers
  4. Star wars redbox release date

 locked
How to create a new-pssession that runs a administrator

Windows PowerShellhttps://social.technet.microsoft.com/Forums/en-US/81786853-3b8e-4100-bb10-3da7ccb952cc/how-to-create-a-newpssession-that-runs-a-administrator?forum=winserverpowershellQuestion116/7/2013 5:41:13 AM7/8/2014 3:28:11 PMDiscussion on Windows Server Windows Powershell12

  • Question

  • text/html6/7/2013 5:41:13 AMSC TNE0

    Hello all,

    I'm trying to open a remote pssession to a management server that runs as administrator.

    When I logon to the server with my account account and start the powershell prompt, then it immediatly starts with elevated rights.

    UAC has been turned off and elevate without prompt is enabled via GPO.

    I've seen a lot of posts around this by not entering the PSSession, but running the commands through invoke-command.

    This doesn't work for me.. When I try to import the SCCM module for example, I get an access denied.

    I've also tried creating the session, entering it and then starting a new process: powershell.exe with the switch -verb runas.

    This doesn't do the trick neither.

    Does anyone have an idea how I can get this working?

    Thanks

    Filip

    • Edited bySC TNEFriday, June 7, 2013 5:41 AM

Answers

  • text/html6/7/2013 2:55:17 PMR Jason Morgan0

  • text/html6/7/2013 2:56:21 PMR Jason Morgan0

    Just as a side note if you are attempting to access ANY network resource from a remote session you will get access denied unless you have configured delegated credentials.


    Hope that helps! Jason

All replies

  • text/html6/7/2013 1:04:27 PMMike Laughlin0

  • text/html6/7/2013 1:17:29 PMSC TNE0

    Hello Mike,

    Yes, I'm aware of that and create a new pssession in a 32bit configuration.

    Filip

  • text/html6/7/2013 2:55:17 PMR Jason Morgan0

  • text/html6/7/2013 2:56:21 PMR Jason Morgan0

    Just as a side note if you are attempting to access ANY network resource from a remote session you will get access denied unless you have configured delegated credentials.


    Hope that helps! Jason

  • text/html6/10/2013 5:11:41 AMArthur_Li0

    Hi,

     

    I would like to confirm what is the current situation? If there is anything that I can do for you, please do not hesitate to let me know, and I will be happy to help.

    Regards,

    Arthur Li

    TechNet Subscriber Support

    If you are TechNet Subscriptionuser and have any feedback on our support quality, please send your feedback here.


    Arthur Li

    TechNet Community Support

  • text/html6/10/2013 5:31:12 PMSC TNE0

    Hello Jason,

    how do you configure delegated credentials?

    is this something to do with credssp?

    Thanks!

    FIlip

  • text/html6/10/2013 6:19:20 PMSC TNE0

    Hi Mike,

    Thank you for your reply.

    I read through the article and executed commands on both the winrm client and server and rebooted them to be sure.

    When I try to connect using credssp, I get the following error:

    Enter-PSSession : Connecting to remote server server.domain.local failed with the following error message : 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. For more
    information, see the about_Remote_Troubleshooting Help topic.


    I didn't configure to use SSL. Is this why it is failing?

    For the rest, I configured everything as described (also checked local policy (for fresh credential delegation) and this is set as described in the article 


    Regards,

    Filip


    • Edited bySC TNEMonday, June 10, 2013 6:19 PM
  • text/html6/10/2013 7:54:09 PMR Jason Morgan0

    Filip,

    Ultimately PSRemoting is a really big topic.  There are multiple books that deal with how to configure the various features.  Specifically using CredSSP and Double hop remoting are a little too broad for this forum.  You should look at PowerShell Deep Dives, available here:

    http://www.manning.com/hicks/

    And the powershell remoting book , available free, here:

    Powershell.org

    I'm not going to be able to walk you through that process.  I do, however, think that your original question has been answered.


    Hope that helps! Jason

  • text/html6/11/2013 4:39:00 AMSC TNE0

    Hello Jason,

    You are right, My initial question has been answered, but I do feel however (by reading that blog) that enabling CredSSP support only entails a couple of steps, of which I maybe missed one.

    I'll mark this topic as answered and open a new one for the issues I'm having with enabling it.

    Regards,

    Filip

Sours: https://social.technet.microsoft.com/Forums/en-US/81786853-3b8e-4100-bb10-3da7ccb952cc/how-to-create-a-newpssession-that-runs-a-administrator?forum=winserverpowershell
PowerShell Remoting

How to Run PowerShell Script on Remote Computer as Administrator

To optimize IT workload, you must have those sysadmins on your team who know how to automate repetitive tasks by writing scripts — this is where PowerShell skills come in handy. However, running a workstation with standard privileges, you’ll soon find out that it’s impossible to launch a PowerShell script with administrator privileges by right-clicking the script and selecting Run as administrator from the context menu (which is available for most the executable file formats over types of executable). In this article, I’ll show you:

  • How to run a PowerShell script on a remote computer
  • How to run a PowerShell script with administrative privileges.

How to automate administration with Windows PowerShell 2.0 Remoting

PowerShell Remoting (PSRemoting) infrastructure is based on Windows Remote Management version 2.0 (WinRM 2.0), and therefore inherits all the advantages of this technology, among which are transfer encryption encrypting the data transferred, and the ability to work usage of HTTP / HTTPS ports. PSRemoting offers a wide range of ever-useful features to administer remote computers and run commands on them.

Before discovering the PowerShell Remoting potential, you first need to activate it on workstations with administrator or standard privileges. To do so, run the cmdlet (Windows PowerShell command) Enable-PSRemoting. You may also add the -Force key to continue with no confirmation. This command prompt runs WinRM quickconfig, if necessary, and creates exceptions in Windows Firewall so that no further action is needed.

Having done things right, you’ve got access to other computers, and you can remotely execute commands by using the Invoke-Command cmdlet (or its alias — icm):

Invoke-Command -ComputerName Main -ScriptBlock {netsh interface dump > c:\ipconfig.txt}

You adjust the command specifying the -ComputerName parameter with one or multiple workstations. 

Meanwhile, you’ll find the following sequence quite useful as it displays the version of the Explorer.exe file from three computers at once:

$Command = {(get-item c:\Windows\explorer.exe).VersionInfo.FileVersion} Invoke-Command -ComputerName Main, Server7, Replica -ScriptBlock $Command

Sours: https://www.action1.com/how-to-run-powershell-script-on-remote-computer-as-administrator/

As admin pssession enter

Enter-PSSession

Starts an interactive session with a remote computer.

Syntax

Description

The cmdlet starts an interactive session with a single remote computer. During the session, the commands that you type run on the remote computer, just as if you were typing directly on the remote computer. You can have only one interactive session at a time.

Typically, you use the ComputerName parameter to specify the name of the remote computer. However, you can also use a session that you create by using the cmdlet for the interactive session. However, you cannot use the , , or cmdlets to disconnect from or re-connect to an interactive session.

Starting with PowerShell 6.0 you can use Secure Shell (SSH) to establish a connection to a remote computer, if SSH is available on the local computer and the remote computer is configured with a PowerShell SSH endpoint. The benefit an SSH based PowerShell remote session is that it works across multiple platforms (Windows, Linux, macOS). For SSH based remoting you use the HostName parameter set to specify the remote computer and relevant connection information. For more information about how to set up PowerShell SSH remoting, see PowerShell Remoting Over SSH.

To end the interactive session and disconnect from the remote computer, use the cmdlet, or type .

Examples

Example 1: Start an interactive session

This command starts an interactive session on the local computer. The command prompt changes to indicate that you are now running commands in a different session.

The commands that you enter run in the new session, and the results are returned to the default session as text.

Example 2: Work with an interactive session

The first command uses the cmdlet to start an interactive session with Server01, a remote computer. When the session starts, the command prompt changes to include the computer name.

The second command gets the PowerShell process and redirects the output to the Process.txt file. The command is submitted to the remote computer, and the file is saved on the remote computer.

The third command uses the Exit keyword to end the interactive session and close the connection. The fourth command confirms that the Process.txt file is on the remote computer. A ("dir") command on the local computer cannot find the file.

This command shows how to work in an interactive session with a remote computer.

Example 3: Use the Session parameter

These commands use the Session parameter of to run the interactive session in an existing PowerShell session (PSSession).

Example 4: Start an interactive session and specify the Port and Credential parameters

This command starts an interactive session with the Server01 computer. It uses the Port parameter to specify the port and the Credential parameter to specify the account of a user who has permission to connect to the remote computer.

Example 5: Stop an interactive session

This example shows how to start and stop an interactive session. The first command uses the cmdlet to start an interactive session with the Server01 computer.

The second command uses the cmdlet to end the session. You can also use the Exit keyword to end the interactive session. and Exit have the same effect.

Example 6: Start an interactive session using SSH

This example shows how to start an interactive session using Secure Shell (SSH). If SSH is configured on the remote computer to prompt for passwords then you will get a password prompt. Otherwise you will have to use SSH key based user authentication.

Example 7: Start an interactive session using SSH and specify the Port and user authentication key

This example shows how to start an interactive session using SSH. It uses the Port parameter to specify the port to use and the KeyFilePath parameter to specify an RSA key used to authenticate the user on the remote computer.

Parameters

-AllowRedirection

Allows redirection of this connection to an alternate Uniform Resource Identifier (URI). By default, redirection is not allowed.

When you use the ConnectionURI parameter, the remote destination can return an instruction to redirect to a different URI. By default, PowerShell does not redirect connections, but you can use this parameter to allow it to redirect the connection.

You can also limit the number of times the connection is redirected by changing the MaximumConnectionRedirectionCount session option value. Use the MaximumRedirection parameter of the cmdlet or set the MaximumConnectionRedirectionCount property of the preference variable. The default value is 5.

Type:SwitchParameter
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-ApplicationName

Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you are not using the ConnectionURI parameter in the command.

The default value is the value of the preference variable on the local computer. If this preference variable is not defined, the default value is WSMAN. This value is appropriate for most uses. For more information, see about_Preference_Variables.

The WinRM service uses the application name to select a listener to service the connection request. The value of this parameter should match the value of the URLPrefix property of a listener on the remote computer.

Type:String
Position:Named
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

-Authentication

Specifies the mechanism that is used to authenticate the user's credentials. The acceptable values for this parameter are:

  • Default
  • Basic
  • Credssp
  • Digest
  • Kerberos
  • Negotiate
  • NegotiateWithImplicitCredential

The default value is Default.

CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of the Windows operating system.

For more information about the values of this parameter, see AuthenticationMechanism Enum.

Caution: Credential Security Support Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the network session.

Type:AuthenticationMechanism
Accepted values:Default, Basic, Negotiate, NegotiateWithImplicitCredential, Credssp, Digest, Kerberos
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-CertificateThumbprint

Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate.

Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts.

To get a certificate, use the or command in the PowerShell Cert: drive.

Type:String
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-ComputerName

Specifies a computer name. This cmdlet starts an interactive session with the specified remote computer. Enter only one computer name. The default is the local computer.

Type the NetBIOS name, the IP address, or the fully qualified domain name of the computer. You can also pipe a computer name to .

To use an IP address in the value of the ComputerName parameter, the command must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in about_Remote_Troubleshooting.

Note: In Windows Vista and later versions of the Windows operating system, to include the local computer in the value of the ComputerName parameter, you must start PowerShell with the Run as administrator option.

Type:String
Aliases:Cn
Position:0
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

-ConfigurationName

Specifies the session configuration that is used for the interactive session.

Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: .

When used with SSH, this specifies the subsystem to use on the target as defined in sshd_config. The default value for SSH is the subsystem.

The session configuration for a session is located on the remote computer. If the specified session configuration does not exist on the remote computer, the command fails.

The default value is the value of the preference variable on the local computer. If this preference variable is not set, the default is Microsoft.PowerShell. For more information, see about_Preference_Variables.

Type:String
Position:Named
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

-ConnectionUri

Specifies a URI that defines the connection endpoint for the session. The URI must be fully qualified. The format of this string is as follows:

The default value is as follows:

If you do not specify a ConnectionURI, you can use the UseSSL, ComputerName, Port, and ApplicationName parameters to specify the ConnectionURI values.

Valid values for the Transport segment of the URI are HTTP and HTTPS. If you specify a connection URI with a Transport segment, but do not specify a port, the session is created by using standards ports: 80 for HTTP and 443 for HTTPS. To use the default ports for PowerShell remoting, specify port 5985 for HTTP or 5986 for HTTPS.

If the destination computer redirects the connection to a different URI, PowerShell prevents the redirection unless you use the AllowRedirection parameter in the command.

Type:Uri
Aliases:URI, CU
Position:1
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

-ContainerId

Specifies the ID of a container.

Type:String
Position:0
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

-Credential

Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as User01 or Domain01\User01, or enter a PSCredential object generated by the cmdlet. If you type a user name, you're prompted to enter the password.

Credentials are stored in a PSCredential object and the password is stored as a SecureString.

Type:PSCredential
Position:1
Default value:Current user
Accept pipeline input:True
Accept wildcard characters:False

-EnableNetworkAccess

Indicates that this cmdlet adds an interactive security token to loopback sessions. The interactive token lets you run commands in the loopback session that get data from other computers. For example, you can run a command in the session that copies XML files from a remote computer to the local computer.

A loopback session is a PSSession that originates and ends on the same computer. To create a loopback session, omit the ComputerName parameter or set its value to . (dot), localhost, or the name of the local computer.

By default, loopback sessions are created by using a network token, which might not provide sufficient permission to authenticate to remote computers.

The EnableNetworkAccess parameter is effective only in loopback sessions. If you use EnableNetworkAccess when you create a session on a remote computer, the command succeeds, but the parameter is ignored.

You can also allow remote access in a loopback session by using the CredSSP value of the Authentication parameter, which delegates the session credentials to other computers.

This parameter was introduced in Windows PowerShell 3.0.

Type:SwitchParameter
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-HostName

Specifies a computer name for a Secure Shell (SSH) based connection. This is similar to the ComputerName parameter except that the connection to the remote computer is made using SSH rather than Windows WinRM. This parameter supports specifying the user name and/or port as part of the host name parameter value using the form . The user name and/or port specified as part of the host name takes precedence over the and parameters, if specified. This allows passing multiple computer names to this parameter where some have specific user names and/or ports, while others use the user name and/or port from the and parameters.

This parameter was introduced in PowerShell 6.0.

Type:String
Position:0
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

-Id

Specifies the ID of an existing session. uses the specified session for the interactive session.

To find the ID of a session, use the cmdlet.

Type:Int32
Position:0
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

-InstanceId

Specifies the instance ID of an existing session. uses the specified session for the interactive session.

The instance ID is a GUID. To find the instance ID of a session, use the cmdlet. You can also use the Session, Name, or ID parameters to specify an existing session. Or, you can use the ComputerName parameter to start a temporary session.

Type:Guid
Position:Named
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

-KeyFilePath

Specifies a key file path used by Secure Shell (SSH) to authenticate a user on a remote computer.

SSH allows user authentication to be performed via private/public keys as an alternative to basic password authentication. If the remote computer is configured for key authentication then this parameter can be used to provide the key that identifies the user.

This parameter was introduced in PowerShell 6.0.

Type:String
Aliases:IdentityFilePath
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

-Name

Specifies the friendly name of an existing session. uses the specified session for the interactive session.

If the name that you specify matches more than one session, the command fails. You can also use the Session, InstanceID, or ID parameters to specify an existing session. Or, you can use the ComputerName parameter to start a temporary session.

To establish a friendly name for a session, use the Name parameter of the cmdlet.

Type:String
Position:Named
Default value:None
Accept pipeline input:True
Accept wildcard characters:False

-Port

Specifies the network port on the remote computer that is used for this command.

In PowerShell 6.0 this parameter was inlcuded in the HostName parameter set which supports Secure Shell (SSH) connections.

WinRM (ComputerName parameter set)

To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985, which is the WinRM port for HTTP, and 5986, which is the WinRM port for HTTPS.

Before using an alternate port, you must configure the WinRM listener on the remote computer to listen at that port. Use the following commands to configure the listener:

    Do not use the Port parameter unless you must. The port setting in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers.

    SSH (HostName parameter set)

    To connect to a remote computer, the remote computer must be configured with the SSH service (SSHD) and must be listening on the port that the connection uses. The default port for SSH is 22.

    Type:Int32
    Position:Named
    Default value:None
    Accept pipeline input:False
    Accept wildcard characters:False

    -RunAsAdministrator

    Indicates that the PSSession runs as administrator.

    Type:SwitchParameter
    Position:Named
    Default value:None
    Accept pipeline input:False
    Accept wildcard characters:False

    -Session

    Specifies a PowerShell session (PSSession) to use for the interactive session. This parameter takes a session object. You can also use the Name, InstanceID, or ID parameters to specify a PSSession.

    Enter a variable that contains a session object or a command that creates or gets a session object, such as a or command. You can also pipe a session object to . You can submit only one PSSession by using this parameter. If you enter a variable that contains more than one PSSession, the command fails.

    When you use or the EXIT keyword, the interactive session ends, but the PSSession that you created remains open and available for use.

    Type:PSSession
    Position:0
    Default value:None
    Accept pipeline input:True
    Accept wildcard characters:False

    -SessionOption

    Sets advanced options for the session. Enter a SessionOption object, such as one that you create by using the cmdlet, or a hash table in which the keys are session option names and the values are session option values.

    The default values for the options are determined by the value of the preference variable, if it is set. Otherwise, the default values are established by options set in the session configuration.

    The session option values take precedence over default values for sessions set in the preference variable and in the session configuration. However, they do not take precedence over maximum values, quotas or limits set in the session configuration.

    For a description of the session options, including the default values, see . For information about the preference variable, see about_Preference_Variables. For more information about session configurations, see about_Session_Configurations.

    Type:PSSessionOption
    Position:Named
    Default value:None
    Accept pipeline input:False
    Accept wildcard characters:False

    -SSHTransport

    Indicates that the remote connection is established using Secure Shell (SSH).

    By default PowerShell uses Windows WinRM to connect to a remote computer. This switch forces PowerShell to use the HostName parameter set for establishing an SSH based remote connection.

    This parameter was introduced in PowerShell 6.0.

    Type:SwitchParameter
    Accepted values:true
    Position:Named
    Default value:None
    Accept pipeline input:False
    Accept wildcard characters:False

    -Subsystem

    Specifies the SSH subsystem used for the new PSSession.

    This specifies the subsystem to use on the target as defined in sshd_config. The subsystem starts a specific version of PowerShell with predefined parameters. If the specified subsystem does not exist on the remote computer, the command fails.

    If this parameter is not used, the default is the 'powershell' subsystem.

    Type:String
    Position:Named
    Default value:powershell
    Accept pipeline input:True
    Accept wildcard characters:False

    -UserName

    Specifies the user name for the account used to create a session on the remote computer. User authentication method will depend on how Secure Shell (SSH) is configured on the remote computer.

    If SSH is configured for basic password authentication then you will be prompted for the user password.

    If SSH is configured for key based user authentication then a key file path can be provided via the KeyFilePath parameter and no password prompt will occur. Note that if the client user key file is located in an SSH known location then the KeyFilePath parameter is not needed for key based authentication, and user authentication will occur automatically based on the user name. See SSH documentation about key based user authentication for more information.

    This is not a required parameter. If no UserName parameter is specified then the current log on user name is used for the connection.

    This parameter was introduced in PowerShell 6.0.

    Type:String
    Position:Named
    Default value:None
    Accept pipeline input:False
    Accept wildcard characters:False

    -UseSSL

    Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.

    WS-Management encrypts all PowerShell content transmitted over the network. The UseSSL parameter is an additional protection that sends the data across an HTTPS connection instead of an HTTP connection.

    If you use this parameter, but SSL is not available on the port that is used for the command, the command fails.

    Type:SwitchParameter
    Position:Named
    Default value:None
    Accept pipeline input:False
    Accept wildcard characters:False

    -VMId

    Specifies the ID of a virtual machine.

    Type:Guid
    Aliases:VMGuid
    Position:0
    Default value:None
    Accept pipeline input:True
    Accept wildcard characters:False

    -VMName

    Specifies the name of a virtual machine.

    Type:String
    Position:0
    Default value:None
    Accept pipeline input:True
    Accept wildcard characters:False

    Inputs

    System.String, System.Management.Automation.Runspaces.PSSession

    You can pipe a computer name, as a string, or a session object to this cmdlet.

    Outputs

    None

    The cmdlet does not return any output.

    Notes

    To connect to a remote computer, you must be a member of the Administrators group on the remote computer. To start an interactive session on the local computer, you must start PowerShell with the Run as administrator option.

    When you use , your user profile on the remote computer is used for the interactive session. The commands in the remote user profile, including commands to add PowerShell modules and to change the command prompt, run before the remote prompt is displayed.

    uses the UI culture setting on the local computer for the interactive session. To find the local UI culture, use the automatic variable.

    requires the , , and cmdlets. If these cmdlets are not included in the session configuration on the remote computer, the commands fails.

    Unlike , which parses and interprets the commands before it sends them to the remote computer, sends the commands directly to the remote computer without interpretation.

    If the session you want to enter is busy processing a command, there might be a delay before PowerShell responds to the command. You are connected as soon as the session is available. To cancel the command, press +.

    The HostName parameter set was included starting with PowerShell 6.0. It was added to provide PowerShell remoting based on Secure Shell (SSH). Both SSH and PowerShell are supported on multiple platforms (Windows, Linux, macOS) and PowerShell remoting will work over these platforms where PowerShell and SSH are installed and configured. This is separate from the previous Windows only remoting that is based on WinRM and much of the WinRM specific features and limitations do not apply. For example, WinRM based quotas, session options, custom endpoint configuration, and disconnect/reconnect features are currently not supported. For more information about how to set up PowerShell SSH remoting, see PowerShell Remoting Over SSH.

    Prior to PowerShell 7.1, remoting over SSH did not support second-hop remote sessions. This capability was limited to sessions using WinRM. PowerShell 7.1 allows and to work from within any interactive remote session.

    Related Links

    Sours: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/enter-pssession
    Set Powershell to Run as Admin

    Run remote powershell as administrator

    Before I dive into the question, I have found several other questions that seem similar to mine, but they have not been able to solve my problem. Here are links to them:

    Remotely run a script invoking "Run As Administrator"

    https://stackoverflow.com/questions/10724591/how-to-remote-execute-an-elevated-remote-script-in-powershell

    Now onto the question: I need to run a Windows Update script on a remote machine via Powershell. If I remote into the machine via mstsc, run Powershell as administrator and run the Windows Update script, it works fine. If I remote into the machine via mstsc, run Powershell WITHOUT choosing the run as administrator, and run the script, I will get a bunch of errors along this line: "Exception calling "Download" with "0" argument(s): "Exception from HRESULT: 0x80240044""

    This only happens if I run it WITHOUT admin privileges.

    The script I am running is this: http://www.ehow.com/how_8724332_use-powershell-run-windows-updates.html

    Now, when I remote into the machine using Enter-PSSession and try to run the script I get errors, but they are a little bit different. They are along this line: "Exception calling "CreateUpdateDownloader" with "0" argument(s): "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))""

    I am open to suggestions as to what could be causing this problem, but I think I have it figured out. I believe that the Powershell session needs to be run with elevated privileges. I know how to do this while remoting in via mstsc, but I have been unable to find a way to do this via Enter-PSSession. I have Googled and Googled, but have not found anything. If anyone could help shed some light on this, that would be greatly appreciated.

    Sours: https://serverfault.com/questions/473991/run-remote-powershell-as-administrator

    Similar news:

    My task is simple: uninstall softwares using their default uninstaller (be it .MSI or .EXE) on each and every hostname from a CSV file. A sample of this CSV file would be something like that:

    Text

    Hostname,SoftwareName,SoftwareVersion,SoftwareVendor US0001,Google Chrome,60.0.3112.90,Google Inc. US0001,CCleaner,5.32,Piriform US0001,Spotify,1.0.60.492.gbb40dab7,Spotify AB US0002,Google Chrome,60.0.3112.90,Google Inc. US0002,Steam,2.10.91.91,Valve Corporation US0003,WinRAR 5.40 (64-bit),5.40.0,win.rar GmbH <and so on...>

    I do notwant to use Win32_Product, WMI, CIM, because:

    1. Why Win32_Product is Bad News!
    2. Event log message indicates that the Windows Installer reconfigured all installed applications
    3. Win32_Product Is Evil.

    This leaves me with only one option: querying the registry directly via Powershell in order to get the UninstallString parameter and use it to uninstall the program. Every computer has a local administrator account, let's call it ladmin. I'm using Invoke-Command to execute the below structure in loop to iterate over the hostnames. Right now, this is how I can get the software from the remote machine (lab environment, not production):

    Powershell

    Invoke-Command-ComputerName$hostname-ScriptBlock{Get-ChildItem-PathHKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall,HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall|Get-ItemProperty|Where-Object{$_.DisplayName-eq$using:softwareName}}-Credential$domain\Administrator|Format-List

    Output:

    Text

    PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\BitComet_x64 PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall PSChildName : BitComet_x64 PSProvider : Microsoft.PowerShell.Core\Registry PSComputerName : LAB01PC01 RunspaceId : f94bd32b-8224-40ee-b8ad-c2ab739da116 DisplayName : BitComet 1.46 UninstallString : C:\Program Files\BitComet\uninst.exe DisplayIcon : C:\Program Files\BitComet\BitComet.exe DisplayVersion : 1.46 VersionMajor : 1 VersionMinor : 46 InstallLocation : C:\Program Files\BitComet NSIS:StartMenuDir : BitComet (64-bit) URLInfoAbout : http://www.bitcomet.com Publisher : CometNetwork EstimatedSize : 29099

    It works, but I'm using the Domain Admin account Administrator, and that's a big no for me. I want to use the local administrator of each computer I'm running this script against, as we have Local Administrator Password Solution (LAPS) in place. This way I will generate a local admin password with a 5 minutes expiration time, run the script against that machine and let the password expire naturally. To turn this into reality, I was thinking about having a code like this:

    Powershell

    Invoke-Command-ComputerName$hostname-ScriptBlock{Get-ChildItem-PathHKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall,HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall|Get-ItemProperty|Where-Object{$_.DisplayName-eq$using:softwareName}}-Credential$hostname\ladmin|Format-List
    This way, I would login with $hostname\ladmin, e.g. US0001\ladmin. Sadly, it doesn't work and I get the following error:

    Text

    [LAB01PC01] Connecting to remote server LAB01PC01 failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic. + CategoryInfo : OpenError: (LAB01PC01:String) [], PSRemotingTransportException + FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken

    Tried searching it, but didn't find any actual help on how to really solve this :(

    -----


    So, how can I use Invoke-Command against remote local administrator account?

    Edited Aug 5, 2017 at 01:13 UTC

    Best Answer

    JChris

    Anaheim

    OP

    Found the issue, to login on local accounts on remote computers we need to add said computers to TrustedHosts on the machine that is running the script, or add the wildcard "*" to allow/trust all computers.

    Powershell

    Set-Item-PathWSMan:\localhost\Client\TrustedHosts-Value'*'

    Now, it's totally working. I set the value to "*" before running the script, then I go back to " " (nothing). Finally!!!!

    View this "Best Answer" in the replies below »

    11 Replies

    · · ·

    M Boyle

    Ghost Chili

    OP

    Ideally you'd have a separate account that is a member of the local admin group on each desktop. Then you'd use that account for the software removal.

    0

    · · ·

    JChris

    Anaheim

    OP

    M Boyle wrote:

    Ideally you'd have a separate account that is a member of the local admin group on each desktop. Then you'd use that account for the software removal.

    Maybe I didn't understand your answer correctly... This goes against all the mindset of local administrator password solution (LAPS). If there's only one account and this account is part of the local admin group of each and every computer on the domain, and this account gets compromised, you can say bye bye to everything. On the other hand, if the account "ladmin" of US0001 gets compromised, you have only one small problem as the same local admin account "ladmin" on machine US0002 has a different password. The local admin account "ladmin" is already a member of the local admin group on each and every machine. The issue is that I have to authenticate against the machine (US0001\ladmin, US0002\ladmin etc) and not the Kerberos server from AD.

    0

    · · ·

    tfl

    Mace

    OP

    You need to send a proper credential object, not just username and password. Do you get a popup? The error message just says that access is denied, meaning the credentials you are using is not valid for renting. I would reread the suggestion made in the error message.

    0

    · · ·

    JChris

    Anaheim

    OP

    tfl wrote:

    You need to send a proper credential object, not just username and password. Do you get a popup? The error message just says that access is denied, meaning the credentials you are using is not valid for renting. I would reread the suggestion made in the error message.

    I'm sending a proper credential object. I do get the prompt and enter the password:


    I even changed my code, to make things faster for testing, right now I use a $cred variable, like so:

    Powershell

    $domainAdminUsername='Administrator'$domainAdminPassword=ConvertTo-SecureString"supersecret"-AsPlainText-Force$cred=new-object-typenameSystem.Management.Automation.PSCredential-ArgumentList$domainAdminUsername,$domainAdminPasswordInvoke-Command-ComputerName$hostname-Credential$cred-ScriptBlock{<snip>}

    The script will run normally if the credential passed is from the Kerberos Server running on my DC LAB01DC01, but I need to authenticate using the local administrator account on $hostname(e.g. LAB01PC01\ladmin). The helpwasn't of any use. I searched for anything related to "local account", "remote local" etc, and didn't find a thing in there. The script must run using the local administrator account, as the user account (which authenticates using Kerberos) doesn't have enough privileges to uninstall softwares, and in production we are not allowed to use the Domain Admin account freely.
    Edited Aug 6, 2017 at 18:43 UTC

    0

    · · ·

    tfl

    Mace

    OP

    This is one of the key scenarios for the domain admin account - it is added to each machine's local administrator account. The Domain Admin account should work just fine, and you can re-inforce it with Group Policy.

    As to why this is failing - you are getting access denied - no idea.

    Can you use that $Cred object and 'Enter-PSSession' to one of the systems? If that fails, then I'd argue the password you are sending is not correct, or that account is disabled for some reason.

    0

    · · ·

    JChris

    Anaheim

    OP

    I believe we are out of sync here. I'll try to make this clear as water. I have two scenarios:

    1. Inside my lab, when I use the Domain Admin account "Administrator" (ACME\Administrator) as the credential for Invoke-Command, the script WORKS. But, this is a lab environment and I'm NOT allowed to use the real Domain Admin account from my company's AD to run the script. I'm just using a Domain Admin account (from the LAB AD) to test if the script really uninstalls the programs successfully, and it does. Right now, my only issue is how to authenticate the script in the real world.

    2. Inside my lab, when I use the remote Local Admin account "ladmin" (LAB01PC01\ladmin) as the credential for Invoke-Command, the script DOESN'T WORK, giving the error I said. I run the script on the machine LAB01PC02 against the LAB01PC01, and I need to use the LAB01PC01\ladmin account. In the real world scenario, there's one local admin account configured in ALL machines inside the company and all those machines have LAPS in place, so we can generate random and strong passwords with expiration time. Those local admin accounts are intended for cases like this regarding maintenance, field support, or any other task that needs elevated privileges inside a given computer.

    The password is correct and the account is enabled. I know Domain Admin account is inside each and every computer inside the AD, but we are not allowed to use that for security purposes, it's a very sensitive account that shouldn't be passed from hand to hand. I hope that clarifies things :/

    Edited Aug 6, 2017 at 21:58 UTC

    0

    · · ·

    tfl

    Mace

    OP

    I appreciate your position. As I said, the Doman Admin user was designed for the purposes of domain wide operations - just like you are trying to achieve here. It is the simplest solution to a simple problem and avoids the need for 3rd party apps. And as you know it works. But having said that...

    The error message you are getting says Access Denied. In Windows, there are basically two reasons for this. The usual is bad credentials (mistyped username or bad password). Can you open a terminal services connection using the same username and password?  Can you logon locally to the workstation with that set of credentials?

    The other reason is that while the credentials may be valid, the account has been denied access to the resource. To invoke a command on a remote system, PowerShell uses WinRM. Does the remote system have the WinRM service up and running? What endpoint are you using? And what is the ACL on that end-point?  What does Get-PSSessionConfiguration return? Can you use the Enter-PSSession on the remote machine?  I have not tried it, but if you take a network trace of the attempt to invoke the command, you may see more detailed error information in the network trace (probably a long shot). 

    Is the ladmin is a member of the local administrator's group? Does the ladmin user have permissions to access the default remoting end-point. What group memberships does the Ladmin user have? 

      Finally, what does the security log on the target workstation say?

    0

    · · ·

    tfl

    Mace

    OP

    I've re-read the LAPS details (https://www.microsoft.com/en-us/download/details.aspx?id=46899) which say: LAPS [sets] a different, random password for the common local administrator account on every computer in the domain.  It appears you are not using that user, instead you are using a separate user (Ladmin) . Have you tried using the actual Administrator user? And how did you create the ladmin user in the first place?

    0

    · · ·

    JChris

    Anaheim

    OP

    Best Answer

    Found the issue, to login on local accounts on remote computers we need to add said computers to TrustedHosts on the machine that is running the script, or add the wildcard "*" to allow/trust all computers.

    Powershell

    Set-Item-PathWSMan:\localhost\Client\TrustedHosts-Value'*'

    Now, it's totally working. I set the value to "*" before running the script, then I go back to " " (nothing). Finally!!!!

    1

    · · ·

    claus66

    Pimiento

    OP

    Hey Juan

    I've tried the same as you - to remote to a pc using laps local admin. 

    Did you do anything else than adding * to the trustedHosts? I can't get it to work

    I have following setting:

    Text

    Thanks,

    Claus

    0

    This topic has been locked by an administrator and is no longer open for commenting.

    To continue this discussion, please ask a new question.

    Sours: https://community.spiceworks.com/topic/2027703-how-to-use-invoke-command-with-remote-local-administrator-account


    950 951 952 953 954