Using PSCredential Object to authenticate commands non-interactively - windows

I am using the PSCredential Object to authenticate a command, which I need to be run as a different user.
I get the following on the powershell cli.
> whoami
dmn1\srveikafka
> $secpasswd = ConvertTo-SecureString "mypassword" -AsPlainText -Force
> $mycreds = New-Object System.Management.Automation.PSCredential ("srveizookeeper", $secpasswd)
>
> $sess = new-pssession -computername remotecomputer.xyz.com -credential $mycreds
> invoke-command -session $sess -scriptblock {whoami}
dmn1\srveizookeeper
But when I run these same commands as a powershell script I get this error.
new-pssession : [remotecomputer.xyz.com] Connecting to remote server remotecomputer.xyz.com failed with the following
error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
At C:\workstation\add_zookeeper_spn.ps1:13 char:9
+ $sess = new-pssession -computername remotecomputer.xyz.com -credential $mycreds
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At C:\workstation\add_zookeeper_spn.ps1:14 char:25
+ invoke-command -session $sess -scriptblock {whoami}
+ ~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
What am I getting wrong or missing?

You might need to include the domain as part of the username in the credential constructor:
$mycreds = New-Object System.Management.Automation.PSCredential ("dmn1\srveizookeeper", $secpasswd)

Related

How to copy file to Ubuntu from Windows via PowerShell script

Source is Windows and destination is Ubuntu (installed on VMware player).
I ran below script in Windows:
$targetComputerName = "192.168.22.130"
$Username = 'zahid'
$Password = 'Z#hid1212'
$Pass = ConvertTo-SecureString -AsPlainText $Password -Force
$SecureString= $pass
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecureString
$Session = New-PSSession $targetComputerName -Credential $MySecureCreds
$DestinationPath = "/home/zahid/Downloads"
$Source = 'D:\zahid.txt'
Copy-Item -Path $Source -ToSession $Session -Destination $DestinationPath
$Session | Remove-PSSession
and got error:
New-PSSession : [192.168.22.130] Connecting to remote server 192.168.22.130 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.
At C:\Users\DELL\Desktop\Untitled1.ps1:8 char:12
+ $Session = New-PSSession $targetComputerName -Credential $MySecureCre ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CannotConnect,PSSessionOpenFailed
Copy-Item : Cannot validate argument on parameter 'ToSession'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command
again.
At C:\Users\DELL\Desktop\Untitled1.ps1:12 char:36
+ Copy-Item -Path $Source -ToSession $Session -Destination $Destination ...
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Copy-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.CopyItemCommand
Do I need to setup winrm service on destination (here is Ubuntu) also? How can I achieve that?
I used to use WinScp with PowerShell, or Posh-SSH.
These two ways allow you exploit conventional SSH on Linux.
Begining with PowerShell 6 you can use PowerShell remoting over SSH, this link show you the setup on Windows and Ubuntu.

Why is invoke-command and new-pssession not working?

I have no idea why this isn't working. Any ideas? I honestly don't know what else I can try.
I plan to add it to a script that prompts the user for a computername / domain creds but I can't get it to work in a shell window for starters.
Here's the line:
Invoke-Command -Session New-PSSession -ComputerName server001 -ScriptBlock {shutdown.exe /r -t 0}
Here's the error:
Invoke-Command : Cannot bind parameter 'Session'. Cannot convert the "New-PSSession" value of type "System.String" to
type "System.Management.Automation.Runspaces.PSSession".
At line:1 char:25
+ Invoke-Command -Session New-PSSession -ComputerName server001 -Scrip ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeCommandCommand
Sorry for not having anything further to add to this but I'm still trying to learn PowerShell and need guidance.
As the error indicates, the -Session parameter accepts arguments of type PSSession - and to create such an object we need to invoke New-PSSession (not just pass it's name as an argument):
$session = New-PSSession -ComputerName computer01
Invoke-Command -Session $session { ... }
If you don't plan on reusing the session later, you can simply pass the computer name directly to Invoke-Command, it'll handle session management for you implicitly:
Invoke-Command -ComputerName computer01 { ... }

Powershell: Passing Credentials in a PSSession to a machine returns Incorrect network password

Just some notes:
The issue that is being faced does not happen on every machine, only 1 in 20
I know it is not a powershell issue, but need to know from a health perspective what could cause this
The machine allows a connection with an Admin account over the PS Port, but after that the machine does not see the rights of the account
If I pass the Credentials using a Get-Credential rather than a PS Credential Object, it works however this is not an acceptable solution as the script it being wrapped in an MSO Runbook
Code being used for Credentials:
$Username = "domainname\userid"
$Password = "P#s4w0rd1!" | ConvertTo-SecureString -AsPlainText -Force
$mycreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $Password
Code for the PSSession:
$Session1 = New-PSSession -ComputerName WorkstationNAme #Connects to the computer
Invoke-Command -Session $Session1 -ScriptBlock {
$FreeDrive = (68..90 | %{$L=[char]$_; if ((gdr).Name -notContains $L) {$L}})[0] #Grabs the first available Drive Letter
$execDriveLocation = New-PSDrive -Name $FreeDrive -PSProvider FileSystem -Root $Using:Variable1 -Credential $using:mycreds -Persist #Creates temporary mapped drive
}
Error Returned on the affected machines:
The specified network password is not correct
+ CategoryInfo : InvalidOperation: (D:PSDriveInfo) [New-PSDrive], Win32Exception
+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand
+ PSComputerName : computername
Any thoughts or suggestions?

Powershell's Invoke-Command won't take in a variable for -ComputerName parameter

I just can't seem to get this to work, and I can't figure out how to google this issue. similar script is working remotly but now i need to made it work localy. But... Please check the script...
Function Local-Install {
$ComputerName = "$env:computername"
$AppName = "Deployment"
Invoke-Command -ComputerName $ComputerName ,$AppName -ScriptBlock `
{
param ($ComputerName,$AppName)
write-host "Getting Parameters for '$AppName' on $ComputerName"}
$Application = Get-WmiObject -computername $ComputerName -Namespace "root\ccm\ClientSDK" -Class CCM_Application | where {$_.Name -like "$AppName"} | Select-Object Id, Revision, IsMachineTarget
$AppID = $Application.Id
$AppRev = $Application.Revision
$AppTarget = $Application.IsMachineTarget
([wmiclass]'ROOT\ccm\ClientSdk:CCM_Application').Install($AppID, $AppRev, $AppTarget, 0, 'Normal', $False)
}
and i get an error like this:
Invoke-Command : One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects ins
tead of strings.
At line:5 char:1
+ Invoke-Command -ComputerName $ComputerName ,$AppName -ScriptBlock `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (System.String[]:String[]) [Invoke-Command], ArgumentException
+ FullyQualifiedErrorId : PSSessionInvalidComputerName,Microsoft.PowerShell.Commands.InvokeCommandCommand
Exception calling "Install" : ""
At line:13 char:1
+ ([wmiclass]'ROOT\ccm\ClientSdk:CCM_Application').Install($AppID, $AppRev, $AppTa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WMIMethodException
Since this is local you could just run the "env:COMPUTERNAME" call in the method. However, if you want to get this to work as is, you just need to add the -ArgumentList argument to the Invoke-Command call:
Invoke-Command -ComputerName $ComputerName, $AppName -ArgumentList $ComputerName, $AppName -ScriptBlock `

Powershell get-credentials fails

PS C:\Windows\system32> $creds = Get-Credential
cmdlet Get-Credential at command pipeline position 1 Supply values for
the following parameters: Credential
PS C:\Windows\system32> $ses = New-PSSession -ComputerName WIN-O4VC136J0E2 -Credential $creds
New-PSSession : [WIN-O4VC136J0E2] Connecting to remote server
WIN-O4VC136J0E2 failed with the following error message : The user
name or password is incorrect. For more information, see the
about_Remote_Troubleshooting Help topic. At line:1 char:8
+ $ses = New-PSSession -ComputerName WIN-O4VC136J0E2 -Credential $creds
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession],
PSRemotin gTransportException
+ FullyQualifiedErrorId : LogonFailure,PSSessionOpenFailed
The credentials I used are the same ones I used to login manually. Is there something else I am doing wrong? I've tried several different ways and never can seem to login.
Try the following, works very nicely with either a domain account or local account:
# Enter your pass and stores it securely:
$SecureString = Read-Host -AsSecureString 'Enter your password ' | ConvertFrom-SecureString | ConvertTo-SecureString
# Users you password securly
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "MyLoCalMachine\MyUserID",$SecureString
# Sets yous credentials to be used
$RemoteConn = New-PSSession -ComputerName $ts -Credential $MySecureCreds -Authentication default

Resources