Powershell 使用变量设置内容
我正在尝试使用PowerShell脚本生成PowerShell脚本。如何在新生成的脚本内容中获取变量的值Powershell 使用变量设置内容,powershell,powershell-5.0,Powershell,Powershell 5.0,我正在尝试使用PowerShell脚本生成PowerShell脚本。如何在新生成的脚本内容中获取变量的值 foreach($testServers中的服务器){ 新项目-ItemType文件-Name“$($server)\u wu.ps1”-路径“D:\tools\windows updates\uscripts” 设置内容-路径“D:\tools\windows updates\uscripts\$($server)\u wu.ps1”-值{ $computer=$server 调用命令-C
foreach($testServers中的服务器){
新项目-ItemType文件-Name“$($server)\u wu.ps1”-路径“D:\tools\windows updates\uscripts”
设置内容-路径“D:\tools\windows updates\uscripts\$($server)\u wu.ps1”-值{
$computer=$server
调用命令-ComputerName$computer-ScriptBlock{
设置ExecutionPolicy旁路
查找模块PSWindowsUpdate |安装模块-强制|导入模块-强制
}
$UpdateCount=(获取WindowsUpdate-ComputerName$computer)。计数
而($updateCount-gt“0”){
psexec\\$computer-s“powershell.exe”安装WindowsUpdate-确认:`$false-IgnoreReboot“”
重新启动计算机-计算机名称$Computer-强制-等待
$UpdateCount=(获取WindowsUpdate-ComputerName$computer)。计数
}
}
}
结果如下:
$computer=$server
调用命令-ComputerName$computer-ScriptBlock{
设置ExecutionPolicy旁路
查找模块PSWindowsUpdate |安装模块-强制|导入模块-强制
}
$UpdateCount=(获取WindowsUpdate-ComputerName$computer)。计数
而($updateCount-gt“0”){
psexec\\$computer-s“powershell.exe”安装WindowsUpdate-确认:`$false-IgnoreReboot“”
重新启动计算机-计算机名称$Computer-强制-等待
$UpdateCount=(获取WindowsUpdate-ComputerName$computer)。计数
}
但是,在新脚本中,我希望将
$server
替换为生成脚本的服务器的名称。好吧-所以我不知道如何操作我的字符串,最终解决了这个问题。。。任何更短、更简单的答案都是绝对受欢迎的(请注意,脚本的其余部分也发生了一些变化)
要生成的脚本和生成的脚本都像符咒一样工作(^^,)
干杯执行您要求的操作的标准方法可能是使用a并通过(
-f
)插入特定值:
但是,我认为编写一个参数化脚本并使用相应的计算机名调用该脚本可能比为每台计算机创建一个脚本更合适:
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$Computer
)
Invoke-Command -ComputerName $Computer -ScriptBlock {
Set-ExecutionPolicy Bypass
Find-Module PSWindowsUpdate | Install-Module -Force | Import-Module -Force
}
$updatesCount = (Get-WindowsUpdate -ComputerName $Computer).Count
while ($updatesCount -gt "0") {
psexec \\$Computer -s 'powershell.exe "Install-WindowsUpdate -Confirm:$false -IgnoreReboot"'
Restart-Computer -ComputerName $Computer -Force -Wait
$updatesCount = (Get-WindowsUpdate -ComputerName $Computer).Count
}
调用:
PS> script.ps1 -Computer FOO
PS>script.ps1-计算机FOO
显而易见的解决方案是将“value”设置为一个字符串变量,在设置内容之前,您可以进行任何需要的更改。我已尝试将新脚本放入
$value
变量中<代码>$value是一个字符串。我使用此$value
设置内容
。。。但我还是得到了同样的结果。
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$Computer
)
Invoke-Command -ComputerName $Computer -ScriptBlock {
Set-ExecutionPolicy Bypass
Find-Module PSWindowsUpdate | Install-Module -Force | Import-Module -Force
}
$updatesCount = (Get-WindowsUpdate -ComputerName $Computer).Count
while ($updatesCount -gt "0") {
psexec \\$Computer -s 'powershell.exe "Install-WindowsUpdate -Confirm:$false -IgnoreReboot"'
Restart-Computer -ComputerName $Computer -Force -Wait
$updatesCount = (Get-WindowsUpdate -ComputerName $Computer).Count
}
PS> script.ps1 -Computer FOO