如何使用PowerShell在远程设备上设置时间? [英] How to use PowerShell to set the time on a remote device?

查看:82
本文介绍了如何使用PowerShell在远程设备上设置时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我创建了一个变量$ dateTime来保存本地的DateTime. 我为变量$ password分配了用于连接远程设备的密码. 我创建一个凭证对象. 我使用Enter-PSSession连接到远程设备. 现在,我已经连接了,我尝试使用Set-Date = $ dateTime |为远程设备分配DateTime.外串.

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.

我得到无法将值"="转换为键入"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变量超出范围.有办法解决吗?

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

推荐答案

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

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

我会用这个:

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

将局部变量传递到远程会话通常需要using命名空间.

这篇关于如何使用PowerShell在远程设备上设置时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆