Passing parameters to Invoke-Command - powershell

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

Related

Start powershell script with credentials of other user isn't working

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

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?

Executing powershell remotely issue

Hi when i try to do some code:
$Username = 'us'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
powershell.exe -command "Invoke-Command -ComputerName server.com -scriptblock {pathCopyAndUnzip.ps1} -Credential $Cred"
This prompt me for a password but when i try to run this command like here (without powershell.exe):
Invoke-Command -ComputerName server.com -scriptblock {pathCopyAndUnzip.ps1} -Credential $Cred
it works without prompt. Do you know how to resolve that? I need to use option 1 because this command is runned from TFS build definition file like here:
<Exec Command="powershell.exe -command "Invoke-Command -ComputerName $(Server) -scriptblock {path} -Credential $Cred"" Condition="'$(RunTests)' == 'True'"/>
You could put your script into it's own file and then call that from TFS rather inline code.
C:\folder\script.ps1:
Param(
[string]$Username,
[string]$Password,
[string]$OtherParam,
)
$Password = $Password | ConvertTo-SecureString -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$Password
Invoke-Command -ComputerName server.com -FilePath "C:\folder\CopyAndUnzip.ps1 -Something $OtherParam" -Credential $Cred
Then call it like so:
<Exec Command="powershell.exe -command "C:\folder\script.ps1 -username user10 -password P#55w0rd -OtherParam Whatever" Condition="'$(RunTests)' == 'True'"/>
You could try to pipe the commands to powershell.exe like this:
'$Username = "us"; $Password = "password"; $pass = ConvertTo-SecureString -AsPlainText $Password -Force; $Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass; Invoke-Command -ComputerName server.com -scriptblock {pathCopyAndUnzip.ps1} -Credential $Cred' | powershell.exe -command -
<Exec Command="$(PsExecPath) -accepteula \\$(Server) cmd /C powershell -File FILEPATH " Condition="'$(RunTests)' == 'True'"/>
I used old good psExec :) Everything is work now.

How to return a variable from a remote PowerShell session to a local PowerShell session

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.

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