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

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 ?

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.

Related

Need to execute winrm set winrm/config/client '#{TrustedHosts="192.168.4.231"}' command from PowerShell script from remote

I am firing following script from remote machine to add the executer IP (192.168.4.231) in trusted list. but the below script is getting fired but not I am not getting desired results.
Please let me know is there any wrong way I am executing below script.
$servers = #("192.168.4.236")
foreach($server in $servers) {
$username = 'administrator'
$password = '*******'
$pw = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ($username, $pw)
$s = New-PSSession -ComputerName $server -Credential $cred
Enter-PSSession $s
Invoke-Command -Session $s -Scriptblock {
Invoke-Expression 'winrm set winrm/config/client '#{TrustedHosts="192.168.4.231"}''
}
Write-Host "Completed"
Remove-PSSession $s
}

Passing Credentials In PowerShell multi line scriptblock

I have passed credentials before using a credential parameter in my Scriptblock and passing the value via an argument. I expect the size of my Scriptblock to grow so I am using a here string to keep it clean then I convert the string into a Scriptblock. How do I add a credential parameter and argument to my example below. I know the $credential value I use to get my remote session below has the necessary priveleges to get the file I want as I have tested it on the remote machine. So if possible I would like to pass this same credential.
$user = 'MyDomain\username'
$password = ConvertTo-SecureString 'mypassword' -asplaintext -force
$credential = New-Object -typename System.Management.Automation.PSCredential -ArgumentList $user, $password
try {
$s = New-PSSession -ComputerName MyRemoteComputer -Credential $credential
$remoteCommand = #"
New-PSDrive -Name 'P' -PSProvider 'FileSystem' -Root '\\main-server\Folders\DevOps\Projetcs\Juniper'
Get-Item -Path P:\V1.6\InstallFiles\Install.bat
"#
$scriptBlock = [Scriptblock]::Create($remoteCommand)
$status = Invoke-Command -Session $s -ScriptBlock $scriptBlock
Write-Host $status
Exit-PSSession -Session $s
}
catch {
#TODO Add exception handling
}

how to use different credentials inside an invoke-command

I am currently trying to get a value from a different server. So I am connecting to a server using $sessionUsername and $sessionPassword but then I need to use different credentials to get the information that I require.
I am unsure as to how I can do this, so far I have tried to do a Start-Job and a Start-Process inside the Invoke-Command and even another invoker command but this has not worked.
$sessionUserName = "mysession"
$sessionPassword = "sessionPassword"
#$sessionUserName = "LON\user"
#$sessionPassword = "user"
$serverAddress = "the address"
$securePassword = ConvertTo-SecureString -AsPlainText -Force -String $sessionPassword
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $sessionUserName,$securePassword
$session = New-PSSession -ComputerName $serverAddress -Credential $credentials
$username = "LON\differentuser"
$password = "different password"
$PSS = ConvertTo-SecureString $password -AsPlainText -Force
$cred = new-object system.management.automation.PSCredential $username,$PSS
Invoke-Command -Session $session -scriptblock {
#Start-Process "C:\StuckApps\powershell.exe" -Credential $args[0] -ArgumentList "-file C:\StuckApps\connect.ps1"
$args[0].GetNetworkCredential().username;
$args[0].GetNetworkCredential().password;
$t = {
$args[0].GetNetworkCredential().username;
$args[0].GetNetworkCredential().password;
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server = Theserver.co.uk; Database = m; Integrated Security = true;"
$conn.Open()
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandTimeout = 0
$command.CommandText = "exec dbo.AlphaBoard_GetStuckApps"
$command.Connection = $conn
$rows = $command.ExecuteReader()
$dt = New-Object System.Data.DataTable
$dt.Load($rows)
$number = $dt.Rows.Count
$conn.Close()
return $number
Write-Host "Hello"
}
Start-Job -ScriptBlock $t -Credential $args[0]
#Start-Process powershell -ArgumentList '-executionpolicy','bypass', $t -Credential $session
$number
} -ArgumentList $cred
$number
$previousNumberPath = "C:\bamboo-home\xml-data\build-dir\INT-SAM-JOB1\number.txt"
The $args[0].GetNetworkCredential().username; inside the invoke-command shows me that this is passing the credentials in, but how can I use them? I am not sure what I am doing wrong? I can't seem to get the $number variable back, how can I do this?
The main problem I have is the error
This command cannot be run due to the error: Access is denied.
Which I am unsure why this is happening as on the server itself it I run:
Start-Process powershell.exe -Credential $cred -ArgumentList "noexit", "-file C:\StuckApps\connect.ps1"
which I have also tried on my current script, it works fine, but using this on my script shows an access denied. I have already got on the server via the first invoke-command why can't I get the same result?

Execute remote PS command properly

I'm trying to change passwords on more than 1000 hosts running windows server 2008/2012. They assigned to different domains, so I connect to them via their IP, all of them have PowerShell remoting open.
Stuck at my script implementation. For now I just want to connect to single host and change the password of the user or admin whatever.
Here is the code I use
$username = "UserWhose Password I want to change"
$password = ConvertTo-SecureString "users old password" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
$serverNameOrIp = "host ip address here"
$s = New-PSSession -ComputerName $serverNameOrIp -Authentication default -Credential $cred
#invoke the scriptblock remotely
$sb = {
"[ADSI]`$Admin=`"WinNT://$env:COMPUTERNAME/$env:USERNAME`""
"`$Admin.SetPassword(`"Users new password`")"
}
Invoke-Command -Session $s -ScriptBlock $sb
Remove-PSSession $s
Now, the console output I get:
PS C:\> ./script
[ADSI]$Admin="WinNT://WIN-TA49U0TR9GT/Administrator"
$Admin.SetPassword("Users new password")
PS C:\>
"WinNT://WIN-TA49U0TR9GT/Administrator" belongs to remote host, my local computername and a username are different.
I'm not getting any error or proper output here. The password isn't changing. If I try to run these commands manually on any host - it works.
Any suggestions? Maybe a working solutions?
You define the commands you want to run on the remote host as strings inside a scriptblock. When you invoke the scriptblock on the remote host it does what PowerShell does with all bare strings: echo them.
Remove the outer quoting and escaping and the code should work as you expect:
$sb = {
[ADSI]$Admin = "WinNT://$env:COMPUTERNAME/$env:USERNAME"
$Admin.SetPassword("Users new password")
}
The scriptblock already prevents variables from being expanded in the current context.
Posting complete working script, that accept console arguments, connect to specified host and change the user password.
ARGS = IP USERNAME OLDPASS NEWPASS
Hope this will help somebody
$serverNameOrIp = $args[0]
$username = $args[1]
$password = ConvertTo-SecureString -String $args[2] -AsPlainText -Force
$newPassword = $args[3]
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
$s = New-PSSession -ComputerName $serverNameOrIp -Authentication default -Credential $cred
$sb = {
param($newPassword)
[ADSI]$Admin = "WinNT://$env:COMPUTERNAME/$env:USERNAME"
$Admin.SetPassword($newPassword)
}
Invoke-Command -Session $s -ScriptBlock $sb -args $newPassword
Remove-PSSession $s

Simple Powershell script doesn't work when compiled or run as a script

I have a simple snippet I can run no problems within the powershell console. When I compile it to an EXE, or even a ps1 and run it, it doesn't find the reg value, no idea why.
Here is the code:
$User = "Training\Administrator"
$PWord = ConvertTo-SecureString -String "P#ssWord" -AsPlainText -Force
$Credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$creds = $Credentials
enter-pssession –computername Win7Client –credential $creds
Start-Sleep -s 2
Set-itemproperty “HKLM:\SOFTWARE\Citrix\Metaframe Password Manager\Extensions\SyncManager\Syncs\DefaultSync\Servers” -name Server1 -value \\DFSI\CPMStore
Return
I would change the last lines to:
$Pssn = new-psssession –computername Win7Client –credential $creds
invoke-command -Session $Pssn -scriptblock {Set-itemproperty “HKLM:\SOFTWARE\Citrix\Metaframe Password Manager\Extensions\SyncManager\Syncs\DefaultSync\Servers” -name Server1 -value \\DFSI\CPMStore }
Return
Hope this helps,
Luc