从 TXT 或 CSV 中获取主机名,存储在变量中

Get Hostname from TXT or CSV, store in variable

这是我的第一个 Powershell 命令,已经有一个星期了,我无法弄清楚问题出在哪里。我想要做的是:

  1. Select TXT 或 CSV 文件包含主机名列表
  2. 存储在变量中
  3. 稍后我将为每个系统运行一个循环命令

我的第一个问题是,出于某种原因,我的 Get-Content 命令似乎无法正常工作,

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


最终,我将运行一个调用 $SystemList 变量的命令


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

}

$FileBrowser.ShowDialog() returns 显示对话框的结果 - 不是实际选择的文件路径。

为此,您需要 $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:\default\path\to\hostnames.txt"
}

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