Powershell从CSV读取主机输入

时间:2017-06-28 14:03:59

标签: powershell

我试图让这个脚本工作,而不是我手动输入系统名称,我可以将服务器放入csv并编写脚本并提供结果输出

它只是在等待手动输入的提示

$csvpath = E:\Tsm.csv
$SvcName = '*tsm*scheduler*'
$dataset = import-csv -path $csvpath
$row = ($dataset | where{$_.hostname -eq $SysName})
$SysName = Read-Host -prompt "Enter the target computer name: "
$Tsm = Get-Service -ComputerName $SysName | Where {$_.name -Like $SvcName}
Write-Host "Service :" $Tsm.DisplayName
Write-Host "Status :" $Tsm.Status
Write-host "Start Type :" $Tsm.StartType

If ($Tsm.StartType -ne 'Automatic')
{
    Write-Host "Setting service startup type to Automatic."
    Set-Service -InputObject $Tsm -StartupType Automatic
}
If ($Tsm.Status -ne 'Running')
{
    Write-Host "Starting the service."
    Start-Service -InputObject $Tsm
}

$Tsm2 = Get-Service -ComputerName $SysName | Where {$_.name -Like $SvcName}
Write-Host "Service :" $Tsm2.DisplayName
Write-Host "Status :" $Tsm2.Status
Write-host "Start Type :" $Tsm2.StartType
Export-Csv C:\TestOutput.csv$csvpath = E:\Tsm.csv

1 个答案:

答案 0 :(得分:0)

有很多方法可以获得你想要的东西。基本上你不应该使用Read-Host,或者只在你想要提示和手动等待时使用它。

有几点:

# this line uses the $SysName variable, which is asked for in the next line. 
# so it will not work correctly.
$row = ($dataset | where{$_.hostname -eq $SysName})       

# if you do not want the waiting and pause on screen, remove this line.
# That's the standard way Read-Host works.
$SysName = Read-Host -prompt "Enter the target computer name: "

一种可能的解决方案:

param(
    [switch]$manual
)

if($manual){
    $SysName = Read-Host -prompt "Enter the target computer name: "
}else{
    $SysName = "value or variable"
}

使用此解决方案,您可以使用.\script.ps1为自动解决方案调用脚本,或为.\script.ps1 -manual调用Read-Host

相关问题