Removing spaces from a variable input using PowerShell 4.0

前端 未结 5 1655
青春惊慌失措
青春惊慌失措 2021-02-05 03:59

I\'ve tried a few things already but they don\'t seem to work for some reason.

Basically what I\'m attempting to do is have a user input a value using the \"Read-host\

5条回答
  •  隐瞒了意图╮
    2021-02-05 04:21

    You also have the Trim, TrimEnd and TrimStart methods of the System.String class. The trim method will strip whitespace (with a couple of Unicode quirks) from the leading and trailing portion of the string while allowing you to optionally specify the characters to remove.

    #Note there are spaces at the beginning and end
    Write-Host " ! This is a test string !%^ "
     ! This is a test string !%^
    #Strips standard whitespace
    Write-Host " ! This is a test string !%^ ".Trim()
    ! This is a test string !%^
    #Strips the characters I specified
    Write-Host " ! This is a test string !%^ ".Trim('!',' ')
    This is a test string !%^
    #Now removing ^ as well
    Write-Host " ! This is a test string !%^ ".Trim('!',' ','^')
    This is a test string !%
    Write-Host " ! This is a test string !%^ ".Trim('!',' ','^','%')
    This is a test string
    #Powershell even casts strings to character arrays for you
    Write-Host " ! This is a test string !%^ ".Trim('! ^%')
    This is a test string
    

    TrimStart and TrimEnd work the same way just only trimming the start or end of the string.

提交回复
热议问题