Solved

Windows Powershell Scripting

Posted on 2016-12-01
8
32 Views
Last Modified: 2017-01-04
Hi, could someone assist with an example of a powershell script that I could edit for my network environment?

I have a need to update (overwrite) a file on all PC's in a particular department in our MS AD environment, the path I need to drop the file into is C:\Program Files\xxx\xxx.

The share file will come off a shared network drive that the department already have access to, I was going to do it via a batch file at logon but have concerns that it will not overwrite the existing file without user intervention.  The users machines are W7 Pro's and have tighter security than most machines so additional credentials might be needed and I wouldn't want that visible to the users.

So is there a script that I can edit and use to achieve this and what is the best way to execute it.  It would be good to have it run during the day rather than at logon if possible by being pushed to the PC's?

Thanks for any advise or assistance in advance.
0
Comment
Question by:mercuriousu2
  • 4
  • 4
8 Comments
 
LVL 83

Accepted Solution

by:
oBdA earned 500 total points
ID: 41908665
Logon would not work, as users don't have Write permissions in Program Files.
You can use this to push the file from an administrative machine. It will log which machines were processed, so you can call it several times and it will only reprocess machines were a former attempt failed.
$SearchBase = "OU_Wherever,DC=contoso,DC=com"
$SourceFile = 'C:\Temp\test.txt'
$TargetFolder = 'C:\Program Files'

$ScriptItem = Get-Item -Path $MyInvocation.MyCommand.Path
$CsvPath = Join-Path -Path $ScriptItem.DirectoryName -ChildPath "$($ScriptItem.BaseName).csv"
$Csv = If (Test-Path -Path $CsvPath) {
	"Continuing from  $($CsvPath) ..." | Write-Host -ForegroundColor White
	Import-Csv -Path $CsvPath
} Else {
	"Retrieving AD computer from $($SearchBase) ..." | Write-Host -ForegroundColor White
	Get-ADComputer -Properties Name -Filter "(Enabled -eq 'True') -and (OperatingSystem -like 'Windows 7*')" -SearchBase $SearchBase |
		Select-Object Name, DNSHostName, @{n='Processed'; e={'False'}},  @{n='Error'; e={''}}, DistinguishedName |
		Sort-Object -Property Name
}
ForEach ($Computer In $Csv) {
	"Processing $($Computer.Name) ... " | Write-Host -ForegroundColor White -NoNewline
	If ($Computer.Processed -eq 'True') {
		'already processed.' | Write-Host -ForegroundColor Green
	} Else {
		If (Test-Connection -ComputerName $Computer.DNSHostName -Count 2 -Quiet) {
			'online, copying ... ' | Write-Host -ForegroundColor Yellow -NoNewline
			Try {
				Copy-Item -Path $SourceFile -Destination "\\$($Computer.DNSHostName)\$($TargetFolder.Replace(':', '$'))" -Force -ErrorAction Stop
				$Computer.Processed = 'True'
				'OK.' | Write-Host -ForegroundColor Green
			} Catch {
				$Computer.Error = $_.Exception.Message
				$Computer.Error | Write-Host -ForegroundColor Red
			}
		} Else {
			$Computer.Error = 'Offline'
			$Computer.Error | Write-Host -ForegroundColor Red
		}
	}
}
$Csv | Export-Csv -Path $CsvPath -NoTypeInformation
$Csv | Format-Table -AutoSize

Open in new window

1
 

Author Comment

by:mercuriousu2
ID: 41908704
Hi, thank you for providing that. I assume these are the only editable fields I need to edit:

$SearchBase = "OU_Wherever,DC=contoso,DC=com"
$SourceFile = 'C:\Temp\test.txt'
$TargetFolder = 'C:\Program Files'

Am I correct in assuming that the searchbase is the OU with the group membership in?

Does this run seamless to the user, also where can I edit the path to get a completed or failed csv or does the script write it to the source file destination?

Thanks
0
 
LVL 83

Expert Comment

by:oBdA
ID: 41908711
$SearchBase is the OU where the computer objects to process are.
The csv file will be stored in the script's folder, with the script's name, and the extension '.csv'.
0
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 

Author Comment

by:mercuriousu2
ID: 41908834
Ok, that failed and I think the was because the OU of the group needed is users and not Computer names.  We dont have a OU for specific users PC's as the change out rate at time would make it hard to keep updated.

Is there an addition that can be made so the script picks up the logged on user at the PC at all?

Thanks
0
 
LVL 83

Expert Comment

by:oBdA
ID: 41908846
You're trying to deliver a file to computers - where do users come into play here? If it's under Program Files, the program will be installed on the machine regardless of the user logging on at some point.
0
 

Author Comment

by:mercuriousu2
ID: 41908852
Yup, but I dont have the user machines in an OU specific just for them, just one OU for computers for the entire company :-(
0
 
LVL 83

Expert Comment

by:oBdA
ID: 41908872
Then you need to generate a text file of computer names (one name per line) and use this script:
$ComputerList = 'C:\Temp\ComputerList.txt'
$SourceFile = 'C:\Temp\test.txt'
$TargetFolder = 'C:\Program Files'

$ScriptItem = Get-Item -Path $MyInvocation.MyCommand.Path
$CsvPath = Join-Path -Path $ScriptItem.DirectoryName -ChildPath "$($ScriptItem.BaseName).csv"
$Csv = If (Test-Path -Path $CsvPath) {
	"Continuing from  $($CsvPath) ..." | Write-Host -ForegroundColor White
	Import-Csv -Path $CsvPath
} Else {
	"Retrieving AD computer from file '$($ComputerList)' ..." | Write-Host -ForegroundColor White
	Get-Content -Path $ComputerList | 
		Select-Object @{n='Name'; e={$_.Split('.')[0]}}, @{n='DNSHostName'; e={$_}}, @{n='Processed'; e={'False'}},  @{n='Error'; e={''}}, DistinguishedName |
		Sort-Object -Property Name
}
ForEach ($Computer In $Csv) {
	"Processing $($Computer.Name) ... " | Write-Host -ForegroundColor White -NoNewline
	If ($Computer.Processed -eq 'True') {
		'already processed.' | Write-Host -ForegroundColor Green
	} Else {
		If (Test-Connection -ComputerName $Computer.DNSHostName -Count 2 -Quiet) {
			'online, copying ... ' | Write-Host -ForegroundColor Yellow -NoNewline
			Try {
				Copy-Item -Path $SourceFile -Destination "\\$($Computer.DNSHostName)\$($TargetFolder.Replace(':', '$'))" -Force -ErrorAction Stop
				$Computer.Processed = 'True'
				'OK.' | Write-Host -ForegroundColor Green
			} Catch {
				$Computer.Error = $_.Exception.Message
				$Computer.Error | Write-Host -ForegroundColor Red
			}
		} Else {
			$Computer.Error = 'Offline'
			$Computer.Error | Write-Host -ForegroundColor Red
		}
	}
}
$Csv | Export-Csv -Path $CsvPath -NoTypeInformation
$Csv | Format-Table -AutoSize

Open in new window

0
 

Author Comment

by:mercuriousu2
ID: 41908998
Excellent, many thanks. I will be able to amend this for future use as well :-)

Appreciate the assistance
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For many of us, the  holiday season kindles the natural urge to give back to our friends, family members and communities. While it's easy for friends to notice the impact of such deeds, understanding the contributions of businesses and enterprises i…
A brief introduction to what I consider to be the best editor for PowerShell.
This Micro Tutorial will give you a basic overview of Windows DVD Burner through its features and interface. This will be demonstrated using Windows 7 operating system.
After creating this article (http://www.experts-exchange.com/articles/23699/Setup-Mikrotik-routers-with-OSPF.html), I decided to make a video (no audio) to show you how to configure the routers and run some trace routes and pings between the 7 sites…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question