modify text string in file

This topic contains 3 replies, has 3 voices, and was last updated by  Rob Jaudon 2 years, 4 months ago.

  • Author
    Posts
  • #25092

    Rob Jaudon
    Participant

    All,

    I am looking for direction on manipulating text in a text file. I have a bunch on entries for device names in a file and I would like to generate a pwd for each machine that is the reverse of the device name. This is for a testing lab and nothing more. I don't know where to start for taking an input string and reverse ordering it to out it back onto the file.

    Process for script

    1. Read a text file for the name
    2. Reverse the output to console or into a tab delimited output

    EX

    DeviceName1 1emanecived
    DeviceName2 2emanecived

  • #25107

    Simon Wåhlin
    Participant

    Try this:

    Get-Content -Path 'C:\folder\devices.txt' | Foreach{-join$_[-1..-[$_.length]]} | Out-File -Path 'C:\folder\passwords.txt'

    Here is an explanation:
    You can get one char of a string by using the index of the char, like this:

    $String = 'test'
    $String[0]

    This will output only the first char of $String (Index 0)

    If you want to select a range of chars, specify an index range:

    $String[0..2]

    This will ouput 'tes', the range of chars from index 0 to index 2

    PowerShell also accepts negative indexes, for example:

    $String[-1]

    This will return the last char of $String

    To turn a string backwards, simply index the range from the last char to the first char.
    Since $String in this example has a length of 4, this will return the string backwards:

    $String[-1..-4]

    To make it more dynamic, replace -4 with -($String.length), hence:

    $String[-1..-[$String.length]]

    /Simon

    • #25540

      Rob Jaudon
      Participant

      Simon,

      Thank you for the explanation. That is a HUGE help.

      Rob

  • #25122

    Itta
    Participant

    There may be other simple ways to solve this, however below is my version. Note: *You need to loop the below code for all array elements*

    $A = Get-Content D:\devices.txt
    $Split = $A[0] -split ""
    [array]::Reverse($Split)
    $rev = $Split -join "
    $revString = $Rev.ToLower()
    $HT = [ordered]@{'DeviceName' = $A[0]; 'Password' = $revString}
    $Obj = New-Object -TypeName psobject -Property $HT
    $Obj | ft -AutoSize

You must be logged in to reply to this topic.