首页 > 解决方案 > 从 TXT 或 CSV 获取主机名,存储在变量中

问题描述

这是我的第一个 Powershell 命令,已经一周了,我无法弄清楚问题出在哪里。我想要做的是以下内容:

  1. 选择包含主机名列表的 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"
    }

}

标签: powershellscripting

解决方案


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

为此,您需要$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

推荐阅读