Reputation: 107
I've written a script to push .EXE over to multiple remote servers across domains and install them. When I execute the script, it attempts to run the installer on my local machine. Any review and correction to my script would be of great help. Thank you
$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
}
Upvotes: 0
Views: 627
Reputation: 1716
This looks over complicated. I'm not sure what access limitations your environment has, but I would try going this way:
$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 {
$_
}
}
Instead of hard coding a username/password, run the script with correct credentials from the start.
Copy-Item
should create the temp folder automatically, provided the username/password has access to do this.
Invoke-WmiMethod
will start the process on $target, again provided username/password has access to do this. Invoke-Command
also works (as Sami mentioned).
Upvotes: 1