Solved

Powershell scripting

Posted on 2013-01-02
18
1,937 Views
Last Modified: 2013-03-19
All, I am in the middle of configuring a powershell script that is able to run a BAT file that is stored on a remote server. This script will be ran from our NMS and will run the BAT file remotely (ideally anyway). However, to where our NMS and remote server lie, are across 2 domains and wondered if anyone of a way I can run the powershell script under a different domain credentials?

here is a copy of the scripts that works:

$RemoteServerName = "\\xxx.xxx.xxx.xxx"
$Process = [WMICLASS]"$RemoteServerName\ROOT\CIMV2:win32_process"
$result = $process.create("D:/xxxx/xxx.bat")

surely there must a switch that can be included that can run this task as another remote user?

thanks
0
Comment
Question by:ccfcfc
  • 7
  • 7
  • 2
  • +1
18 Comments
 
LVL 37

Expert Comment

by:Neil Russell
Comment Utility
I use the simple method of....

NET USE \\remotecomputername.domain\IPC$ $password /U:$username
copy .\script.bat \\remotecomputername\c$\temp -force
psexec.exe \\$remotecomputername -p Password -u username -file C:\Temp\script.bat

Open in new window


The drawback is that psexec uses plain text to transmit passwords.
0
 
LVL 37

Expert Comment

by:Neil Russell
Comment Utility
Or ofcourse use proper remote powershell.  See tutorial here to get you started.
http://www.computerperformance.co.uk/powershell/powershell_remote.htm
0
 
LVL 18

Expert Comment

by:irweazelwallis
Comment Utility
if you run the batch file which executes the powershell as a scheduled task then you can put the credentials in there

or here is the powershell way

http://blogs.technet.com/b/robcost/archive/2008/05/01/powershell-tip-storing-and-using-password-credentials.aspx
0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
Any special reason for using PS just to start a batch file? My approach would be the psexec as shown above, or PS Remoting (staying inside of PS all the time), but not mix the methods here.
0
 

Author Comment

by:ccfcfc
Comment Utility
Originally due to our NMS software is only able to run a PSscript, VBscript or Java scripts. I was informed from co workers that powershell would probably be the best option to work from.

Also, this bat file must run on the remote server and run in a logged in session as the BAT file it runs requires to stay open in order to work.

thanks
0
 
LVL 18

Expert Comment

by:irweazelwallis
Comment Utility
in that case use the link i posted from technet to embed the credentials in there. Its really easy if you don't mind the credentials being left in plain text
0
 

Author Comment

by:ccfcfc
Comment Utility
Neilsr, thank you for your post.

I have taken a look at your linked articles and have added all the servers involved into the trust lists, however, when creating the a 'PSSession' i am getting this error:

192.168.50.242] Connecting to remote server failed with the following error message : The WinRM client cannot process
the request. Default authentication may be used with an IP address under the following conditions: the transport is HTT
PS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use winrm.cmd to configure Tr
ustedHosts. Note that computers in the TrustedHosts list might not be authenticated. For more information on how to set
 TrustedHosts run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting
Help topic.
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportExc
   eption

Have you seen this error before? Im preety certain that due to the server being across 2 different domains, I need to stick in a credential switch, but unsure how. This is the command I used:

new-pssession <Ipaddress>

irweazelwallis, thanks for your posts also, I am reading that one also.

Kind regards
0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
New-PSSession/Invoke-Command with an IP address, or with a target in a different domain, will need more. By default, Kerberos is used to authenticate, but that only works within the same domain and with machine names.

Also note that you have to restart WinRM after setting TrustedHosts. You only need to set the target host here. The two ways to do that are
winrm set winrm/config/client @{TrustedHosts="RemotePC1, RemotePC2"}

Open in new window

or
cd WSMan:\localhost\Client
set-Item trustedhosts "RemotePC1, RemotePC2" –force

Open in new window

and then
restart-Service winRM

Open in new window

For invoking a remote command with explicit credentials you should use
$cred = New-Object system.management.automation.pscredential("RemoteUser", (ConvertTo-SecureString "RemotePwd" -AsPlainText –force))
invoke-command RemotePC1 {dir c:\} –authenticate negotiate –credential $cred

Open in new window

where dir c:\ is an example command.
0
 

Author Comment

by:ccfcfc
Comment Utility
Qlemo,

thanks for your response.

I have adjusted my script to the following:

'$cred = new-object system.management.automation.pscredential("*******", (ConvertTo-SecureString "***********" -AsPlainText -force)) invoke-command "\\192.168.51.242" {dir C:\}
invoke-command "\\192.168.51.242" {dir c:\} –authenticate negotiate –credential $cred
$RemoteServerName = "\\192.168.51.242"
$Process = [WMICLASS]"$RemoteServerName\ROOT\CIMV2:win32_process"
$result = $process.create("D:/Red5/red5.bat")'

When i run this script, a dialogue box appears seeking credentials. I key in the credentials and receive this error:

New-Object : A positional parameter cannot be found that accepts argument 'invoke-command'.
At C:\Scripts\ldc_fms_01.ps1:1 char:19
+ $cred = new-object <<<<  system.management.automation.pscredential("*********", (ConvertTo-SecureString "*******************" -AsPlainText -force)) invoke-command "\\192.168.51.242" {dir C:\
}
    + CategoryInfo          : InvalidArgument: (:) [New-Object], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
 
Invoke-Command : A parameter cannot be found that matches parameter name 'authenticate'.
At C:\Scripts\ldc_fms_01.ps1:2 char:58
+ invoke-command "\\192.168.51.242" {dir c:\} –authenticate <<<<  negotiate –credential $cred
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
 
Cannot convert value "\\192.168.51.242\ROOT\CIMV2:win32_process" to type "System.Management.ManagementClass". Error: "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
At C:\Scripts\ldc_fms_01.ps1:4 char:22
+ $Process = [WMICLASS] <<<< "$RemoteServerName\ROOT\CIMV2:win32_process"
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException
 
You cannot call a method on a null-valued expression.
At C:\Scripts\ldc_fms_01.ps1:5 char:26
+ $result = $process.create <<<< ("D:/Red5/red5.bat")
    + CategoryInfo          : InvalidOperation: (create:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Do you know what is causing this to error. Please bare in mind I am new to powershell and not a Guru when it come to this area.

Thanks in advance.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
You seem to have made some mistakes when pasting all together. However, the second line contained a typo anyway. Your code should look like:
$RemoteServerName = "\\192.168.51.242"
$cred = new-object system.management.automation.pscredential("*******", (ConvertTo-SecureString "***********" -AsPlainText -force))
$result = invoke-command $RemoteServerName {cmd /c D:\Red5\red5.bat} –Authentication negotiate –Credential $cred 

Open in new window

0
 

Author Comment

by:ccfcfc
Comment Utility
Hi Qlemo,

Thank you for your response. Taking a look at your script, I have adapted your suggested script to our systems but seem to be getting errors in return:

'[ldc-fms-01] Connecting to remote server failed with the following error message : The WinRM client cannot process the request. If the authentication scheme is different from Kerberos, or if th
e client computer is not joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts configuration setting. Use winrm.cmd to configure Tru
stedHosts. Note that computers in the TrustedHosts list might not be authenticated. You can get more information about that by running the following command: winrm help config. For more informa
tion, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (:) [], PSRemotingTransportException
    + FullyQualifiedErrorId : PSSessionStateBroken'

Also, here is the scripts that I have made and used to receive this error:

'$RemoteServerName = 'servername'
$cred = new-object system.management.automation.pscredential("domain\username", (ConvertTo-SecureString "*****************" -AsPlainText -force))
$result = invoke-command $RemoteServerName {cmd /c D:\Red5\red5.bat} –Authentication negotiate –Credential $cred '

please note that these 2 servers are on 2 different domains that are linked together via VPN.

thanks
0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
That error message is only sent when TrustedHosts is not correct. Please make sure you execute
set RemoteServerName='ldc-fms-01'
set-Item WSMan:\localhost\Client\trustedhosts $RemoteServerName –force
$cred = new-object system.management.automation.pscredential("*******", (ConvertTo-SecureString "***********" -AsPlainText -force))
$result = invoke-command $RemoteServerName {cmd /c D:\Red5\red5.bat} –Authentication negotiate –Credential $cred 

Open in new window

0
 

Author Comment

by:ccfcfc
Comment Utility
Qlemo, Thank you for your reply.

I have tried the script you had suggested, and seem to be getting more errors.

here is the script I tried:

'set RemoteServerName= 'ldc-man-02'
set-Item WSMan:\localhost\Client\trustedhosts $RemoteServerName –force
$cred = new-object system.management.automation.pscredential (domain\username", (ConvertTo-SecureString "***password***" -AsPlainText -force))
$result = invoke-command $RemoteServerName {cmd /c C:\scripts\test.bat} –Authentication negotiate –Credential $cred '

Here is the error that I am getting:

'The string starting:
At C:\Scripts\ldc_fms_01.ps1:3 char:120
+ $cred = new-object system.management.automation.pscredential (domain\username", (ConvertTo-SecureString "xxxxxxxxxxxxxxxx <<<< " -AsPlainText -force))
is missing the terminator: ".
At C:\Scripts\ldc_fms_01.ps1:4 char:118
+ $result = invoke-command $RemoteServerName {cmd /c C:\scripts\test.bat} –Authentication negotiate –Credential $cred   <<<<
    + CategoryInfo          : ParserError: ( -AsPlainText -...dential $cred  :String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString'

Does any of this make sense to you?

thanks

EDIT:  ModeIT  2-2-13 (removed sensitive info)
0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
You have omitted the leading double quote for domain\username. You need to enclose it in double or single quotes.
0
 

Author Comment

by:ccfcfc
Comment Utility
Qlemo, despite doing this, the errors still remain? Any other thoughts?

thanks
0
 
LVL 68

Accepted Solution

by:
Qlemo earned 500 total points
Comment Utility
Exactly the same error ("... is missing the the terminator")? Try
set RemoteServerName= 'ldc-man-02'
set-Item WSMan:\localhost\Client\trustedhosts $RemoteServerName –force
$cred = new-object system.management.automation.pscredential ('domain\username', (ConvertTo-SecureString '***password***' -AsPlainText -force))
$result = invoke-command $RemoteServerName {cmd /c C:\scripts\test.bat} –Authentication negotiate –Credential $cred 

Open in new window

0
 

Author Comment

by:ccfcfc
Comment Utility
Qlemo, I ran the proposed script but am still getting errors when attempting to run the scripts:

S C:\Scripts> C:\Scripts\ldc_fms_01.ps1
Set-Item : This command cannot be used because Parameter Value is not supplied. Check the value again and run your command.
At C:\Scripts\ldc_fms_01.ps1:2 char:9
+ set-Item <<<<  WSMan:\localhost\Client\trustedhosts $RemoteServerName –force
    + CategoryInfo          : NotSpecified: (:) [Set-Item], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.SetItemCommand
 
Invoke-Command : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.
At C:\Scripts\ldc_fms_01.ps1:4 char:25
+ $result = invoke-command <<<<  $RemoteServerName {cmd /c C:\scripts\test.bat} –Authentication negotiate –Credential $cred  
    + CategoryInfo          : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand

Thanks
0
 
LVL 68

Expert Comment

by:Qlemo
Comment Utility
Sorry, small typo in the first line:
set $RemoteServerName= 'ldc-man-02'
set-Item WSMan:\localhost\Client\trustedhosts $RemoteServerName –force
$cred = new-object system.management.automation.pscredential ('domain\username', (ConvertTo-SecureString '***password***' -AsPlainText -force))
$result = invoke-command $RemoteServerName {cmd /c C:\scripts\test.bat} –Authentication negotiate –Credential $cred 

Open in new window

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Utilizing an array to gracefully append to a list of EmailAddresses
I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now