PowerShell - Remote Upgrade Script - windows

I am trying to upgrade Powershell on a bunch of Windows 7 boxes so I can do other remote installs and such. I am using Invoke-Expression but I swear this worked once before without it. There doesn't appear to be a Wait option for any of this. It does work when I run the Invoke-Expression locally. I also tried Start-Process. Is there a better way to get feedback on why it didn't run? The debugging is painfully slow because it has been a lot of just guessing, both due to lack of feedback and due to its hard to tell on the remote machine when its actually installing the background. The script is getting copied. I've tried without the Remove-item in case I was deleting it too fast. The $cred is admin. I'm not sure Execution Policy is necessary.
foreach ($comp in $computers) {
$comp.Name
if(test-connection -ComputerName $comp.Name -quiet ){
$Destination = "\\$($comp.Name)\c$\Temp\"
copy-item -path "\\10.1.32.161\New Client Setups\WMF_5.1_PowerShell\*" -Destination $Destination -recurse -force
"`t Copied"
$session = Enter-PSSession $comp.Name -Credential $cred
$results = Invoke-Command -ComputerName $comp.Name -ScriptBlock {
Set-ExecutionPolicy RemoteSigned
$ver = $PSVersionTable.PSVersion.Major
"`t Powershell Version : $ver"
if ($ver -lt "5"){
"`tNeeds upgrade"
$argumentList = #()
$argumentList += , "-AcceptEULA"
$argumentList += , "-AllowRestart"
#Invoke-Expression "& 'C:\Temp\Windows7_Server2008r2\Install-WMF5.1.ps1' + $argumentList"
Invoke-Expression 'C:\Temp\Windows7_Server2008r2\Install-WMF5.1.ps1 -AllowRestart -AcceptEULA'
}
}
$results
Remove-item -Path "$Destination*" -recurse
Exit-PSSession
Remove-PSSession -session $session

Related

HOWTO Discover Postgres Running in Windows Environment

HOWTO Discover Postgres Running in Windows Environment
So How do we discover all the Postgres installed in our Windows 2012R2/2016 environment with PowerShell?
I wrote this script but I am told that will not find ALL postgres instances, if the install was not coded to create a service... Ideas?
#List-PostGres-Servers.ps1
Remove-Item -force "drive\path\*-List-PostGres-Servers-log.txt" -ErrorAction
ignore
$today = (Get-Date -Format yyyyMMdd)+"-"+(get-date -uformat %H)
Start-Transcript -Path "drive\path\$today-List-PostGres-Servers-log.txt"
$servers = get-content 'drive\path\input\listofservers.txt'
foreach ($server in $servers){
if ((Test-Connection -Count 1 -ComputerName $server -quiet) -eq $false){continue}
else{
$PostGresSearch = (get-service -ComputerName $server -name *postgres* -ErrorAction Ignore -WarningAction Ignore -InformationAction Continue)
$PostGresServicename = $PostGresSearch.Name
#|out-file -Encoding ascii "drive\path\output\DOMAINNAME-CheckListPostgres.txt" -force -Append
if ($PostGresServicename -eq $null){continue}
else {
$server+","+" "+$PostGresServicename
}
}
}
You could check to see if postgres is currently running with:
Get-Process *postgres*
In the case where neither a service is installed nor is the binary running, then you're not using that postgres install. Alternatively, search $env:ProgramFiles or ${env:ProgramFiles(x86)} for psql.

Run Cleanmgr on remote PC as System user

So i'm trying to run CleanMgr via powershell on a remote computer. Since CleanMgr has a GUI Powershell cannot run it directly, as described here
If you do this then CleanMgr will hang forever waiting for user input. So this means we have to approach this differently.
I tried several approaches, see below. But non of them works like i would. It still hangs OR runs attached from powershell giving no feedback when done.
Simply put i want to run (remotely) CleanMgr on our Office PC's from my PC (Domain Admin).
Invoke-Command -ComputerName $ComputerOBJ -ScriptBlock {
# Create registry values
Write-Host "Setup keys..."
$volumeCaches = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
foreach ($key in $volumeCaches) {
Set-ItemProperty -Path "$($key.PSPath)" -Name StateFlags0333 -Value 2
}
# Execute Disk Cleanup Tool (cleanmgr.exe)
#Write-Host 'Starting CleanMgr.exe...'
Attempt 1:
Start-Process -FilePath "CleanMgr.exe" -ArgumentList '/sagerun:333' -NoNewWindow
Attempt 2:
Start-Process -FilePath "CleanMgr.exe" -ArgumentList '/sagerun:333' -WindowStyle Hidden
Attempt 3:
Invoke-WmiMethod -Class Win32_Process -Name "Create" -ArgumentList 'CleanMgr.exe /sagerun:333'
Attempt 4:
C:\temp\PsExec.exe \\$ComputerOBJ CleanMgr.exe /sagerun:333
Attempt 5:
$A = New-ScheduledTaskAction -Execute "cleanmgr.exe" -Argument '/sagerun:333'
$T = New-ScheduledTaskTrigger -Once -At (get-date).AddSeconds(1); $t.EndBoundary = (get-date).AddSeconds(60).ToString('s')
$S = New-ScheduledTaskSettingsSet -StartWhenAvailable -DeleteExpiredTaskAfter 00:00:30
Register-ScheduledTask -Force -user SYSTEM -TaskName "Run CleanMgr" -Action $A -Trigger $T -Settings $S
#Wait until Clean is done.
Write-Host 'Waiting for CleanMgr and DismHost processes to complete...'
Get-Process -Name cleanmgr, dismhost -ErrorAction SilentlyContinue | Wait-Process
# Remove the previously created registry values
Write-Host "Cleanmgr completed, now deleting keys"
$volumeCaches = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
foreach ($key in $volumeCaches) {
Remove-ItemProperty -Path "$($key.PSPath)" -Name StateFlags0333 -Force
}
}

powershell start-process as admin, am i misssing something

Im trying to create a script where a domain user would be able to run IIS service on windows as a local admin using stored credentials.
$adminerpath = 'c:\programdata\adminer'
Function StoreCreds(){
$credential = Get-Credential
$credential | Export-CliXml -Path $adminerpath\data.dat
}
if (Test-Path $adminerpath){
$credential = Import-CliXml -Path $adminerpath\data.dat
Start-Process C:\windows\System32\inetsrv\InetMgr.exe -Credential ($credentials)
}
else {
New-Item -Path $adminerpath -ItemType "directory"
attrib +h c:\programdata\adminer | Out-Null
StoreCreds
}
very simple, should see if the credential is stored and then run process with -credential.
it works with anything else (like note.exe or pwoershell.exe), but when i try running this with InetMgr.exe im getting:
start-process : This command cannot be run due to the error: The requested operation requires elevation.
any help would be much appriciated

Running a powershell from rundeck(linux) display different result

I'm trying to run a powershell script from rundeck(linux), If I run the script locally[Deletes some files from multiple terminal servers](Windows server) it is working as expected however if I call it from rundeck server(winrm configured) it seems that the script cant access the remote folders I'm trying to access.
I tried running the script using the same user but still shows different result.
Script bellow:
$userAD = "someuser"
$servers = Get-Content C:\TSList.csv
$Folder = "c$\Users\$userAD\"
$TSFolderShare = "\\sharepath"
Write-Output "#####Start of script#####"
Write-output `n
Write-output "Checking if $userAD user profile exist in Terminal servers..."
sleep -seconds 1
foreach ($server in $servers) {
Test-Path "\\$server\$Folder" -PathType Any
Get-ChildItem "\\$server\$Folder"
if (Test-Path "\\$server\$Folder" -PathType Any) {
Write-output "Resetting user profile in $server.."
Get-ChildItem "\\$server\$Folder" -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
sleep -seconds 1
Write-output "Done."
if( (Get-ChildItem "\\$server\$Folder" | Measure-Object).Count -eq 0)
{
Write-output "Done."
}
}
else
{
Write-output "Resetting user profile in $server.."
sleep -seconds 1
Write-output "User profile does not exist in $server."
#Write-output "\\$server\$Folder does not exist in $server!" -ForegroundColor Red
}
}
EDIT: It seems my problem is when running my script from another script with RunAS.
Below I'm trying to access a folder from another server using ps script, but since I want to integrate this to Rundeck I need to call my ps script from my linux server using python. I did a test running the ps script directly and calling the test path script using another script with RunUs using the same user I used to run the script manually
Scenario 1
Running PS script via separate PS script with RunAS(my_account)
$username = "my_account"
$password = "my_password"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
Invoke-Command -FilePath "C:\testpath.ps1" -Credential $cred -Computer localhost
(C:\testpath.ps1) Content below:
Test-Path "\\server\c$\Users\myaccount\"
result:
Access is denied
+ CategoryInfo : PermissionDenied: (\server\c$\Users\myaccount:String) [Test-Path], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.TestPathCommand
+ PSComputerName : localhost
False
Scenario 2
Running C:\testpath.ps1 directly as my_account
Test-Path "\\server\c$\Users\myaccount\"
result:
True
I used session configuration in powershell to solve the issue. This way allows you to tie a credential to a PowerShell session configuration and reuse this configuration for all future connections.
https://4sysops.com/archives/solve-the-powershell-multi-hop-problem-without-using-credssp/
Thanks a lot!
You're facing a double-hop issue with Rundeck and Powershell, here the explanation. That's asked before, take a look a this, and here a good workaround. Also this to solve it.

large file transfer write-progress not updating in real-time

I am attempting to write progress on a large file copy in powershell. I have the progress bar working quite well with small file copies, but when I transfer over a gig of data the progress bar does not update in real time. I can check the folder I am copying to and see that everything is transferring as it should, however, my progress bar just sits on the same file and the bar itself doesn't seem to move at all. I am using CredSSP to invoke the command on a server at our data center, so I'm not sure if that is making a difference in the write-progress cmdlet or not. Here is an excerpt of my script:
$credential = Get-Credential -Credential domain\user
$session = New-PSSession -ComputerName server.domain.edu -Credential $credential -authentication CredSSP
Invoke-Command -session $session -ScriptBlock {
$path = "\\domain\shares\dfsdatacenter" + "-DC" + "\HomeDir\ttest1"
$dest = "\\server\Archive$\Terminated"
$counter = 0
$files = gci $path -recurse | ? { -not $_.PSIsContainer; }
Foreach($file in $files)
{
Copy-Item $path $dest -recurse -force
Write-Progress -Activity "Backing Up Terminated User HomeDir:" -status $file.FullName -PercentComplete ($counter / $files.count*100)
$counter++
}
}
Thanks in advance for any help anyone can offer!

Resources