Reputation: 27
I am getting the following error when I run the function below:
Invoke-Command : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again. At C:\Users\usernameone\Desktop\script.ps1:16 char:29 + Invoke-Command -ComputerName <<<< $_ -ScriptBlock $s -Credential $cred + CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
$username = "username"
$password = "password"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$_="192.168.10.4"
function test{
$s = $ExecutionContext.InvokeCommand.NewScriptBlock("mkdir C:\'Documents and Settings'\username\Desktop\Testfolder")
Invoke-Command -ComputerName $_ -ScriptBlock $s -Credential $cred
}
Do you have any ideas as to what I've done wrong?
Upvotes: 1
Views: 196
Reputation: 8728
Rename your variable $_
and it will work...
Explanation:
$_
is "reserved" for the current value in an iteration e.g. foreach
or a pipeline. See here: What does $_ mean in PowerShell?
If you call your function as @x0n said, then it could make sense. If you want your function to create a folder everytime on the same machine, then don't use a variable. But if you want your function to create the folder on different machines your function should know on which computer you want the folder. That is normally done with a function parameter.
[...]
$ipaddress = "192.168.10.4";
function test([string]$ip, [System.Management.Automation.PSCredential]$credentials) {
$s = $ExecutionContext.InvokeCommand.NewScriptBlock("mkdir C:\'Documents and Settings'\username\Desktop\Testfolder");
Invoke-Command -ComputerName $ip -ScriptBlock $s -Credential $credentials;
}
// then call it like this
test $ipaddress $cred;
Here is a list of all those reserved things: http://www.neolisk.com/techblog/powershell-specialcharactersandtokens
Upvotes: 0
Reputation: 52420
The special variable $_
is only populated when the function or scriptblock containing it is involved in an active pipeline. It should work if you invoke test
like this:
PS> "computername" | test
Follow?
As an aside, why are you creating a scriptblock in that awkward fashion? Use literal syntax:
$s = { mkdir 'c:\...\blah' }
If you want to create scriptblocks programmatically from text, there's an easier way:
$s = [scriptblock]::create('...')
Don't forget to use single quotes if you don't want references to variables to be resolved before the scriptblock is parsed.
Upvotes: 1