1

I'm traditional bash user therefore i don't understand how to work foreach in powershell.

Powershell

I need output

Vasya
http://192.168.10.61:8085/data.json
Misha
http://192.168.10.82:8085/data.json

but I receive another output

Vasya
Misha
http://192.168.10.61:8085/data.json
http://192.168.10.82:8085/data.json
  • Script
$pspath="E:\monitor.ps1"
$txtpath="E:\temp.txt"
$user1="Vasya"
$user2="Misha"
$ip1="http://192.168.10.61:8085/data.json"
$ip2="http://192.168.10.82:8085/data.json"


$list = @"
${user1}-${ip1}
${user2}-${ip2}
"@

foreach ($zab in $list)
{
    $regex_url = 'http://\d+.\d+.\d+.\d+:\d+/data.json'
    $regex_name = "([A-Z]|[a-z])\w+"
    $name =  echo $zab |%{$_.split('-')} |sls -pattern $regex_name -AllMatches |%{$_.Matches -notmatch 'http|json|data'} |%{$_.Value}
    $url = echo $zab |%{$_.split('-')} |sls -pattern $regex_url -AllMatches |%{$_.Matches} |%{$_.Value}
    echo $name
    echo $url
}

Bash

In bash work's perfect.

  • Script

#!/bin/bash
users="Vasya-http://192.168.10.61:8085/data.json Misha-http://192.168.10.82:8085/data.json"


for zab in $users; do
    name=$(echo $zab |cut -f 1 -d -)
    url=$(echo $zab |cut -f 2 -d -)
    echo $name
    echo $url

done
exit 0

Help guys my hands are tied.

2 Answers 2

1

This:

$list = @"
${user1}-${ip1}
${user2}-${ip2}
"@

is a single multi-line string, so the foreach loop is redundant.

Split the string before running Select-String:

foreach($zab in $list -split '\r?\n'){
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your PowerShell script is quite different from the bash script.

I don't know if you need the greater complexity with the Select-String for other reasons,
but in PowerShell it could also be as easy as:

$users="Vasya-http://192.168.10.61:8085/data.json Misha-http://192.168.10.82:8085/data.json"

foreach($zab in ($users -split ' ')){
    $name,$url = $zab -split '-',2
    [PSCustomObject]@{
        Name = $name
        Url  = $url
    }
}

for this sample object oriented output:

Name  Url
----  ---
Vasya http://192.168.10.61:8085/data.json
Misha http://192.168.10.82:8085/data.json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.