Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

powershell - Get Hostname from TXT or CSV, store in variable

This is my first Powershell command and it has been a week and I can't figure out what's the problem. What I want to do is the following:

  1. Select a TXT or CSV file contains a list of hostname
  2. Store in a variable
  3. Later I am going to run a loop command for each system

My first issue is that for some reason my Get-Content command seems not to be working,

#Select File that contains the list of machines

$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
    InitialDirectory = [Environment]::GetFolderPath('Desktop') 
    Filter = 'Text File (*.txt)|*.docx|Spreadsheet (*.csv)|*.csv|All Files (*.*)|*.*'
    
    }
    $GetList = $FileBrowser.ShowDialog() 
    
#Get Each List of System
    
    $SystemList = Get-Content -Path "$GetList"


Eventually, I am going to run a command calling $SystemList variable


# Remote run the install for each system

foreach ($System in $SystemList) {
    if (test-Connection -Cn $System -quiet) { 
        Copy-item $SetupFolder -Destination \$System$Dest -recurse -Force

        if (Test-Path - Path $) {
            Invoke-Command -ComputerName $System -ScriptBlock {powershell.exe $Path /S} -credential $Credentials

            Write-Host -ForegroundColor Green "Installation Successful on $System"
        }

    } else {
    Write-Host -ForegroundColor Red "$System is not online, Install failed"
    }

}
question from:https://stackoverflow.com/questions/66067701/get-hostname-from-txt-or-csv-store-in-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

$FileBrowser.ShowDialog() returns the result of showing the dialog - not the file path that was actually selected.

For that, you'll need $FileBrowser.FileName:

$dialogResult = $FileBrowser.ShowDialog()

if($dialogResult -eq 'OK'){
  # user selected a file
  $GetList = $FileBrowser.FileName
}
else{
  # user canceled the dialog, either `return`, throw an error, or assign a static value to `$GetList`, like this
  $GetList = "C:defaultpathohostnames.txt"
}

# Now we can safely proceed with `Get-Content`:
$SystemList = Get-Content -LiteralPath $GetList

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...