Powershell RDP Session and CLI Script - loops

What I am looking to do seems fairly simple but I cant figure it out. I am looking to run a Powershell script to launch an RDP session, copy a file to the c:\ directory, then run that file from a command line. I would like it to loop, getting the paramaters froma csv file, such as server IP, username, and password. So in essence the steps would be as follows...
import infor from the csv file to define variables
copy specefied file
(then loop)
launch mstsc.exe
enter server IP, username, password
paste copied file into the c:\ directory
launch cmd.exe
Run the file that was copied to the c:\ directory
log off server
I wanted to see if someone could help me out with this.I am new to power shell and have been able to work through a lot of it. If someone could point me in the right direction, or even provide me the code to fill in the blanks, I would greatly appreaciate it.

I have done remote installs using psexec. psexec \\servername -u domain\usernamr -p password cmd /c "msiexec /i program.msi
PSexec download: https://learn.microsoft.com/en-us/sysinternals/downloads/psexec
This means instead of RDP you will use psexec to run the install remotely.
I have created a small PowerShell script to get you started. So let's assume your CSV file (c:\info.csv) has three columns ServerName, UserName, Password.
Run the below code, and it should work but make sure the change the first 4 lines as per your environment. Start by putting one server to observe the script behavior.
# Set intial variables
$CSVFile = "c:\info.csv"
$MSI = "\\servername\sharename\setup.msi"
$MSILog = "c:\Windows\temp\setup.log"
$Domain = "YourDomain"
# Import info from CSV file
$Servers = import-csv $CSVFile
# loop through each server
foreach ($server in $servers) {
# run psexec on each server to install a program
psexec \\$server.servername -u $Domain\$server.username -p $server.password -h cmd /c "msiexec /i $MSI /quite /l*v $MSILog"
}

I recommend you using this command because I don't exactly what you are trying to do.
Get-help Import-CSV
Get-help about_remoting this will avoid doing the mstsc.exe thing for you.
Enter into the session and Invoke-Command against this session and you can run commands on that server.
$session = New-PSSession -ComputerName Server1 -Credentials Get-Credential
Invoke-Command -Session $session -ScriptBlock {
}
Inside the Script block specify you powershell command to copy files and run them.

Related

Run bat file as admin remotely in cmd prompt for user on network

I've tried uses psexec but all it does is start the process in the background and gives it an ID but doesn't actually do anything.
Attempts:
psexec \\pc -h -u org\user -p pass -d -i cmd copy "first_location" "<into_this_locat>"
psexec \\pc -h -u org\user -p pass command copy "first_location" "<into_this_locat>"
It's important that I run this command as an admin otherwise it won't work.
Maybe I can run a .bat file after connecting to their computer as admin?
A sustainable way to do this without the need for additional programs to be installed is by using PowerShell. If you are on a supported Windows system, PowerShell will be available.
If you must run from a cmd.exe shell, the following can be used.
powershell -NoLogo -NoProfile -Command ^
"Invoke-Command -ComputerName 'SERVER01' -ScriptBlock {Copy-Item -Path "$Env:USERPROFILE\y.y" -Destination "$Env:USERPROFILE\x.x"}"

TFS Run batch script on a remote server with admin permission

I currently have Server A which is where my TFS and Build Agent is located. I then have Server B which is when my source code site. I am trying to set up a build definition and copies file from on location in server B to another and then build the solution.
However when I run this batch file as part of a build definition it is not creating folders where it need to be. I believe due to the agent not having correct permissions.
Is there a way to run the following batch script to run with Admin permission from a build definition.
You can try below workarounds:
Convert the batch script to PowerShell script, then copy the
PowerShell script to target machine and use the PowerShell on Target
Machines task to run the script. You can enter your admin user
and password using the task. Reference below screenshot.
Add a PowerShell task and run below script to call the cmd.exe to
run the batch script with an admin user account on target machine
(Copy the batch script to target machine first, in below sample I
copied the batch script to C:\Scripts\Test.bat):
Param(
[string]$computerName = "v-tinmo-12r2",
)
$Username = "Domain\user"
$Password = ConvertTo-SecureString "password-here" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($Username,$password)
Invoke-Command -ComputerName $computerName -Credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'C:\Scripts\Test.bat'"}

Unable to invoke PSEXEC on remote machine using ActiveBatch

I am trying to execute a bat file on a remote computer using psexec through ActiveBatch and getting the rejection:
"Could not start PSEXESVC service on 'remote machine', Activity
'ShellCommand' failed, ApplicationException in step 'ShellCommand':
Process exited with '2250'".
To run access the remote .bat I am using a ShellCommand step with the following command:
psexec -u admincred -p pass -i 2 -d \remotecomputer cmd /c c:\msg.bat
I believe the path is correct since the bat file is on the c: drive and will execute if the psexec command is run through cmd on my machine. All the .bat does is call a message to another remote computer.
I believe the problem is getting psexec to run through the ActiveBatch ShellCommand on the remote machine.
I do not know anything about ActiveBatch. But, if you can specify a command line, could you use something like this and not need psexec.exe?
powershell -NoProfile -Command "Invoke-Command -ComputerName HOST001-ScriptBlock { & cmd.exe /C C:\Temp\msg.bat }"
A shortened form would be:
powershell -NoProfile "Invoke-Command HOST001 { & cmd.exe /C C:\Temp\msg.bat }"
If you must run the script as a different user, Invoke-Command has a -Credential parameter that can be used.

Powershell running as administrator refuses to redirect STDOUT to file

As an exercise, I am trying to make a web control panel for Hyper-V. It will use Powershell to interact with Hyper-V.
First thing I tried to do was to use the Get-VM command to create a table with the status of all the VM's on the local machine. I ran Get-VM from PHP:
$output = `powershell Get-VM`;
$output became NULL. After a lot of troubleshooting, I realized that Get-VM doesn't give output unless Powershell is running as an administrator (I was running the Powershell instance that I was testing with as administrator, but the one that was created by PHP was not run as administrator).
Then, I went to the powershell.exe file, right-clicked on it, went to Properties -> Compatibility -> Change settings for all users, and checked "Run as administrator". This should make it run as administrator no matter where it is started from, and it appears that it does exactly that in this case as well. However, once Powershell is running as an administrator, it does not output to a file, even if told to do so by the > operator.
If I run powershell Get-VM > out.txt, while powershell is running as an administrator, it creates the file out.txt, but it is 0kb and contains nothing. powershell Get-Process > out.txt has the same result, a 0kb file.
Running powershell Get-Process > out.txt with a non-elevated powershell.exe yields the expected result, namely the output from Get-Process in out.txt. However, you can't do this with powershell Get-VM > out.txt, since Get-VM returns no data unless powershell is run as administrator.
To wrap it up, my question is why does Powershell refuse to redirect its STDOUT to a file if it is running as administrator, but not if it is running as a normal user?
My diligent father has solved the problem, by not using redirection operators, but rather piping the output into Powershell's own out-file or export-csv, so that the command becomes powershell Get-VM | export-csv out.csv. I then parse this in PHP and convert it to a table. Works like a charm.

How to Acess Remote Computer Folders in PS SQLSERVER:\>

Recently I came to know how to use Powersehll commands for executing SQL queries as mentioned below:
Import-Module “sqlps” -DisableNameChecking
$ds=Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $server -ConnectionTimeout $ConnectionTimeout -QueryTimeout $QueryTimeout
At this time Powershell ISE output Console will be in
PS SQLSERVER:\>
I was able to perform Select and Update queries without any error. The problem is faced when I wanted to access one of the file in remote computer. I tried to access the file as below:
PS SQLSERVER:\> Get-Content -Path \\Server\D$\Log\App.log
Even tried, just to list files/folders as
PS SQLSERVER:\> ls \\Server\D$\Log\
Iam getting below errors:
Get-Content : Cannot find path '\Server\D$\Log\App.log' because it does not exist.
ls : Cannot find path '\Server\D$\Log\' because it does not exist.
Need not to say- folder and file exists on that server as I was able to access the same when Powershell is running without SQL module. I mean console was showing just
PS C:\User\abc\
Sorry for this long story-- now, simple question!
How to access remote files/folders when Shell is in SQLSERVER console?
Thanks in Advance!
-Raj
You should be able to use the filesystem provider explicitly like this:
ls filesystem::\\server\d$\log
Just change your directory like so:
cd c:\
then:
ls \\server\d$\log
you can then change back to sql server by doing the same:
cd sqlserver:\
The powershell providers can be used just like you would a normal drive letter, pretty cool.
I believe it's running the commands remotely on the SQL server, which makes accessing data on another server from there a "double hop" scenario, and you'll need CredSSP auth for that to work.....

Resources