Friday, November 30, 2007

Powershell equivalent of "Right()"

In VBScript, there is the the Right() function used to return the right-most X characters of a string.

After googling, I couldn't find a clear example of doing this in Powershell. Microsoft has a page on VBscript equivalents in Powershell, but their Right() page didn't give exactly what I wanted.

My delimma:
I have a Powershell script performing a nightly commit of our production servers' code shares to an SVN repository. One of the scripts calls "svn status", which returns the status of all files in the working folder as compared to the repository:
!______D:\Path\to\some\file
Where the first 6 characters are status codes, there's 1 space, then the file path (I replaced spaces with _ above for readability). What I need for performing an "svn add" or "svn delete" is just the file path. So, I needed to somehow get all EXCEPT the first 7 characters of the output into a variable.

To do this, I ended up using the .SubString() function. This is called with two arguments: the number of characters to remove, and the number of characters to return. To remove the first 7 characters, I specify "7" and then the length of the string minus 7:
$FileName = $SvnStatusLine.SubString(7,$SvnStatusLine.Length - 7)

Conversely, if you wanted to remove the LAST 7 characters, just reverse the position of the arguments.

Update:
Thanks to a knowledgeable commenter for this slicker alternative:

/\/\o\/\/ said...

in this case you might consider using remove :

$s = "!______D:\Path\to\some\file"
$s.Remove(0,7)

D:\Path\to\some\file

Greetings /\/\o\/\/


Where were you a few days ago ;-) Thanks!

1 comments:

/\/\o\/\/ said...

in this case you might consider using remove :

$s = "!______D:\Path\to\some\file"
$s.Remove(0,7)

D:\Path\to\some\file

Greetings /\/\o\/\/