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.
Related
I am trying to import Exchange Server session into runspace.addscript({
it is something like below
$PowerShell = [powershell]::Create()
$PowerShell.RunspacePool = $RunspacePool
#$PowerShell.AddCommand({New-PSSession});
#$PowerShell.AddParameter("ConfigurationName", "Microsoft.Exchange");
#$PowerShell.AddParameter("ConnectionUri","http://win2012-2/PowerShell/");
#$PowerShell.AddParameter("Credential", $ExchangeCredential);
#$PowerShell.AddParameter("Authentication", "Kerberos");
$PowerShell.AddScript({
param($FileName,$FilePath,$i_f)
[console]::WriteLine("script")
$User = "localdomain\administrator"
$Pass = "********"
$ExchangeCredential = New-Object -typename System.Management.Automation.PSCredential -argumentlist $User, $Pass
$ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://win2012-2/PowerShell/ -Authentication Kerberos -Credential $ExchangeCredential
$Session = Import-PSSession $ExchangeSession -AllowClobber
$state = $Session.SessionState
[console]::WriteLine($state) | FT
But i could not get session information from $Session object or $state object,
how can i import the exchange session to runspace script?
any help would be appreciated
Thank you
[console]::WriteLine("foo") does not work inside a runspace, so you don't see any input. You can get around this by passing your current console's details ($host) to your scriptblock
I know you commented them out, but any parameters you're adding should be defined in the param() of your script block
I only have exchange-online, but this should work pretty similarly for either
# example of getting cred once at start
$UserCredential = Get-Credential
# create the PS session and assign a runspace
$PowerShell = [powershell]::Create()
$PowerShell.Runspace = [runspacefactory]::CreateRunspace()
$PowerShell.Runspace.Open()
# First, the script block
$Scriptblock = {
param($cred,$console)
# use $cred defined as a parameter
$ExchSession = New-PSSession -Credential $cred -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Authentication Basic
Import-PSSession $ExchSession -DisableNameChecking -AllowClobber
# test session and output to console
$m = get-mailbox user#domain.com
$console.UI.WriteLine($m.name)
Remove-PSSession $ExchSession
}
# Then add the script block to your runspace
# add Arguments in order, or add named Parameters
$powershell.AddScript($Scriptblock) | out-null
$powershell.AddArgument($UserCredential) | out-null
$powershell.AddArgument($host) | out-null
# run
$invokeInfo = $PowerShell.BeginInvoke()
# wait for completion, check output...
$PowerShell.Runspace.Dispose()
$PowerShell.Dispose()
## To run the script
# .\get_status.ps1 -Hostname <host> -Service_Action <action> -Service_Name <name>
#$Hostname = "hostname"
#$Service_Action = "Get-Service"
#$Service_Name = "service_name"
param(
[string]$Hostname,
[string]$Service_Action,
[string]$Service_Name
)
$ScriptBlockContent = {
param($Service_Action, $Service_Name)
& $Service_Action $Service_Name
}
# user credentials
$Username = "username"
$Password = "password"
# To avoid Manual entry of Username and Password
$Secure_String = convertto-securestring $Password -asplaintext -force
$User_cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username, $Secure_String
# Create a Session
$pso = New-PSSessionOption -NoMachineProfile
$sess = New-PSSession -ComputerName $Hostname -SessionOption $pso -credential $User_cred
#Run a powershell script in the session.
Invoke-Command -Session $sess -ScriptBlock $ScriptBlockContent -ArgumentList $Service_Action, $Service_Name
# Remove session
Remove-PSSession $sess
To run the script:
.\<script_name>.ps1 -Hostname <host> -Service_Action <action> -Service_Name <name>
For ex: Service Action is- Get-Service, Stop-Service, Start-Service
and then Name
Command: Get-Service Servicename
I am getting an error:
Unexpected token in expression or statement on this line of code:
$ScriptBlockContent = {
param($Service_Action, $Service_Name)
$Service_Action $Service_Name # here is the error
}
You are passing your commands as strings to your function, so what you are syntactically doing with $Service_Action $Service_Name is to refer to two string objects in one line without any operator connecting them. That is the reason for the exception.
To tell powershell, that you want to execute a string as a command you have several options:
One option is to pass the commands as a single string to the Invoke-Expressioncmdlet:
Invoke-Expression "$Service_Action $Service_Name"
Alternatively you can use the call-Operator &, which also tells powershell to treat a command as string. In this case you cannot give cmdlet and arguments in a single string, but in two:
& $Service_Action $Service_Name
## To run the script
# .\get_status.ps1 -Hostname <host> -Service_Action <action> -Service_Name <name>
#$Hostname = "hostname"
#$Service_Action = "Get-Service"
#$Service_Name = "service_name"
param(
[string]$Hostname,
[string]$Service_Action,
[string]$Service_Name
)
$ScriptBlockContent = {
param($Service_Action, $Service_Name)
& $Service_Action $Service_Name
}
# user credentials
$Username = "username"
$Password = "password"
# To avoid Manual entry of Username and Password
$Secure_String = convertto-securestring $Password -asplaintext -force
$User_cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username, $Secure_String
# Create a Session
$pso = New-PSSessionOption -NoMachineProfile
$sess = New-PSSession -ComputerName $Hostname -SessionOption $pso -credential $User_cred
#Run a powershell script in the session.
Invoke-Command -Session $sess -ScriptBlock $ScriptBlockContent -ArgumentList $Service_Action, $Service_Name
# Remove session
Remove-PSSession $sess`enter code here`
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}
I have a script that copies another script to a remote server then executes the 2nd script. This was working ok last week but today execution of the first script failed saying the 2nd script couldn't be found. As part of troubleshooting I created a simple version of the 2nd script (containing only Write-Host "Wrong Server!) on the local server. Now when I run the 1st script, the dummy 2nd script is executed on the local server!
I have pasted by test-harness script below:
$DeploymentFolderOnTargetServer = "c:\biztalkdeployment"
$TargetServer = "d-vasbiz01"
$Username = "TFS_Service"
$Password = "x"
$SecPass = ConvertTo-SecureString $Password -AsPlainText -Force
$Cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $Username,$SecPass
$Session = New-PSSession -ComputerName $TargetServer -Authentication CredSSP -Credential $Cred
$Environment = "Dev"
$ExecuteScriptFilePath = join-path "$DeploymentFolderOnTargetServer" "ExecuteBizTalkAppMSI.ps1"
$MSI = "bin\debug\x.int.mis-3.0.0.msi"
$InstallFolderOnTargetServer = "C:\Program Files (x86)\x.Int.MIS for BizTalk 2010\3.0"
Write-Host "Session = $Session"
Write-Host "ExecuteScriptFilePath = $ExecuteScriptFilePath"
Write-Host "MSI = $MSI"
Write-Host "InstallFolderOnTargetServer = $InstallFolderOnTargetServer"
Write-Host "Environment = $Environment"
Write-Host "DeploymentFolderOnTargetServer = $DeploymentFolderOnTargetServer"
Invoke-Command -Session $Session -FilePath $ExecuteScriptFilePath -argumentlist $MSI, $InstallFolderOnTargetServer, $Environment, $DeploymentFolderOnTargetServer
The output from the test is as follows:
Session = System.Management.Automation.Runspaces.PSSession
ExecuteScriptFilePath = c:\biztalkdeployment\ExecuteBizTalkAppMSI.ps1
MSI = bin\debug\x.int.mis-3.0.0.msi
InstallFolderOnTargetServer = C:\Program Files (x86)\Vasanta.Int.MIS for BizTalk 2010\3.0
Environment = Dev
DeploymentFolderOnTargetServer = c:\biztalkdeployment
Wrong Server!
If I run get-session then the Computer Name for the session is correctly pointing at the 2nd Server.
Any ideas?
The -FilePath parameter to Invoke-Command is specifying a local path to a script - not a path on the target computer. Invoke-Command will take care of getting the local script file over to the target computer so that it can execute there.
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 ?