我怎么能有一个回弹在同一条线上回响的powershell循环?

mho*_*321 1 sql powershell formatting loops echo

目前我有跟随ps读取用户名列表,然后回复它.

用户名文件如下

username1
username2
username3
Run Code Online (Sandbox Code Playgroud)

ps脚本如下

$userNames = (Get-Content usernames.txt)# | Sort-Object
$userID=0
$userNames.Count
echo "FROM table WHERE (userID ='"
For ($i =1; $i -le ($userNames.Count - 1); $i++)
{
echo $userNames[$userID] "' OR userID='"
$userID++
}
echo $userNames[$userNames.Count - 1] "'"
Run Code Online (Sandbox Code Playgroud)

我希望能够在同一行上回复(并最终写入文本文件).

FROM table WHERE (userID = 'username1' OR userID = 'username2' OR userID = 'username3'
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Jos*_*osh 6

你在寻找的是:

Write-Host "Blah" -NoNewLine
Run Code Online (Sandbox Code Playgroud)

我可能会重写这样的脚本,以避免使用 For...Loop

$userNames = (Get-Content usernames.txt) | Sort-Object
$count = 0

Write-Host "FROM table WHERE (" -NoNewLine

$userNames |% {
    Write-Host "userID='$_'" -NoNewLine

    if(++$count -ne $userNames.Length){
        Write-Host " OR " -NoNewLine
    }
    else {
        Write-Host ")"
    }
}
Run Code Online (Sandbox Code Playgroud)

此脚本还将利用PowerShell的另一个不错的功能,即字符串文字中的变量替换.在迭代期间For-EachObject自动设置$_为当前对象,PowerShell将自动解析字符串文字中的变量并替换它们的值.

另外...... 我刚刚意识到整个事情可以简化为以下几点:

$userNames = (Get-Content usernames.txt) | Sort-Object |% { "'$_'" }

Write-Host "FROM table WHERE UserID in ($([String]::Join(",",$userNames)))"
Run Code Online (Sandbox Code Playgroud)

这将产生以下查询:

FROM table WHERE UserID in ('username1','username2','username3')
Run Code Online (Sandbox Code Playgroud)

在我看来,这是一个更愉快的脚本查询:)