I have a PowerShell script that attempts to invoke bash shell script on a remote Linux machine. I use -ArgumentList to pass a parameter but get an error.
Sample om my script:
param ( [Parameter(mandatory=true)[string]$param1 )
Remove-SshSession
$session = New-SshSession -ComputerName $myServer -Command $StopServer
$result = Invoke-SshCommand -ComputerName $myServer -ScriptBlock {/root/scripts/Test.sh $args[0]} -ArgumentList $param1
The error:
Invoke-SshCommand : A Parameter cannot be found that matches parameter name 'ArgumentList'. At C:\TestProject\InstallBuild.ps1:6
+ ... root/test.sh $args[0]} -ArgumentList $param1...
+
+ CategogyInnfo : InvalidArgument: (:) [Invoke-SshCommand], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Invoke-SshCommand
How do I pass an argument to -ScriptBlock with Invoke-SshCommand?
Related
Below is my code, I've used the same process for connecting to sftp securely. I'm getting the error at the bottom of my post. Not sure if I'm missing a step in the creation of the key and password. Thanks.
#Set the credentials
$Password = Get-Content "c:\password.txt" |
ConvertTo-SecureString -Key (Get-Content "c:\aes.key")
$Credential = New-Object System.Management.Automation.PSCredential ('serviceaccount', $Password)
# Start a new instance of Windows PowerShell using the credentials
# stored in $Credential and run the script in $scriptblock
$powershellPath = "$env:windir\system32\windowspowershell\v1.0\powershell.exe"
$process = Start-Process $powershellPath -Credential $Credential -NoNewWindow `
-ArgumentList ("-ExecutionPolicy Bypass -noninteractive -noprofile " + $scriptBlock) -PassThru
# Script to execute in the new PowerShell instance
$scriptBlock = {
Import-Module ActiveDirectory
Get-ADUser ecarlsson | Set-ADUser -Manager bbob
Read-Host
}
I tried the code above and go the password error below.
Start-Process : This command cannot be run due to the error: The user name or password is incorrect.
At\filepath \\fV3.ps1:7 char:12
+ $process = Start-Process $powershellPath -Credential $Credential -NoN ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
I need to create a powershell script that launch an exe file which also has two parameters, I want to put it in a group policy, so that it starts at the power on of each computer.
I tried this command:
$Username = 'user'
$Password = 'pass'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $pass
invoke-command -Credential $Cred -ScriptBlock {& 'C:\myfile.exe' --param1 value --param2}
It tells me
Invoke-Command : Impossibile risolvere il set di parametri utilizzando i parametri denominati specificati.
In riga:1 car:1
+ invoke-command -Credential $Cred -ScriptBlock { & 'C:\Program Files ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.InvokeCommandCommand
I also tried this:
invoke-command -Credential $Cred -ScriptBlock {Start-Process -FilePath 'C:\myfile.exe' -ArgumentList "--param1 value", "-psb4"}
but the error that appears is the same.
I have a primary SCCM server - "ABC"
Later I installed SCCM console and PowerShell Module on one more machine - "XYZ"
I am running below script from server - "OPQ" and trying to remote "XYZ" (on which i installed SCCM Console Recently)
Script ::
$Session = New-PSSession -ComputerName "XYZ" -Authentication Kerberos -Credential $Cred -ConfigurationName Microsoft.PowerShell32
Invoke-Command -Session $Session -ScriptBlock {
Import-module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"
Set-Location PS1:\
}
ERROR ::
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : OpenError: (PS1:PSDriveInfo) [Import-Module], UnauthorizedAccessException
+ FullyQualifiedErrorId : Drive,Microsoft.PowerShell.Commands.ImportModuleCommand
+ PSComputerName : XYZ
Cannot find drive. A drive with the name '' does not exist.
+ CategoryInfo : ObjectNotFound: (PS1:String) [Set-Location], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
+ PSComputerName : XYZ
Well it appears you have a permissions issue. Here is how I executed a remote command in my SCCM environment, via my PSS:
$device = Invoke-Command -Session $sess -ScriptBlock {
Import-Module (Join-Path (Split-Path $env:SMS_ADMIN_UI_PATH)
ConfigurationManager.psd1)
Push-Location -Path ((Get-WmiObject -Namespace "root\SMS" -Class
"SMS_ProviderLocation" | Select-Object -ExpandProperty SiteCode) + ":")
Get-CMDevice -Name $env:COMPUTERNAME
Pop-Location
}
$device
RunspaceId : cbc7e008-d92c-4ba3-94a3-b75f8005be98
SmsProviderObjectPath : SMS_CM_RES_COLL_SMS00001.ResourceID=16777221
AADDeviceID : 00000000-0000-0000-0000-000000000000
AADTenantID : 00000000-0000-0000-0000-000000000000
ActivationLockBypassState :
ActivationLockState :
ADLastLogonTime : 3/31/2020 11:23:38 PM
ADSiteName : XXXX-XX
...
Note that if you're not remoting to your PSS, you will need to specify your PSS in the Get-WmiObject command, e.g.:
(Get-WmiObject -ComputerName [YOUR PSS] -Namespace "root\SMS" -Class "SMS_ProviderLocation" | Select-Object -ExpandProperty SiteCode) + ":"
I was able to resolve this issue by saving the credentials on the XYZ server and then calling them under my INvoke-Command.
Like This :
$Session = New-PSSession -ComputerName "XYZ"
Invoke-Command -Session $Session -ScriptBlock {
$password = Get-Content -Path D:\Creds\creds.txt | ConvertTo-SecureString
$Cred = New-Object System.Management.Automation.PSCredential ("domain\UserId", $password)
Then the rest of the code. ... .. . . .
}
I'm trying to set up PS Remoting/Win-RM and have the following:
$primary = 'server1'
$user = $env:UserName
$admUser = Get-Credential -UserName "domain\adm-$user" -Message 'Enter your *ADMIN* password:'
Enter-PSSession -ComputerName $primary -Credential $admUser {
hostname
}
However, this is returning the following error (I've tested this from a console and it works, so there's something wrong with my script):
Windows PowerShell credential request.
Enter your *ADMIN* password:
Password for user domain\adm-user1: ***************
Enter-PSSession : A positional parameter cannot be found that accepts argument '
hostname
'.
At line:5 char:1
+ Enter-PSSession -ComputerName $primary -Credential $admUser {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Enter-PSSession], ParameterBindingException
+ FullyQualifiedErrorId :PositionalParameterNotFound,Microsoft.PowerShell.Commands.EnterPSSessionCommand
What am I doing wrong? Thanks in advance!
Enter-PSSession opens a console connection to a remote system.
If you want to run a command on a remote system, you'd want to use Invoke-Command.
Also, you 100% always need to pass scriptblocks into some parameter (minus some edge cases where it's accepted by default). In this case, we need to use -Scriptblock.
Example:
Invoke-Command -ComputerName $primary -Credential $admUser -ScriptBlock {
hostname
}
or
$session = New-PSSession -ComputerName $primary -Credential $admUser
Invoke-Command -Session $session -ScriptBlock {hostname}
Invoke-Command -Session $session -ScriptBlock {$env:USERNAME}
Disconnect-PSSession -Session $session
I am trying to run a command on a remote session but I am getting a
Cannot index into a null array.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
+ PSComputerName : serverName
I have checked all the arguments that I am passing to the remote session and none of them are null. Following is the command:
Invoke-Command -Session $session -ScriptBlock {Start-Process $args[0] -ArgumentList $args[1] -RedirectStandardOutput $args[2] -RedirectStandardError $agrs[3]} -Args $Consoledir,$arguments,$stdOutLog,$stdErrLog;
I am using this command to run a console application that is passed in the $dir argument (D:\Temp\console.exe). This application further takes some arguments that are passed in the $arguments parameter.
Try this:
Invoke-Command -Session $session -ScriptBlock {
Param($dir, $args, $outlog, $errlog)
Start-Process $dir -ArgumentList $args -RedirectStandardOutput $outlog -RedirectStandardError $errlog
} -ArgumentList $Consoledir,$arguments,$stdOutLog,$stdErrLog;