简体   繁体   中英

Powershell Read-host input from CSV

Im trying to get this script to work by instead of me manually inputing sysnames that I can put the servers into csv and script it and give an output of results

It just sits at the prompt waiting for manual input

$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

There are many ways to get what you want. Basically you shouldn't be using Read-Host , or only use it when you want the prompt and manual waiting.

A couple of points:

# 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: "

One possible solution:

param(
    [switch]$manual
)

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

With this solution you can call your script using .\\script.ps1 for auto-solution or .\\script.ps1 -manual for the Read-Host .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM