0
votes

I've written a script that needs to connect to several remote servers that are not on a domain. The end goal is to use Invoke-Command to create a scheduled task on the remote servers.

$name = $server."Name";
$cred = Get-Credential "$name\admin";

It causes a prompt to open and I enter the admin password. But when I call:

Invoke-Command -ComputerName $addr -Script $Script1 -Credential $cred 

The terminal prompts for the UserId.

If the username is entered again this error is given:

Cannot validate argument on parameter 'Password'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
    + CategoryInfo          : InvalidData: (:) [Register-ScheduledTask], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Register-ScheduledTask
    + PSComputerName        : 10.110.0.25

The script I'm running is this:

$Script1 = {Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass -Force -Confirm:$False; $A=New-ScheduledTaskAction -Execute "powershell.exe" -argument "-file C:\PSWU\Shared\ps.ps1"; $p=New-ScheduledTaskPrincipal -RunLevel Highest ; $C=New-ScheduledTask -Action $A -Principal $p ; Register-ScheduledTask T1 -InputObject $C -Password $SecurePassword;}
1
Your error comes from some command in $Script1 script, but you not show it.user4003407
I updated the post to include the script. I believe the error is coming from the New-ScheduledTaskPronciple command.Lambda42

1 Answers

0
votes

It seems the problem here is , $Script here is a ScriptBlock and its in its own scope. So it doesn't have any value for $SecurePassword variable.

use Param($SecurePassword) inside the script block and pass the original $SecurePassword vial -ArgumentList Parameter of Invoke-Command

Here is an example.

$Script = {param($r);"r is $r"}
Invoke-Command -ScriptBlock $Script -ArgumentList 'Value for r'

whatever the variables you are accessing inside a ScriptBlock either should be defined in side the ScriptBlock or should be passed as argument for Invoke-Command

If you are using script block in a script which is locally running, you can use variable scoping.

more info at Get-Help about_Script_Blocks

here too : https://technet.microsoft.com/en-us/library/hh847893.aspx

regards,

Kvprasoon