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

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 { ... }

Related

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?

trying to get all the GPO's related to the OU with invoke command

I have a this set of code:
#Find the OU with the selected Canonical name and save it to this variable
$OUObject = Invoke-Command -Session $S -ScriptBlock {Get-ADOrganizationalUnit -filter * -Property CanonicalName | Where-Object {$_.CanonicalName -eq $using:listBox2.SelectedItem}}
So after this code i get a an OU stored in a variable $OUObject.
i now want to get all the gpo's linked to this ou.
so my next step is this:
$test = $OUObject.LinkedGroupPolicyObjects
and now $test hold all the gpos linked to its ou. problem now is i want to get them by name. so i can do this:
invoke-command -session $s -scriptblock {get-gpo -guid $test}
but i will get this error:
PS C:\WINDOWS\system32> invoke-command -session $s -scriptblock {get-gpo -guid $test}
Cannot validate argument on parameter 'Guid'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
+ CategoryInfo : InvalidData: (:) [Get-GPO], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.GroupPolicy.Commands.GetGpoCommand
+ PSComputerName : DC01
so i look at $test and this is what it holds:
PS C:\WINDOWS\system32> $test
cn={5873971D-F689-4E83-8AFA-389FDD7F34CD},cn=policies,cn=system,DC=bla,DC=local
cn={2B7F8931-038E-46BC-B1DB-FBFA86097C08},cn=policies,cn=system,DC=bla,DC=local
cn={C74CADA1-B609-44A3-8D3C-F733CF3112E2},cn=policies,cn=system,DC=bla,DC=local
so what i acually need is to past to the get-gpo command only the part inside the cn{..}
if i hardcode for example and do this:
invoke-command -session $s -scriptblock {get-gpo -guid 5873971D-F689-4E83-8AFA-389FDD7F34CD}
i get the result right.
can anyone help me achive this please?
Use the regex -replace operator to extract the GUID from the DN, then pass the value to Invoke-Command using the $using: modifier:
$GUIDs = $test -replace '^cn=(\{[0-9a-f-]+\}).*$'
Invoke-Command -Session $s { $using:GUIDs |ForEach-Object { Get-GPO -Guid $_ } }

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 `

Using PSCredential Object to authenticate commands non-interactively

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)

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