首页 > 解决方案 > 如何在 powershell 中创建提示以询问用户在哪个服务器组上运行脚本

问题描述

美好的一天,我有这样的服务器

$libraryserver = ('192.168.0.3','192.168.0.4')
$dormetoryserver = ('192.168.1.15','192.168.1.16')
$teacherserver = ('192.168.1.110','192.168.1.112')

当用户运行 powershell 脚本时,应该有提示符或 arg - 比如:runscript.ps1 -library,之后 $servers 将从 libraryserver 列表中获取

foreach($server in $servers) {
  # Destination UNC path changes based on server name
  $destinationPath = "\\$server\D$\tmp\"
  # Check that full folder structure exists and create if it doesn't
  if(!(Test-Path $destinationPath)) {
    # -Force will create any intermediate folders
    New-Item -ItemType Directory -Force -Path $destinationPath
  }
  # Copy the file across
  Copy-Item $sourcefile $destinationPath
}

请你帮助我好吗 ?谢谢,尝试搜索并失败

标签: powershellvariablesselectremote-server

解决方案


声明一个只接受三个有效值之一的参数(您可以ValidateSet为此使用属性),然后根据参数选择适当的组:

param(
  [ValidateSet('Library', 'Dormitory', 'TeachersLounge')]
  [string]$ServerGroup
)

$servers = @{
  Library        = '192.168.0.3','192.168.0.4'
  Dormitory      = '192.168.1.15','192.168.1.16'
  TeachersLounge = '192.168.1.110','192.168.1.112'
}[$ServerGroup]

foreach($server in $servers){
  # ...
}

推荐阅读