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

拥有回忆 提交于 2019-12-12 03:17:50

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/32828332/how-to-use-powershell-to-set-the-time-on-a-remote-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!