Unresolved parameters (Invoke-Command) - powershell

When running the code below I get the error message
Invoke-Command : Missing an argument for parameter 'ComputerName'. Specify a
parameter of type 'System.String[]' and try again.
At line:11 char:16
+ Invoke-Command -ComputerName -ScriptBlock $scriptblock -Credential $Cred -Argum ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command],
ParameterBindingException
+ FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.InvokeCommandCommand
The code:
$item = "1337"
$username = "username"
$password = "password"
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, ($password | ConvertTo-SecureString -AsPlainText -Force)
$scriptblock = {
New-PSDrive -Name SampleDC -PSProvider FileSystem -Root \\sampleDC\scripts
."C:\scripts\sample.ps1" # include global functions scripts
new_user $args[0] # new_user is a function in global functions
}
Invoke-Command -ScriptBlock $scriptblock -Credential $Cred -ArgumentList $item

You cannot run Invoke-Command with different credentials without specifying a computer. The error you're getting is because you used the parameter -ComputerName without an argument.
To have Invoke-Command run the scriptblock on the local computer use either of the following commands:
Invoke-Command -Computer . -ScriptBlock $scriptblock -Credential $Cred ...
Invoke-Command -Computer localhost -ScriptBlock $scriptblock -Credential $Cred ...
Invoke-Command -Computer $env:COMPUTERNAME -ScriptBlock $scriptblock -Credential $Cred ...
Note that if the user whose credentials you're passing does not have admin privileges you'll be getting an error like this:
[localhost] Connecting to remote server localhost failed with the following
error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
In that case you need to enable PowerShell Remoting for them first. Run the following command in an elevated PowerShell console and add the user or group in the dialog that pops up.
Set-PSSessionConfiguration Microsoft.PowerShell -ShowSecurityDescriptorUI
From the documentation:
HOW TO ENABLE REMOTING FOR NON-ADMINISTRATIVE USERS
ERROR: ACCESS IS DENIED
To establish a PSSession or run a command on a remote computer, the user must have permission to use the session configurations on the remote computer.
By default, only members of the Administrators group on a computer have permission to use the default session configurations. Therefore, only members of the Administrators group can connect to the computer remotely.
To allow other users to connect to the local computer, give the user Execute permissions to the default session configurations on the local computer.
The following command opens a property sheet that lets you change the security descriptor of the default Microsoft.PowerShell session configuration on the local computer.
Set-PSSessionConfiguration Microsoft.PowerShell -ShowSecurityDescriptorUI

The computername parameter is missing. I believe you need to be at an elevated prompt to invoke-command on localhost.

Related

Test-Path Access denied Error - To check if Directory Exists on Shared Drive/Folder using powershell with credentials

I am trying to check if folder exists on network location using Test-Path powershell script with different credential having access to the Network Server but I am getting access denied error. Below is my script which I am trying to execute on local from where I am trying to connect to Network server:
$username="username"
$pass = "#Passw0rd" | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$pass
$pathExists = Invoke-Command -ComputerName . -Credential $cred -ScriptBlock {
Test-Path "\\serverName\Folder"
}
Write-Host $pathExists
I am getting below error:
Access is denied
+ CategoryInfo : PermissionDenied: (\serverName\Folder:String) [Test-Path], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.TestPathCommand
+ PSComputerName : localhost
Note: Admin access for the account is given which is used for accessing Network path and directory
Any help will be much appreciated
The issue most likely is because the credentials stored in $cred don't have Admin privileges on your localhost, hence cannot impersonate your invocation.
Here I'm trying something similar to what you're trying, the user stored in $cred is an Administrator on remote host but does not have any permissions on my laptop (I'm obfuscating for obvious reasons):
PS C:\> icm remoteServer -Credential $cred {test-path \\remoteServer\c$\users}
True
PS C:\> icm remoteServer -Credential $cred {test-path \\localhost\c$\users}
True
PS C:\> icm -computername . -Credential $cred {test-path \\localhost\c$\users}
[localhost] Connecting to remote server localhost failed with the following error message : Access is denied. For more
information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
Edit:
Here is another solution to your problem, Start-Process using the remote credentials and save the results to a file (again obfuscating the name of the remote server):
$argument="-c `"`$path='\\remoteServer\c$\users';'Attempting Test-Path '+`$path;'Result is: '+(Test-Path `$path)`""
$initHash=#{
FilePath='powershell.exe'
Credential=$cred
ArgumentList=$argument
RedirectStandardOutput="$HOME\Documents\testPath.txt"
WindowStyle='Hidden'
}
Start-Process #initHash
PS C:\> gc "$HOME\Documents\testPath.txt"
Attempting Test-Path \\remoteServer\c$\users
Result is: True

Running Powershell script using inline admin credentials to start and stop windows services

I have access as an admin on a machine and I have to Start, Stop and Restart some of the window services using the Powershell script. We don't want to have UAC prompt while running the script because only one user would have access to that machine. Also due to some specific requirements, we have to have run that script file by adding the admin credentials inside it.
Along with other solutions I have tried so far, the one close to what I am looking for is as follows
$username = "Domain\user"
$password = ConvertTo-SecureString "myPassword" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $password)
Set-Service -Name Spooler -Status Running -PassThru -Credential $psCred
But I am getting following error.
Set-Service : A parameter cannot be found that matches parameter name
'Credential'. At line:6 char:53
+ ... t-Service -Name Spooler -Status Running -PassThru -Credential $psCred
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
Update 1 (Trying suggestion)
Invoke-Command -credential $psCred -command {Set-Service -Name Spooler -Status Running -PassThru} -computername myComputerName
[myComputerName] Connecting to remote server myComputerName failed
with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS-Management service running on the
destination, most commonly IIS or WinRM. If the destination is the
WinRM service, run the following command on the destination to analyze
and configure the WinRM service: "winrm quickconfig". For more
information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (myComputerName:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : CannotConnect,PSSessionStateBroken
Update 2
I had to enabled PSRemoting on machine using command Enable-PSRemoting -Force -SkipNetworkProfileCheck so Invoke-Command can execute but after repeating the command Invoke-Command -credential $psCred -command {Set-Service -Name Spooler -Status Running -PassThru} -computername localhost I got following error
[localhost] Connecting to remote server localhost failed with the
following error message : Access is denied. For more information, see
the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
Running the same set of command in elevated powershell window is working fine.
Can you please guide me in the right direction considering I am newbie in the Powershell world.
As mentioned in the official documentation of Set-Service
Can you try like this?
$Cred = Get-Credential
$hostname = "$env:computername.$env:userdnsdomain"
Write-Host $hostname
Invoke-Command -ComputerName $hostname -Credential $Cred -ScriptBlock{ Start-Service -Name Spooler}
Also if you don't want to prompt for the credentials then you can store the credentials in the Windows credentials manager and get it from their in your PowerShell script. Refer to this answer for using credential manager with PowerShell

PSCredential variable stops working for WinRM function after being passed to get-winevent

I am seeing WinRM Client errors when reusing a Credential object, but only if I'm using it on Get-WinEvent, before I used it on Get-WindowsFeature.
If I replace the Get-WindowsFeature with an Invoke-Command calling Get-WindowsFeature against the server and using the same credentials object then things work as expected, but that causes other issues with different parts of my script, and I'd rather understand why it's not working.
I've stripped things down to the bare minimum to demonstrate the error and got to this.
$Cred = Get-Credential
$Name = "server01"
Get-WindowsFeature -ComputerName $Name -Credential $Cred
Get-winEvent -ComputerName $Name -Credential $Cred -MaxEvents 1
Get-WindowsFeature -ComputerName $Name -Credential $Cred
Expected Results
List of Windows features and their status on server01
The most recent event log entry on server01
List of Windows features and their status of server01
Actual Results
List of Windows features and their status on server01
The most recent event log entry on server01
Get-WindowsFeature : The WinRM client cannot process the request. Requests must include user name and password when Basic or Digest authentication mechanism is used. Add the
user name and password or change the authentication mechanism and try the request again.
At line:1 char:1
+ Get-WindowsFeature -ComputerName $Name -Credential $Cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-WindowsFeature], CimException
+ FullyQualifiedErrorId : Microsoft.Management.Infrastructure.CimException,Microsoft.Windows.ServerManager.Commands.GetWindowsFeatureCommand
why not try this instead
$Cred = Get-Credential
$Name = "server01"
invoke-command -ComputerName $Name -Credential $Cred -ScriptBlock {
Get-WindowsFeature
Get-winEvent -MaxEvents 1
Get-WindowsFeature
}

Powershell error when trying to enter psssession

I am trying to enter a new PSSession. If I manually run each line it works, but when I run it as part of a script, I get an error. The creds are valid and it seems the session is created, I just cant enter it in the script. The line number referenced is the write-host. Even if I just have an assignment to a variable it errors there.
$cred = New-Object Management.Automation.PSCredential ($username, $pw)
New-PSSession -ComputerName App02 -Credential $cred
Get-PSSession | Enter-PSSession
Write-Host "ERROR: Partial Service Deployment. See error log file(s)"
I get this as an error:
Cannot perform operation because operation "NewNotImplementedException
at offset 63 in file:line:column :0:0 " is not
implemented. At C:\DEV\Sandbox\Sandbox.ps1:29 char:14
+ Write-Host "ERROR: Partial Service Deployment. See error log file(s ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [], RuntimeException
+ FullyQualifiedErrorId : NotImplemented
You can't use Enter-PSSession in a script. Reason: It is intended for interactive purpose. You can use Invoke-Command with the corresponding -Session parameter to perform commands remotely.
See also this thread.
Example of Invoke-Command:
$cred = New-Object Management.Automation.PSCredential ($username, $pw)
$session = New-PSSession -ComputerName App02 -Credential $cred
Invoke-Command -Session $session -ScriptBlock { Get-Service * } #Return all services from the remote machine
Enter-PSSession can only be used interactively. For scripting, use Invoke-Command, and point it at the computer you want to run the command or scriptblock on.

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"}