sql
  • loops
  • powershell
  • formatting
  • echo
  • 2012-04-06 51 views 1 likes 
    1

    目前我有後續的ps讀取用戶名稱列表,然後回聲。如何在同一行上回顯回聲的PowerShell循環?

    用戶名文件如下

    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' 
    

    我該如何解決這個問題?

    回答

    6

    你所尋找的是:

    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') 
    

    這是一個更加舒適腳本查詢我的意見:)

    +0

    這正是我正在尋找的把戲。它現在打印userID ='username1'。我怎樣才能擺脫1後的空間? – mhopkins321 2012-04-06 15:39:57

    +0

    @ mhopkins321 - 查看我上面的編輯 – Josh 2012-04-06 20:38:58

    相關問題