简体   繁体   中英

How to replace a string in file on remote computer in Powershell?

I have a VM running Windows Server 2012.And some intended services on it. I want to change a configuration file on this VM machine remotely from my desktop pc. Currently I change this configuration file by mapping the C: drive of the remote server and then changing the file. Now this blocks me from changing multiple servers as I can't map multiple server c: simultaneously to same drive. Also, mapping hundreds of drives wouldn't be ideal. The way I am changing the file by mapping drive is:

$password = <password text> | ConvertTo-SecureString -asPlainText -Force
$username = "admin"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
net use Z: \\$ipAddress\C$ <password> /user:admin type 'z:\Program Files\lalaland\Data\Settings.xml'

(Get-Content 'z:\Program Files\lalaland\Data\Settings.xml') | ForEach-Object { $_ -replace $oldString, $newString } | Set-Content 'z:\Program Files\lalaland\Data\Settings.xml'
type 'z:\Program Files\lalaland\Data\Settings.xml'
net use z: /delete

Therefore I searched for a better option and found this script at https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Replace-String-58fbfa85 but it doesn't work for me.

I am using this script as :

.\Replace-StringInFile.ps1 -ComputerName  <RemoteComputerHostName> -TargetPath 'C:\Program Files\lalaland\Data' -Fil

eName Settings.xml -Replace $oldString -ReplaceWith $newString -Credential (Get-Credential)

when I run the command credential window pops up asking for username and password. I enter the username and password that I used for mapping the drive, but it throws the following error:

New-PSSession : [<RemoteHostName>] Connecting to remote server <RemoteHostName> failed with the following error message : The user name or password is incorrect. For more information, see the
about_Remote_Troubleshooting Help topic.
At D:\workspace\Replace-StringInFile.ps1:84 char:14
+ ...  $Session = New-PSSession -ComputerName $Computer -Credential $Creden ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : LogonFailure,PSSessionOpenFailed

what I don't understand is when I map the drive with the same credentials it works fine but using the other script, which internally uses New-PSSession doesn't work.

Any idea ?

I was able to do this using the following cmdlet:

function Edit-RemoteFileStringReplace
{
  [cmdletbinding()]
  param([Parameter(Mandatory=$true)][ValidateScript({$_ -match [IPAddress]$_ })][string]$Address,
        [Parameter(Mandatory=$true)][string]$FilePath,
        [Parameter(Mandatory=$true)][string]$Replace,
        [Parameter(Mandatory=$true)][string]$ReplaceWith,
        [Parameter(Mandatory=$true)][System.Management.Automation.PSCredential]$Credential
  )

  $DriveLetter=""
  $FilePathWithoutDriveLetter=""

  $DriveName = $Address.replace('.','x')
  $DriveName = "PSDrive_$DriveName"

  $DriveLetter = (Get-DriveLetterFromPath -Path $FilePath).Substring(0,1)
  $FilePathWithoutDriveLetter = Remove-DriveLetterFromPath -Path $FilePath
  $MappedFilePath="$DriveName" + ":$FilePathWithoutDriveLetter"

  New-PSDrive -Name $DriveName -PSProvider FileSystem -Root \\$Address\$DriveLetter$ -Credential $Credential -ErrorAction Stop
  (Get-Content $MappedFilePath) | ForEach-Object { $_ -replace $Replace, $ReplaceWith } | Set-Content $MappedFilePath
  Remove-PSDrive -Name $DriveName
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM