Bill Greer
Bill Greer

Reputation: 3156

How to use PowerShell to set the time on a remote device?

I want to set the Date and Time of a remote device (Raspberry Pi 2 running Windows IoT) to the value of the Date Time of a local device.

I create a variable $dateTime to hold the local DateTime. I assign a password to connect to a remote device to a variable $password. I create a credential object. I connect to the remote device using Enter-PSSession. Now that I'm connected I try assigning the remote devices DateTime using Set-Date = $dateTime | Out-String.

I get cannot convertvalue "=" to type "System.TimeSpan" error.

$dateTime = Get-Date
$password = ConvertTo-SecureString "mypassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("myremotedevice     \Administrator",$password)
Enter-PSSession -ComputerName myremotedevice -Credential $cred
Set-Date = $dateTime | Out-String

It seems as if the $dateTime variable is out of scope once I am connected via the PSSession. Is there a way around this ?

Upvotes: 0

Views: 7613

Answers (1)

Bacon Bits
Bacon Bits

Reputation: 32170

I wouldn't use Enter-PSSession for this at all, since that's for interactive sessions.

I'd use this:

$dateTime = Get-Date;
$password = ConvertTo-SecureString "mypassword" -AsPlainText -Force;
$cred = New-Object System.Management.Automation.PSCredential ("myremotedevice     \Administrator",$password);
Invoke-Command -ComputerName myremotedevice -Credential $cred -ScriptBlock {
    Set-Date -Date $using:datetime;
}

Or, if I had multiple things to execute:

$dateTime = Get-Date;
$password = ConvertTo-SecureString "mypassword" -AsPlainText -Force;
$cred = New-Object System.Management.Automation.PSCredential ("myremotedevice     \Administrator",$password);
$session = New-PsSession -ComputerName -Credential $cred;
Invoke-Command -Session $session -ScriptBlock {
    Set-Date -Date $using:datetime;
}
Invoke-Command -Session $session -ScriptBlock { [...] }
.
.
Disconnect-PsSession -Session $session;

Passing local variables to a remote session usually requires the using namespace.

Upvotes: 2

Related Questions