我编写了一个脚本,将.EXE推送到跨域的多个远程服务器并安装它们。当我执行脚本时,它会尝试在我的本地计算机上运行安装程序。对我的脚本进行任何检查和更正都会有很大帮助。谢谢
$uname='domain\username'
$pwd='Password' | ConvertTo-SecureString -Force -AsPlainText
try {
$targets = Get-Content -Path D:\scripts\serverlist.txt
$source = C:\Downloads\installer.exe
$creds=New-object System.Management.Automation.PSCredential ($uname, $pwd)
[ScriptBlock] $code = {
if(!(Test-Path "C:\Temp"))
{
New-Item -Path "C:\Temp" -ItemType Directory
}
}
function Installer([string] $file, [String] $argslist)
{
$ErrorActionPreference="Stop"
try
{
$exec = Start-Process -FilePath $file -ArgumentList $argslist -Wait -PassThru
Write-Host "Exit code for installation of $file is $($exec.ExitCode)"
return $exec.ExitCode
}
catch
{
throw
}
}
foreach($target in $targets){
$name = GC env:computername
$current = New-PSSession -ComputerName $name -Credential $creds -ErrorAction SilentlyContinue
Invoke-Command -Session $current -ScriptBlock $code
Robocopy $source E:\Temp
Installer "\\$name\$source" "/q /norestart"
$current | Remove-PSSession
} }
catch
{
Write-Host -f red "An error has occurred!"
Write-Host "$($error[0].exception)"
$error.clear()
exit $LASTEXITCODE
}
答案 0 :(得分:1)
这看起来很复杂。我不确定您的环境有哪些访问限制,但我会尝试这样:
$source = Get-Item -Path "C:\Downloads\installer.exe"
ForEach ($target In $targets) {
Try {
Copy-Item -Path ($source.FullName) -Destination "\\$target\c$\temp\" -Recurse -Force
Invoke-WmiMethod -ComputerName $target -Class Win32_Process -Name Create -ArgumentList "C:\temp\$($source.Name) /q /norestart"
} Catch {
$_
}
}
不是硬编码用户名/密码,而是从头开始使用正确的凭据运行脚本。
如果用户名/密码有权访问, Copy-Item
应自动创建临时文件夹。
Invoke-WmiMethod
将在$ target上启动该进程,再次提供用户名/密码有权访问此目的。 Invoke-Command
也有效(如萨米所说)。