powershell - 从 TXT 或 CSV 获取主机名,存储在变量中
问题描述
这是我的第一个 Powershell 命令,已经一周了,我无法弄清楚问题出在哪里。我想要做的是以下内容:
- 选择包含主机名列表的 TXT 或 CSV 文件
- 存储在变量中
- 稍后我将为每个系统运行一个循环命令
我的第一个问题是,由于某种原因,我的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()
返回显示对话框的结果- 而不是实际选择的文件路径。
为此,您需要$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
推荐阅读
- java - 获取 java.lang.IllegalAccessError:当我尝试将 menuBar 添加到我的程序时,超类访问检查失败
- javascript - 如何将 javascript 数组与 html 文件连接?
- docker - Docker 原因:连接 ECONNREFUSED 0.0.0.0:80
- powershell - 如何在 PowerShell 中使用 select-object 获取最后写入时间对象?
- asp.net - Visual Studio 19 无法识别用于 ASP.NET 的 SQL Server 2012
- python - numpy数组创建列表数组
- go - kubernetes golang 客户端:在 pod 中获取容器
- bash - 如何在给定基本名称的情况下查找文件并在 bash 脚本中检索其文件类型?
- javascript - 如何将两个或第 n 个不同的列表项按顺序添加到新列表中?
- python - 如何在训练运行之间的中间层内更新每个时期的参数?(张量流急切执行)