I have a powershell script. Executing this will create a session with remote computer and execute some scriptblock inside remote computer. After that execution I need to send a mail.
So, I get the arguments required (like from, to, subject, body, smtp server, credentials) etc locally as shown below:
$param = #{
SmtpServer = 'SMTPServer'
Port = 587
UseSsl = $true
Credential = $crede
From = 'server#domain.in'
To = 'userv#domain.in'
Subject = 'Hi'
Body = "Hello"
}
$crede has value (username explicitly given, password reading from a text file).
And I call that param as shown below:
Send-MailMessage $using:param
This is inside an Invoke-Command.
But when I run this program it asks me for the mail message details like from, to, smtp server etc.. Please note that these values are given on $param locally. I guess $param values are not being passed to the remote session.
Can someone please support me. Any help would be really appreciated.
I just had a similar issue.
$processName = myProcess.exe
$session = New-PSSession -ComputerName $anycomputer -Credential $credentials
# powershell syntax requires -Scriptblock and { on this line
Invoke-Command -Session $session -ScriptBlock {
param([string] $processName)
Get-Process -Name $processName
} -Args $processName
Remove-PSSession $session
$processName = myProcess.exe
$session = New-PSSession -ComputerName $anycomputer -Credential $credentials
Invoke-Command -Session $session {Get-Process -Name $using:processName}
Related
Good day all,
I am running a line of code to download agent logs from multiple servers remotely but I am running into a delay with the current line of code I am working with.
copy-item -path C:\Agent.txt -destination c:\Local\ -fromSession (new-PSSession SERVERNAME -credential DOMAIN\USERNAME -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck))
This will prompt for credentials with the DOMAIN\USERNAME already filled in. What I am hoping to do is for it to begin the download immediately without me having to type in a password for each one.
TIA
This is an ideal place to use variables. You are being prompted each time because you instructed it to do so. If you break it up and store the credentials in a variable, then you won't keep getting prompted.
$session = new-PSSession SERVERNAME -credential DOMAIN\USERNAME -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck)
copy-item -path C:\Agent.txt -destination c:\Local\ -fromSession $session
You may also consider splatting to make the code easier to read and maintain. This may not be the best demonstration, however I thought it was worth mentioning.
$sessopt = #{
ComputerName = 'SERVERNAME'
Credential = 'DOMAIN\USERNAME'
UseSSL = $true
SessionOption = New-PSSessionOption -SkipCACheck
}
$session = New-PSSession #sessopt
$copyopt = #{
Path = 'C:\Agent.txt'
Destination = 'C:\Local\'
FromSession = $session
}
Copy-Item #copyopt
I'd like to collect and process some data from Exchange on remote server using powershell script. Script will be executed on host A, it will create session to host B, inside this session it will create another session - to exchange endpoint.
I'm doing it this way for security reasons, Exchange session needs to be created locally. The issue is that my first session doesn't have exchange data types, type of my $data object
is PSObject, but it should be MailboxDatabase. Is there a way to somehow import data types needed?
$sessWsman = GetOrCreateSession $ip $login $uri $password $configurationName $retryConnectUsingFdqn $uriTemplate $macroMissingWindowsCredentials $macroUnableConnect $macroSessionsDepleted $macroSessionClosed $null
Invoke-Command -Session $sessWsman -Args #("ENG-AUS-SAM-11") -ScriptBlock {
$sessExchange = GetOrCreateSession $ip $login $uri $password $configurationName $retryConnectUsingFdqn $uriTemplate $macroMissingWindowsCredentials $macroUnableConnect $macroSessionsDepleted $macroSessionClosed $sessWsman
if ( -Not ([bool](Get-Command -Name 'Get-MailboxDatabase' -ErrorAction SilentlyContinue)))
{
Import-PSSession $sessExchange -FormatTypeName * -CommandName Get-MailboxDatabase | Out-null
}
$data = Get-MailboxDatabase -Server $HostName -Status
$data.GetType()
}
I tried adding this Add-PSSnapin Microsoft.Exchange* after importing Get-MailboxDatabase, but it didn't helped.
I am trying to create a script that will take input (hardcoded values for now) and call an install PS script and run it on multiple servers. I am using a PSSession and Invoke-Command(see below). The below runs, but does nothing. It doesn't seem to call the other script. Beyond getting it to actually install, I need to know if it was successful or not. I'm pretty novice at Powershell, so any hints/help/suggestions would be great. The below is wrapped in a ForEach to loop the servers with $Computer
Try
{
$session = New-PSSession -ComputerName App02 -Credential $cred
$sourceInstall = $sourceFolder + 'Install\Install.ps1'
Invoke-Command -Session $session -ScriptBlock{param($serviceName, $installFolder, $sourceFolder, $Action, $username, $password) $sourceInstall} -ArgumentList ($ServiceName, $installFolder, $sourceFolder, $Action, $username, $password)
}
Catch
{
$Filename = "Error.txt"
Write-Output "ERROR: Partial Service Deployment. See error log file(s)"
Add-Content $Filename $_.Exception.Message
}
Get-PSSession | Remove-PSSession
You can use it without $Using statement in any version of PowerShell.But pass that too as an argument.
Eg:-
Invoke-Command -ScriptBlock
param($Name)
& $Command $Name
} -ArgumentList 'Get-Process','Notepad'
But you have to pass the arguments positional when using the call operator '&'
Get-Help About_Parameters
https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_parameters
Regards,
Kvprasoon
I have to machines in same network one with windows7 and another win windows server 2012.I tried Enter-PSsession on windows7 machine from server2012 machine...
$ComputerName = "windows7-PC"
$username="administrator"
$password="password"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cr = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$Session = New-PSSession -ComputerName $ComputerName -Credential $cr
Invoke-Command -Session $Session -ScriptBlock { echo '1' }
On doing same,i got an error
New-PSSession : [windows7-PC] Connecting to remote server windows7-PC failed with the following error message : Access is denied.
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
using same script i m able to execute 'echo 1' from windows7-pc to server2012-pc but not from server2012-pc to windows7-pc.
You need to add the remote server in trusted domain.
Please follow below article:
https://technet.microsoft.com/en-us/magazine/ff700227.aspx
This will surely help you.
I'm trying to send this:
Get-WmiObject Win32_PNPEntity |Where{$_.DeviceID.StartsWith("PCI\VEN_10DE") -or $_.DeviceID.StartsWith("PCI\VEN_1002")}
over rdesktop like:
rdesktop -a8 209.** -u ** -p ** -s "cmd.exe /K powershell.exe Get-WmiObject Win32_PNPEntity |Where{\$_.DeviceID.StartsWith("PCI\VEN_10DE") -or $_.DeviceID.StartsWith("PCI\VEN_1002")}"
But windows' shell says:
'Where{$_.DeviceID.StartsWith' is not recognized as an internal or externa....
What am I doing wrong?
why not using powershell wmi remoting?
$cred = get-credential
Get-WmiObject Win32_PNPEntity -computerName MyRemoteComputerName - credential $cred |Where{$_.DeviceID.StartsWith("PCI\VEN_10DE") -or $_.DeviceID.StartsWith("PCI\VEN_1002")}
-credential are only needed if the actual user running powershell isn't administrator of remote machine.
Hi I needed to do some thing like this once so i wrote some code that can send any ps code to a remote computes and display the results in the ps window on your pc.
Just remember to enable powershell remoting on both pc's.
function remote-pscode ($ServerName,$UserName,$password,$PSCode)
{
$global:RemoteCode = $args[0]
Write-Host $RemoteCode
$conprops = (Get-Host).UI.RawUI
$buffsize = $conprops.BufferSize
$buffsize.Height = 800
$conprops.BufferSize= $buffsize
# Set the user name you would like to use for the connection
$global:RemoteUserName = $UserName
$global:RemoteServerName = $ServerName
# Set the password you would like to use for the connection
# Check to see if you have a file on you drive c:\cred.txt with a password to use in it,if you don't it will create one
# for you and ask you for the password you would like to use
$global:RemotePassword = convertto-securestring $password -AsPlainText -Force
$global:credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $RemoteUserName,$RemotePassword
#Create a connection to the remote computer , put a list of IPAddresses or Computer Names.
$global:session = new-PSSession -ComputerName $RemoteServerName -Credential $credentials
$ScriptBlock = $executioncontext.invokecommand.NewScriptBlock($RemoteCode)
invoke-command -Session $session -ScriptBlock $ScriptBlock
#Close the sessions that where created
$global:closesession = Get-PSSession
Remove-PSSession -Session $closesession
}
remote-pscode -ServerName "NameOfRemotePC" -UserName "UserName" -password "password" -PSCode "any powershell code you want to send to the remote pc"
Several things here: put your PS commands in a script block (or a script). Also, why don't you simply use wmic.exe ?