【发布时间】:2020-11-08 19:31:36
【问题描述】:
这是我在 powershell 中的第一个程序,我试图从用户输入中获取,然后 ping IP 地址或主机名,在桌面上创建文本文件。 但是如果用户想要添加多个 IP,我会进入无限循环。 我在这里询问IP地址。
$dirPath = "C:\Users\$env:UserName\Desktop"
function getUserInput()
{
$ipsArray = @()
$response = 'y'
while($response -ne 'n')
{
$choice = Read-Host '
======================================================================
======================================================================
Please enter HOSTNAME or IP Address, enter n to stop adding'
$ipsArray += $choice
$response = Read-Host 'Do you want to add more? (y\n)'
}
ForEach($ip in $ipsArray)
{
createFile($ip)
startPing($ip)
}
}
然后我为每个 IP 地址创建文件:
function createFile($ip)
{
$textPath = "$($dirPath)\$($ip).txt"
if(!(Test-Path -Path $textPath))
{
New-Item -Path $dirPath -Name "$ip.txt" -ItemType "file"
}
}
现在你可以看到问题了,因为我想要使用 TIME 格式写入,所以我的 ForEach 循环有问题,当我开始 ping 时,我无法到达数组中的下一个元素,直到我停止 cmd.exe。
function startPing($ip)
{
ping.exe $ip -t | foreach {"{0} - {1}" -f (Get-Date), $_
} >> $dirPath\$ip.txt
}
也许我应该为每个 IP 地址创建其他文件并传递参数?
【问题讨论】:
-
-t选项将无限期地继续 ping。这就是你想要的,在后台对所有地址进行连续 ping 操作? -
是的,我想让它运行。
标签: powershell ping