问题
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