Invoke-Command Cannot Bind Argument Error - powershell

Is Invoke-Command not pulling my variables?
Im caught on this one. I could use an xtra set of eyes!
Im pulling services from a remote machine and assigning them by number then passing a stop / start to the remote machine based off user input. Im getting a argument on my variable.
Please forgive the code setup Im new and I write then I clean. Some services and names have been removed for privacy.
Code::
$prepend = "ssssssssss"
$append = "sss"
$Fprepend = "tttttttt"
$Fappend = "tt"
$sitenumber = Read-Host 'What is the site number? ex. 1111'
$name = $prepend + $sitenumber + $append
$Fname = $Fname = $Fprepend + $sitenumber + $Fappend
$global:i=0
Get-service -Name Service,Instance,Server,Integration,Data,Message,FTP,Provider -ComputerName $name |
Select #{Name="Item";Expression={$global:i++;$global:i}},Name -OutVariable menu | Format-Table -AutoSize
$r = Read-Host "Select a service to restart by number"
$svc = $menu | where {$_.item -eq $r}
Write-Host "Restarting $($svc.name)" -ForegroundColor Green
Invoke-Command -ComputerName $Fname -ScriptBlock {Stop-Service -Name $svc.name -Force}
sleep 3
Invoke-Command -ComputerName $Fname -ScriptBlock {Start-Service -Name $svc.name -Force}
Get-service -Name $svc.name -Computername $name
Error::
Cannot bind argument to parameter 'Name' because it is null.
+ CategoryInfo : InvalidData: (:) [Stop-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.StopServiceCommand
Cannot bind argument to parameter 'Name' because it is null.
+ CategoryInfo : InvalidData: (:) [Start-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.StartServiceCommand

I have modified the code and now its working fine.
The issue what you are facing is because inside the script block , $svc is not holding any value because its not in the scope even. To make it within the scope you have to pass as an ArgumentList and it has to be initiated inside the block as param. Thats why ou are getting as Null
Use the below code. I just modified the Invoke part
$prepend = "ssssssssss"
$append = "sss"
$Fprepend = "tttttttt"
$Fappend = "tt"
$sitenumber = Read-Host 'What is the site number? ex. 1111'
$name = $prepend + $sitenumber + $append
$Fname = $Fname = $Fprepend + $sitenumber + $Fappend
$global:i=0
Get-service -Name Service,Instance,Server,Integration,Data,Message,FTP,Provider -ComputerName $name |
Select #{Name="Item";Expression={$global:i++;$global:i}},Name -OutVariable menu | Format-Table -AutoSize
$r = Read-Host "Select a service to restart by number"
$svc = $menu | where {$_.item -eq $r}
Write-Host "Restarting $($svc.name)" -ForegroundColor Green
# You have to pass the $svc as an argumentlist and the same has to be initiated as param inside the script block.
Invoke-Command -ComputerName $Fname -ScriptBlock {param($svc)Stop-Service -Name $svc.name -Force} -ArgumentList $svc
sleep 3
Invoke-Command -ComputerName $Fname -ScriptBlock {param($svc)Start-Service -Name $svc.name -Force} -ArgumentList $svc
Get-service -Name $svc.name -Computername $name
Hope you understand the issue now.

Related

PSSession search AD computers Powershell

Good afternoon everyone, I need to configure this script to run on AD machines, but I can only run it on the local machine, could you help me
I tried: $session = New-PSSession -ComputerName computer01
$events = Invoke-Command -ComputerName $session -ScriptBlock {`
param($days,$up,$down)
Get-EventLog `
-After (Get-Date).AddDays(-$days) `
-LogName System `
-Source EventLog `
| Where-Object {
$_.eventID -eq $up `
-OR `
$_.eventID -eq $down }
} -ArgumentList $NumberOfDays,$startUpID,$shutDownID -ErrorAction Stop
however it generated the error below:
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 instead of
strings.
At line:68 char:15
+ ... $events = Invoke-Command -ComputerName $session -ScriptBlock {`
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (System.String[]:String[]) [Invoke-Command], ArgumentException
+ FullyQualifiedErrorId : PSSessionInvalidComputerName,Microsoft.PowerShell.Commands.InvokeCommandCommand

Powershell SSH credentials

I have this script for automation execute command on multiple machines but appear one problem when I try to force user to enter credential:
Write-Host "Enter credentials!" -ForegroundColor Green
$user1 = Read-Host "user"
$pwd1 = Read-Host "pass" -AsSecureString
Write-Host "type command" -ForegroundColor Cyan
Write-Host "--------------" -ForegroundColor Cyan
Write-Host "example: shutdown -f -r -t 0" -ForegroundColor Cyan
$Command1 = Read-Host -Prompt "Comanda"
$Computers = Get-Content -Path C:\Users\Meo\Desktop\ipMachine.txt | Where-Object { $_ -match '\S' }
foreach($Computer in $Computers){
Write-Host $Computer
$User = "$user1"
$pwd1_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd1))
$secpasswd = ConvertTo-SecureString $pwd1 -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential ($User, $secpasswd)
$Command1 = "$Command"
Write-Host $Command
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $Computer -Credential $Credentials -AcceptKey:$true
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command
}
return ( if I put credential in script it works very well.. any ideea? thx)
New-SSHSession : Permission denied (keyboard-interactive).
At line:26 char:14
+ ... SessionID = New-SSHSession -ComputerName $Computer -Credential $Crede ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (Renci.SshNet.SshClient:SshClient) [New-SSHSession], SshAuthenticationException
+ FullyQualifiedErrorId : SSH.NewSshSession
Invoke-SSHCommand : Cannot bind argument to parameter 'SessionId' because it is null.
At line:28 char:26
+ Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-SSHCommand], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Invoke-SSHCommand
```

Powershell Remote Stop and Disable Service

SO Braintrust. I'm not a Powershell person, but I'm working on it. Trying to address yet another zero-day, I'm trying to build a reuseable script to remotely stop and disable the affected service. It is based on a script I got from a Microsoft MVP at (ultimately): http://portal.sivarajan.com/2010/07/stopstart-or-enabledisable-service_26.html
The prompt for the service name was added by me as well as the output information (Write-host & Add-Content lines), so I could get a results summation (the output part's not working fully, but it's the least of my concerns at the moment.).
$output = "c:\scripts\results.csv"
Add-content -path $output "======================"
Add-content -path $output "StopAndDisableService Output Start"
cls
$Cred = Get-Credential
$service = Read-Host -Prompt 'Enter Service Name" '
Import-CSV C:\Scripts\computers.csv | %
{
$computer = $_.ComputerName
Write-Host "Working on $computer"
Add-content -path $output "$computer"
$result = (Get-WmiObject win32_service -computername $computer -filter "name='$service'" -Credential $cred).stopservice()
Add-content -path $output " Stop - $result"
$result = (Get-WmiObject win32_service -computername $computer -filter "name='$service'" -Credential $cred).ChangeStartMode("Disabled")
Add-content -path $output " Disable - $result"
}
Add-content -path $output "======================"
Add-content -path $output "StopAndDisableService Output End"
when I run it, I get an error on the computer name
Get-WmiObject : Cannot validate argument on parameter 'ComputerName'.
The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Scripts\StopAndDisableService.ps1:12 char:54
+ ... result = (Get-WmiObject win32_service -computername $computer -filter ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand
Get-WmiObject : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Scripts\StopAndDisableService.ps1:14 char:54
+ ... result = (Get-WmiObject win32_service -computername $computer -filter ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand
Computer.csv contains one computer name per line, no punctuation, no FQDN, just the computer name
Special thanks to #Mathias R. Jessen for his help on this. Final working code. you will have to analyze the screen output to catch any errors and see which machines it did not catch due to being offline # time of running (some output file items have been commented out since they don't work as intended)
$output = "c:\scripts\results.csv"
Add-content -path $output "======================"
Add-content -path $output "StopAndDisableService Output Start"
cls
$Cred = Get-Credential
$service = Read-Host -Prompt 'Enter Service Name" '
Import-CSV C:\Scripts\computers.csv -Header ComputerName | % {
$computer = $_.ComputerName
Write-Host "Working on $computer"
Add-content -path $output "$computer"
$result = (Get-WmiObject win32_service -computername $computer -filter "name='$service'" -Credential $cred).stopservice()
#Add-content -path $output " Stop - $result"
$result = (Get-WmiObject win32_service -computername $computer -filter "name='$service'" -Credential $cred).ChangeStartMode("Disabled")
#Add-content -path $output " Disable - $result"
}
Add-content -path $output "======================"
Add-content -path $output "StopAndDisableService Output End"
Analyzing results on the screen output, any results with
Just the machine name - means it's processed without error on that machine (success)
RPC server is unavailable means machine is offline
Cannot call a method on Null-Valued expression on line 12 or line 14 means that service doesn't exist on that machine
The results.csv output file will contain list of names of the machines this script was run against

Check/read registry key value on remote computer with local admin credential

How to check registry key value on computer which is not in domain??
I think that I must use local admin credential for this but I dont know how
I tried this:
$user = "admin"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
$computer = "computer"
$domain=$computer
$username = $domain + "\" + $user
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$key = '\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters'
$valuename = 'DiskSpaceThreshold'
$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential
$value = $wmi.GetStringValue($HKEY_Local_Machine,$key,$valuename).svalue
$wmi
$value
But the result:
Get-Wmiobject : Could not get objects from namespace root\default. Serwer RPC jest niedostępny. (Wyjątek od HRESULT: 0x800706BA) At line:12 char:8
+ $wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Comp ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : INVALID_NAMESPACE_IDENTIFIER,Microsoft.PowerShell.Commands.GetWmiObjectCommand You cannot call a method on a null-valued expression. At line:13 char:1
+ $value = $wmi.GetStringValue($HKEY_Local_Machine,$key,$valuename).sva ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH : ReturnValue : 6 uValue : PSComputerName :
So I tried something else
# file with computer name
$computers = Get-Content F:\IT\!Set_NTP_Time\ReadRegistry\servers.txt | ?{$_ -notmatch "^#"};
#Registry Hives
[long]$HIVE_HKROOT = 2147483648
[long]$HIVE_HKCU = 2147483649
[long]$HIVE_HKLM = 2147483650
[long]$HIVE_HKU = 2147483651
[long]$HIVE_HKCC = 2147483653
[long]$HIVE_HKDD = 2147483654
# registry
$HKLM = 2147483650
$main = "Localmachine"
$keyPath = "System\CurrentControlSet\Services\W32Time"
$keyName = "Start"
#$computer ='.'
$reg = [WMIClass]"ROOT\DEFAULT:StdRegProv"
$Key = "W32Time"
#$Value = "HistoryBufferSize"
#$results = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
#"Current History Buffer Size: {0}" -f $results.uValue
<#
Param($computer)
$HKEY_Local_Machine = 2147483650
$reg = [WMIClass]"\\$computer\ROOT\DEFAULT:StdRegProv"
$Key = "SOFTWARE\Wow6432Node\Symantec\Symantec Endpoint Protection\CurrentVersion\SharedDefs"
$ValueName = "DEFWATCH_10"
$results = $reg.GetStringValue($HKEY_LOCAL_MACHINE, $Key, $ValueName)
write $results.sValue
#>
# credentials
$user = "admin"
$user1 = "admin1"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
# Start processing
foreach($computer in $computers) {
$domain=$computer
$username = $domain + "\" + $user
$username1 = $domain + "\" + $user1
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$Credential1 = New-Object System.Management.Automation.PSCredential -ArgumentList $username1,$password
try {
if (($computer -eq "comp1") -or ($computer -eq "comp2") -or ($computer -eq "name_of_computer") -or ($computer -eq "other_computer")) {
#$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential1
#$value = $wmi.GetStringValue($HKLM,$keyPath,$keyName).svalue
#Write-Host -ForegroundColor DarkYellow $computer $value
#$value = Invoke-Command -Scriptblock {Get-Item $HKLM,$keyPath,$keyName} -Computername $computer -Credential $Credential1
$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Credential1 | Where-Object {$_.Name -eq "StdRegProv"}
#$HKLM = 2147483650
#$value = $reg.GetStringValue($HKLM,$keyPath,$keyName).sValue
$value = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
Write-Host -ForegroundColor DarkYellow $computer $reg $value
} else {
#$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential
#$value = $wmi.GetStringValue($HKLM,$keyPath,$keyName).svalue
#Write-Host -ForegroundColor DarkYellow $computer $value
#$value = Invoke-Command -Scriptblock {Get-Item $HKLM,$keyPath,$keyName} -Computername $computer -Credential $Credential
$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Credential | Where-Object {$_.Name -eq "StdRegProv"}
#$HKLM = 2147483650
#$value = $reg.GetStringValue($HKLM,$keyPath,$keyName).sValue
$value = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
Write-Host -ForegroundColor DarkYellow $computer $reg $value
}
<#
if($value -eq 2)
{
Write-Host -ForegroundColor DarkYellow $computer "YES"
} else {
Write-Host -ForegroundColor Red $computer "NO"
}
#>
} catch {
Write-Host -ForegroundColor Red "$computer access denied.$_";
}
}
Result for this script
comp1 \COMP1\ROOT\default:StdRegProv System.Management.ManagementBaseObject
comp2 \COMP2\ROOT\default:StdRegProv System.Management.ManagementBaseObject
comp3 \COMP3\ROOT\default:StdRegProv System.Management.ManagementBaseObject
Personally, as I am used to use powershell remoting to gather information from remote machines, I would proceed like this:
Establish remote PS session
Run script on remote machine
Profit
So in your case, something like (If you are retrieving a value named DiskSpaceThreshold inside of HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters)
$user = "admin"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
$computer = "computer"
$domain=$computer
$username = $domain + "\" + $user
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$session = New-PSSession $computer -Credential $Credential
$r = Invoke-Command -Session $session -ScriptBlock { Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters -Name "DiskSpaceThreshold" }
Remove-PSSession $session
Write-Host $r.DiskSpaceThreshold
The effect of trying to run the script from P-L user post
New-PSSession : [computer] Connecting to remote server computer failed with the following error message : WinRM cannot process the
request. The following error with errorcode 0x80090311 occurred while using Kerberos authentication: There are currently no
logon servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTT
PS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see
the about_Remote_Troubleshooting Help topic.
At line:9 char:12
+ $session = New-PSSession $computer -Credential $Credential
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTran
sportException
+ FullyQualifiedErrorId : AuthenticationFailed,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 line:10 char:30
+ $r = Invoke-Command -Session $session -ScriptBlock { Get-ItemProperty -Path HKLM ...
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
Remove-PSSession : Cannot validate argument on parameter 'Id'. The argument is null. Provide a valid value for the argument,
and then try running the command again.
At line:11 char:18
+ Remove-PSSession $session
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Remove-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.RemovePSSessionCommand
The username and password are good.

PowerShell - Error in path while Set-FsrmQuota

I'm trying to make a script that changes the quota of a specific directory on a remote server. For that I'm using the following code ($Quota and $chosen_username enter as parameters):
$prefix_path = "C:\Shares\Users\";
$path = $prefix_path + $chosen_username;
if($Quota){
invoke-command -computername $servername {Set-FsrmQuota -path $path -Size $Quota+"GB"}
}
if((invoke-command -computername $servername {Get-FsrmQuota -path $path} | select #{n='QuotaSize'; e={$_.Size / 1gb -as [int]}}).QuotaSize -eq $Quota){
return "Success."
} else {
return "Failed."
}
And it is giving me this error:
Cannot bind argument to parameter 'Path' because it is an empty string.
+ CategoryInfo : InvalidData: (:) [Set-FsrmQuota], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Set-FsrmQuota
+ PSComputerName : ServerName
I've done debug and the value of $path is correct.
When using invoke-command on a remote computer, the local variables are unknown for the remote host, so you have to use either:
the using prefix for PS >= 3
invoke-command -computername $servername {Set-FsrmQuota -path $using:path -Size $using:Quota+"GB"}
the argumentlist parameter for PS < 3
invoke-command -computername $servername {Set-FsrmQuota -path $args[0] -Size $args[1]+"GB"} -argumentlist $path,$quota