We help IT Professionals succeed at work.

replace a string on a text file on a remote computer

replace a string on a text file on a remote computer

Currently, I have to type in \\RemotecomputerName\c$ I will be prompted to type  in RemotecomputerName\administrator  and password.
then open a text file (it has extension of CMD). the file has few lines on it , but the string  I want to replace is called username and comes after -username (notice the dash before username).

example:
aaaaaa bbbbbbbb ccccccccc dddddddddd -username username
then Save the file.

I need this operation to be done by a script

Thank you
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
NVITEnd-user support

Commented:
Does this help?
set origstr=aaaaaa bbbbbbbb ccccccccc dddddddddd -username olduser
set rmvstr=%origstr:*-username=%
call set rslt=%origstr:%rmvstr%=%
echo %rslt% newuser

Open in new window

Author

Commented:
Can you explain you script please. ?

I have a list of computers. for instance Excel spreadsheet or text file:

computername      newusername
Comp1                  UserA
Comp2                  UserB
...
...

Open in new window


the script should access comp1  , It s access this way:  comp1\administrator then type in Password
then on text file name Mytext.com  there is a line that literally contains -username username
as you can notice the first username has dash.
the script should replace the second username with UserA
then it closes the text file and save it

it will jump to second computer Comp2 and do the same thing..
Most Valuable Expert 2012
Distinguished Expert 2018

Commented:
Should be pretty easy in Powershell.

Replacing text in a file is straight forward:
https://mcpmag.com/articles/2018/08/08/replace-text-with-powershell.aspx

I don't have a network where I can test anything on remote computers but scripts seem to exist:
https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Replace-String-58fbfa85
NVITEnd-user support

Commented:
@jskfan... My solution would be a CMD script. I see you've changed your topic tags. I thought it originally included Windows Batch/Script. Now, it just shows VB Script.

If you would still like a CMD solution, let me know. Otherwise, please wait for someone to come in with a VB Script solution.
Most Valuable Expert 2012
Distinguished Expert 2018

Commented:
I see Batch is still there:
Untitled.jpg
NVITEnd-user support

Commented:
@slightwv... Thanks for that. I was looking on my Android mobile, which shows just VB Script. On desktop its fine. Weird.
Most Valuable Expert 2012
Distinguished Expert 2018

Commented:
Don't use Mobile but see if there is a "+" looking icon next to VB Script to expand the topics.
NVITEnd-user support

Commented:
No + icon next to VB Script on my android. Shucks! Thanks again.

Author

Commented:
NVIT

Any Script that bring a solutions is welcomed
Most Valuable Expert 2012
Distinguished Expert 2018

Commented:
Personally, I would stay away from old BAT scripting.  IMO, it should have gone away in the 90's early 00's.  Much better options out there these days that are much easier to work with.

Did you look at the Powershell link I posted?
NVITEnd-user support

Commented:
@jsk... Please clarify your objective and steps. It's not clear.

Your original question says: but the string  I want to replace is called username and comes after -username (notice the dash before username).
aaaaaa bbbbbbbb ccccccccc dddddddddd -username username

Your next post makes things more confusing. Sorry, it's probably just me but I'm having trouble getting the overall goal and steps you need.

Need clarification, please
Most Valuable Expert 2012
Distinguished Expert 2018

Commented:
>>Need clarification, please

Seems straight forward to me.

Parse a file getting the computer name and new password:
Get Comp1 then open a file looking for "some string -username xxx" then replace "xxx" with  "UserA"
next line in file, go to Comp2  replace string after -username "www" with "UserB"
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Some PowerShell should do it; expects a csv with columns ComputerName and NewUsername
## Local file path on the clients:
$filePath = 'C:\Temp\foo.cmd'
$csv = '.\replace.csv'
$credential = Get-Credential -Message 'Logon for the client administrator' -Username Administrator

$directory = [IO.Path]::GetDirectoryName($filePath).Replace(':', '$')
$file = [IO.Path]::GetFileName($filePath)
$pattern = '(-username\s+)\S+'
Import-Csv -Path $csv | ForEach-Object {
	$computer = $_.ComputerName
	$newUser = $_.NewUsername
	Write-Host "Processing $($computer) ..." -NoNewline
	Try {
		$clientDrive = $null
		$clientDrive = New-PSDrive -Name Client -PSProvider FileSystem -Root "\\$($computer)\$($directory)" -Credential $credential -ErrorAction Stop
		$content = Get-Content -Path "Client:\$($file)" -ErrorAction Stop
		$content -replace $pattern, "`$1$($newUser)" | Set-Content -Path "Client:\$($file)" -Force -ErrorAction Stop
		Write-Host " OK" -ForegroundColor Green
	} Catch {
		Write-Host " FAILED: $($_.Exception.Message)" -ForegroundColor Red
	} Finally {
		If ($clientDrive) {
			$clientDrive | Remove-PSDrive -Force
		}
	}
}

Open in new window

Author

Commented:
oBdA


can you please explain (by commenting the lines of the script), before I test it ?

Thank you.

By the way this Powershell command worked, but just on one local computer:
 ((Get-Content -path C:\ReplaceDemo.txt -Raw) -replace 'brown','white') | Set-Content -Path C:\ReplaceDemo.txt
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
PowerShell is usually pretty self-explanatory, so what exactly is unclear?
The script reads a csv with computernames and new usernames, creates a network drive to the remote computer using the credentials you entered, reads the text file, replaces the string found, writes the text file, and removes the network drive again.
The RegEx pattern (-username\s+)\S+ matches a literal "-username", followed by any number of whitespaces (\s+), followed by any number of non-whitespace (\S+) (the actual username to replace).
$content -replace $pattern, "`$1$($newUser)"
The literal -username and its following spaces will be in match group 1, and be put back in -replace with the $1 ($x a special token in a RegEx that refers to matching group x.

Author

Commented:
I will come back to this topic later..

Thank you Guys!!