gpt4 book ai didi

sql - 我如何拥有在同一行上回显回声的powershell循环?

转载 作者:行者123 更新时间:2023-12-03 00:30:56 25 4
gpt4 key购买 nike

目前,我有跟随ps的用户名列表,然后回显它。

用户名文件如下

username1
username2
username3

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] "'"

我希望能够在同一行上全部回显(并最终写入文本文件)。
FROM table WHERE (userID = 'username1' OR userID = 'username2' OR userID = 'username3'

我将如何解决这个问题?

最佳答案

您正在寻找的是:

Write-Host "Blah" -NoNewLine

我可能会像这样重新编写脚本,以避免不得不使用 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 ")"
}
}

该脚本还将利用PowerShell的另一个不错的功能,即字符串文字中的变量替换。 For-EachObject会在迭代过程中自动将 $_设置为当前对象,PowerShell将自动解析字符串文字中的变量并替换其值。

另外... 我刚刚意识到可以将整个事情简化为以下内容:
$userNames = (Get-Content usernames.txt) | Sort-Object |% { "'$_'" }

Write-Host "FROM table WHERE UserID in ($([String]::Join(",",$userNames)))"

这将产生以下查询:
FROM table WHERE UserID in ('username1','username2','username3')

我认为这是一个更令人愉快的脚本和查询:)

关于sql - 我如何拥有在同一行上回显回声的powershell循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10045551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com