如何使用PowerShell在远程设备上设置时间?

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

我想将远程设备 (Raspberry Pi 2 运行 Windows IoT) 的日期和时间设置为值本地设备的日期时间。

我创建了一个变量 $dateTime 来保存本地日期时间。 我将连接到远程设备的密码分配给变量 $password。 我创建了一个凭证对象。 我使用 Enter-PSSession 连接到远程设备。 现在我已连接,我尝试使用 Set-Date = $dateTime | 分配远程设备 DateTime外弦。

我收到 cannot convertvalue "=" to type "System.TimeSpan" 错误。

$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

一旦我通过 PSSession 连接,似乎 $dateTime 变量就超出了范围。有解决办法吗?

我根本不会为此使用 Enter-PSSession,因为那是用于交互式会话。

我会用这个:

$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;
}

或者,如果我有多个任务要执行:

$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 通常需要 using 命名空间。