Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Powershell scripting

Posted on 2013-01-02
18
Medium Priority
?
2,137 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
ID: 38736864
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
ID: 38736881
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
ID: 38736888
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
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

 
LVL 71

Expert Comment

by:Qlemo
ID: 38737335
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
ID: 38739354
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
ID: 38739374
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
ID: 38743939
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 71

Expert Comment

by:Qlemo
ID: 38744384
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
ID: 38755204
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
 
LVL 71

Expert Comment

by:Qlemo
ID: 38755312
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
ID: 38786407
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 71

Expert Comment

by:Qlemo
ID: 38805526
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
ID: 38818708
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 71

Expert Comment

by:Qlemo
ID: 38819266
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
ID: 38826304
Qlemo, despite doing this, the errors still remain? Any other thoughts?

thanks
0
 
LVL 71

Accepted Solution

by:
Qlemo earned 2000 total points
ID: 38826510
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
ID: 38831537
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 71

Expert Comment

by:Qlemo
ID: 38831850
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

Lessons on Wi-Fi & Recommendations on KRACK

Simplicity and security can be a difficult  balance for any business to tackle. Join us on December 6th for a look at your company's biggest security gap. We will also address the most recent attack, "KRACK" and provide recommendations on how to secure your Wi-Fi network today!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The following article is intended as a guide to using PowerShell as a more versatile and reliable form of application detection in SCCM.
With User Account Control (UAC) enabled in Windows 7, one needs to open an elevated Command Prompt in order to run scripts under administrative privileges. Although the elevated Command Prompt accomplishes the task, the question How to run as script…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Loops Section Overview

886 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