Here is a power shell script that reads the contents of a text file line by line and removes x number of characters from the beginning of the file. There are different ways to do this but I was getting different errors trying to implement them, at the end the below script worked.
The script will remove the first 22 characters from a txt file and will do this up to line 99. On one occasion I had to close the powershell window and re-open and re-run my script and that cleared one instance of the error.
Errors:
-Exception calling “Remove” with “2” argument(s): “Index and count must refer to a location within the string
-Exception calling “Remove” with “1” argument(s): “Index and count must refer to a location within the string
-Exception calling “Substring” with “2” argument(s): “startIndex cannot be larger than length of string”
-PowerShell Remove item [0] from an array
DnsServers.txt
primary name server = dc01.mylab.local
primary name server = dc02.mylab.local
primary name server = dc03.mylab.local
PS C:\> $dnsservers = Get-Content -Path c:\temp\DnsServers.txt -TotalCount 99 | ForEach-Object {$_.substring(22)}
Output (echo command vs write-host):
PS C:\>echo $dnsservers
dc01.mylab.local
dc02.mylab.local
dc03.mylab.local
PS C:\>Write-host $dnsservers
dc01.mylab.local dc02.mylab.local dc03.mylab.local
