Selecting lines in PowerShell script

1

I have code:

$dir=(new-object Net.WebClient).DownloadString("http://www.nbp.pl/kursy/xml/dir.txt")
$dir | foreach {
    if ($_.startswith("a"))
    {
        write-host $_
    }
}

and I need to select only lines that begin with a character. This script is not working, it does not print anything. What should I change in this script to make it work?

pbies

Posted 2016-12-03T22:23:55.310

Reputation: 1 633

Answers

2

Your $dir is a single string with newline characters inside, thus foreach runs only once in your example (you will print the whole string if you change the condition to if ($_.startswith("c")).

You need to split the $dir variable, for example with:

$dir=(new-object Net.WebClient).DownloadString("http://www.nbp.pl/kursy/xml/dir.txt")
foreach ($singleEntry in $dir -split '\r\n') {
    if ($singleEntry.startswith("a"))
    {
        write-host $singleEntry
    }
}

techraf

Posted 2016-12-03T22:23:55.310

Reputation: 4 428

Great! Can I remove all not a beginning lines from $dir? – pbies – 2016-12-03T22:44:14.990

Not sure what the new question is about... Of course you can. – techraf – 2016-12-03T22:58:32.057