每隔x秒循环一次脚本

时间:2013-12-27 15:09:57

标签: loops powershell

我可以将代码放在每隔x秒自动循环一次,但如果脚本被CTRL + C取消,让它再次请求输入?

    mode con: cols=40 lines=5
    while ($tag -ne "Q"){
    $tag1 = ""
    while (-not ($tag1)) {
    $tag1 = Read-Host 'Enter tag #, IP, or Q to quit'
    }
    if($tag1 -eq "Q"){break}

    $ErrorActionPreference = 'silentlycontinue'

        mode con: cols=80 lines=53

    cls

        sc.exe \\$tag1 start RemoteRegistry;

    cls

        start-sleep -seconds 2
*-Need Loop here-*      
    cls

        $CompInfo = get-wmiobject -class win32_computersystem -computername $tag1;
        $username = $CompInfo.UserName.Split("\")[1]; #Outputs DOMAIN\USER into an array and selects USER to display
        $fullname = ((net user $username /domain | Select-String "Full Name") -replace "Full Name","").Trim(); #Takes the USER and displays the full name

        #get-wmiobject -class win32_computersystem -computername c73118 | format-table -Property @{Name="DOMAIN\user";Expression={$_.username}} --> Get w/o variable

        $CompInfo `
        | Format-Table -Autosize -Property `
            @{ Name = "DOMAIN\user"; Expression = { $_.username } },
            @{ Name = "Full Name"; Expression = { $fullname } };
    }

1 个答案:

答案 0 :(得分:1)

这样做的方法是将其拆分为两个脚本。让第一个脚本接受计算机名称的输入,并使用第二个脚本循环返回登录用户。

您的代码如下所示:

<强> C:\测试\ Script1.ps1

mode con: cols=40 lines=5
while ($tag -ne "Q"){
    $tag1 = ""
    while (-not ($tag1)) {
        $tag1 = Read-Host 'Enter tag #, IP, or Q to quit'
    }
    if($tag1 -eq "Q"){break}

    $ErrorActionPreference = 'silentlycontinue'
    mode con: cols=80 lines=53
    cls
    sc.exe \\$tag1 start RemoteRegistry;
    cls

    start-sleep -seconds 2

    #Launch Second script
    Start-Process powershell.exe -ArgumentList "-NoProfile -Command `"& C:\Test\Script2.ps1 $tag1`" "

}

<强> C:\测试\ Script2.ps1

$tag1 = $args[0]

While(1)
{

        $CompInfo = get-wmiobject -class win32_computersystem -computername $tag1;
        $username = $CompInfo.UserName.Split("\")[1]; #Outputs DOMAIN\USER into an array and selects USER to display
        $fullname = ((net user $username /domain | Select-String "Full Name") -replace "Full Name","").Trim(); #Takes the USER and displays the full name

        #get-wmiobject -class win32_computersystem -computername c73118 | format-table -Property @{Name="DOMAIN\user";Expression={$_.username}} --> Get w/o variable

        $CompInfo `
        | Format-Table -Autosize -Property `
            @{ Name = "DOMAIN\user"; Expression = { $_.username } },
            @{ Name = "Full Name"; Expression = { $fullname } };

    Start-Sleep -Seconds 2
}

当第一个脚本获取计算机名称时,它会在另一个PowerShell窗口中启动第二个脚本。这意味着您可以让它运行,并使用Ctrl + C退出它,同时仍然保持原始脚本在第一个PowerShell会话中运行。