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?
Related
I try to run script with higher permissions using -credential argument
When I try to do it using this part of code it shows that error which basically means that The name of the directory is incorrect. Both script (that one that contain start-process and the change_permissions.ps1 are in the same folder which is \\srv1\Projekty\nowy_folder.
Without -credential argument script works completely fine.
Here's whole script:
#gui
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form_start = New-Object System.Windows.Forms.Form
$form_start.Text = 'Tworzenie projektu'
$form_start.Size = New-Object System.Drawing.Size(340,175)
$form_start.StartPosition = 'CenterScreen'
$permission_button = New-Object System.Windows.Forms.Button
$permission_button.Location = New-Object System.Drawing.Point(95,25)
$permission_button.Size = New-Object System.Drawing.Size(135,23)
$permission_button.Text = 'Przydziel uprawnienia'
$permission_button.add_Click({
$username = "DOMAIN\USER"
$password = "PASSWORD"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
# Invoke-Command -FilePath "\\srv1\nowy_folder\change_permissions.ps1" -Credential $credentials
Start-Process powershell -argumentlist '.\change_permissions.ps1' -workingdirectory "S:" #-Credential ($credentials)
# Using UNC instead of .\change_permissions.ps1 isn't working
})
$form_start.Controls.Add($permission_button)
#Code below is basically the same but runs other script which also isn't running properly
$create_folders_button = New-Object System.Windows.Forms.Button
$create_folders_button.Location = New-Object System.Drawing.Point(110,75)
$create_folders_button.Size = New-Object System.Drawing.Size(100,23)
$create_folders_button.Text = 'Utwórz katalogi'
$create_folders_button.add_Click({
$username = "DOMAIN\USER"
$password = "PASSWORD"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
Start-Process powershell -argument "C:\Projekty\nowy_folder\make_project_folder_with_subfolders.ps1" -Credential ($credentials)
# $form_start.close()
})
$form_start.Controls.Add($create_folders_button)
$form_start.Topmost = $true
$form_start.ShowDialog()
As you may noticed I tried the invoke-command as well. While using the invoke-command another error shows up:
Do you have any solution to my problem?
Regarding such approach
Invoke-Command -FilePath c:\scripts\test.ps1 -ComputerName Server01
The FilePath parameter specifies a script that is located on the local computer. The script runs on the remote computer and the results are returned to the local computer.
if your file is locally saved, then you can try:
Invoke-Command -FilePath $localPath -computername srv1 -Credential $credentials
or you can use full path with such approach:
Invoke-Command -computername srv1 -scriptblock { \\srv1\nowy_folder\change_permissions.ps1} -Credential $credentials
or you can use direct path
Invoke-Command -computername srv1 -scriptblock { c:\scripts\change_permissions.ps1} -Credential $credentials
I'm having issues passing parameters to Invoke-Command, I've tried using -Args and -ArgumentList to no avail.
function One {
$errcode = $args
$username = "Ron"
$password = ConvertTo-SecureString -String "Baxter" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$cred
$Result = Invoke-Command -ComputerName MyPc -ScriptBlock { & cmd.exe /c "C:\Scripts\test.bat" Param1 $errcode ; $lastexitcode} -Credential $cred
echo $result
}
One 10
You can update your function to pass in your parameter as $errcode rather than using $args, this is better code as it's less confusing. (I'd recommend readng up on parameters and functions as it'll certainly help)
Then you need to pass $errcode into Invoke-Command using the ArgumentList parameter, and use $args[0] in its place:
function One ($errcode) {
$username = "Ron"
$password = ConvertTo-SecureString -String "Baxter" -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$Result = Invoke-Command -ComputerName MyPc -ScriptBlock { & cmd.exe /c "C:\Scripts\test.bat" Param1 $args[0] ; $lastexitcode} -Credential $cred -ArgumentList $errcode
echo $Result
}
One 10
I have a PowerShell script that creates a new PowerShell session. I need to return one of the variables from the myriad of variables that is created in this session to the local / calling session. Here is my PowerShell script:
param
(
[string]$user,
[string]$password
)
$secure_password = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential $user, $secure_password
$new_session = New-PSSession -Credential $cred
$script = {
$var1 = 0
$var2 = a
}
Invoke-Command -Session $new_session -ScriptBlock $script
Write-Host ($var2)
When the script executes Write-Host ($var2), it doesn't print any value for $var2. How can I return $var2 to the local session?
param
(
[string]$user,
[string]$password
)
$secure_password = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential $user, $secure_password
$new_session = New-PSSession -Credential $cred
$script = {
$var1 = 0
$var2 = a
$var2
}
$varFromSession = Invoke-Command -Session $new_session -ScriptBlock $script
Write-Host $varFromSession
Just return the variable from the session's scriptblock, either with Write-Output or return or just use the variable in another command as I've demonstrated. The return value of Invoke-Command will be whatever the scriptblock wrote to the pipeline.
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.
I am getting this error
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
From this script
$username = "Administrator"
$password = "PASSWORD"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$url = "http://www.website.com/file.zip"
$path = "C:\file.zip"
$client = new-object System.Net.WebClient
$client.DownloadFile( $url, $path )
Invoke-Command -ComputerName 69.69.69.69 -ScriptBlock { $client } -credential $cred
Running on Windows Web Server 2008
Script purpose is to download file.zip to a remote server (there are hundreds of servers so I can't be prompted for the password each time) and see the progress bar of the download.
Any ideas?
Try
$username = "Administrator"
$password = "PASSWORD"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$command = {
$url = "http://www.website.com/file.zip"
$path = "C:\file.zip"
$client = new-object System.Net.WebClient
$client.DownloadFile( $url, $path )
}
Invoke-Command -ComputerName 69.69.69.69 -ScriptBlock $command -credential $cred