Quantcast
Channel: PowerShell.org » All Posts
Viewing all 13067 articles
Browse latest View live

Edit aspnet.config file

$
0
0

Hi Team,

I am working on a server configuration where aspnet.config file need to be edited and some tags needs to be added to the runtime section of the file using DSC. Do we have any existing resource using which I can easily add tags or I have to follow some other steps.

Please guide me.

Thanks,
Aravinda


Reply To: How do I list ActiveSync device users by manager

$
0
0

Thanks Jack. I will play with this and see what come out.

If it works the way I want it to, I will post the script here for all to see and hopefully refine further.

Thanks again

Printer Mapping

$
0
0

I'm currently borrowing from one of Bo Prox's scripts to migrate printer shares and it works great! The only thing I'm having trouble with is logic to guarantee that although the print server name changes, the print share remains the default.

Any ideas?

Paul

Function Switch-Printer
{
	Param [
		$oldprintserver,
		$oldPrintbyIP,
		$newPrintServer,
		$PrinterLog = "c:\printers.csv"
	]
 
 
	Try
	{
		LogWrite ["{0}: Checking for printers mapped to old print server" -f $Env:USERNAME]
		$printers = @[Get-WmiObject -Class Win32_Printer | where { $_.Systemname -like "*$oldprintserver*" -or $_.SystemName -like "*$oldPrintbyIP*" }]
 
		If [$printers.count -gt 0]
		{
			ForEach [$printer in $printers]
			{
				LogWrite ["{0}: Replacing with new print server name: {1}" -f $Printer.Name, $newPrintServer]
 
 
				If [$printer.name -like "*$oldprintserver*"] { $newPrinter = $printer.Name -replace $oldprintserver, $newPrintServer }
 
				If [$printer.name -like "*$oldPrintbyIP*"] { $newPrinter = $printer.Name -replace $oldPrintbyIP, $newPrintServer }
 
 
				$returnValue = [[wmiclass]"Win32_Printer"].AddPrinterConnection[$newPrinter].ReturnValue
				If [$returnValue -eq 0]
				{
					"{0},{1},{2},{3},{4},{5}" -f $Env:COMPUTERNAME,
					$env:USERNAME,
					$newPrinter,
					$returnValue,
					[Get-Date],
					"Added Printer" | Out-File -FilePath $PrinterLog -Append -Encoding ASCII
					LogWrite ["{0}: Removing" -f $printer.name]
					$printer.Delete[]
					"{0},{1},{2},{3},{4},{5}" -f $Env:COMPUTERNAME,
					$env:USERNAME,
					$printer.Name,
					$returnValue,
					[Get-Date],
					"Removed Printer" | Out-File -FilePath $PrinterLog -Append -Encoding ASCII
				}
				Else
				{
					LogWrite ["{0} returned error code: {1}" -f $newPrinter, $returnValue] -Verbose
					"{0},{1},{2},{3},{4},{5}" -f $Env:COMPUTERNAME,
					$env:USERNAME,
					$newPrinter,
					$returnValue,
					[Get-Date],
					"Error Adding Printer" | Out-File -FilePath $PrinterLog -Append -Encoding ASCII
				}
			}
		}
	}
	Catch
	{
		"{0},{1},{2},{3},{4},{5}" -f $Env:COMPUTERNAME,
		$env:USERNAME,
		"WMIERROR",
		$_.Exception.Message,
		[Get-Date],
		"Error Querying Printers" | Out-File -FilePath $PrinterLog -Append -Encoding ASCII
	}
 
 
}

Problem with DoCMD.runsql

$
0
0

I'm still new to Powershell and am working on the following script. I have an Access database with multiple tables. I have multiple Excel workbooks, using PowerQuery to retrieve new data via and API, that will be loaded into the correct Access tables. Spreadsheets and Tables have the same name. So far I want the script to delete the data in the tables then update with data from the Excel spreadsheet. I have been able to work out how to import multiple files into the corresponding tables. When I tried to add the code to delete the data first, I ran into issues. Currently the 'delete' sql will only delete 1 table, not all 3 in my test code. If I hard code the table names the code will run correctly and delete from all 3 tables, but with a variable only 1 of the tables is emptied.

Hope this formatted correctly…

Thanks in advance for any guidance.
Rich

$acImport = 0 
$acSpreadsheetTypeExcel12 = 9 
# list of excel workbooks with eb data
# add script "get-childitem" to replace hardcoded values
$table = 'ScheduleTasks', 'Budget', 'Process_CBVR'
 
$sql = "DELETE * FROM $($t);"
 
$a = New-Object -Comobject Access.Application 
$a.OpenCurrentDatabase("\\kpfs1\Public\shares\cfo\fds\CFM\CFM Shared Files\Reports\database\eBAPI_be.accdb") 
 
#loop table/spreadhsheet list through import step 
 
ForEach ($t in $table)
{
$a.DoCmd.runsql($sql,$False)
#$a.DoCmd.TransferSpreadsheet($acImport, $acSpreadsheetTypeExcel12, $t, "\\kpfs1\Public\shares\cfo\fds\CFM\CFM Shared Files\Reports\sql source files\tobeimported\$($t).xlsx", $True) 
}
 
$a.Quit()

Reply To: Printer Mapping

$
0
0

Get-Member is your friend! If you do a

$printer | Get-Member

you'll notice it has a property called 'Default' (contains true or false) and a method called 'SetDefaultPrinter'. With these two items all you have to do is invoke the SetDefaultPrinter method on the newly created printer if the old printer object's Default parameter was "true".

if ($returnValue -eq 0){
    if ($printer.default){ Get-WmiObject -Class win32_printer -Filter "Name like '$newprinter'" | Invoke-WmiMethod -Name SetDefaultPrinter }
    ##Write to log##
    $printer.Delete()
}

Reply To: Problem with DoCMD.runsql

$
0
0

What does the output of $table look like when you load it with Get-ChildItem?

Reply To: Printer Mapping

$
0
0

Jack,

Thanks a mill, I'm going to try this tonight!

Adding groups to folders

$
0
0

I need to add groups to folders where the group name gives a hint as to what folder it should be added so say I have a

system
application
logs
… etc.

folders and then

System Group
Application Group
Logs Group
….etc.

I know that I can do the testing with
FunctionFolderTest($folders){
foreach($folder in $folders){
if(!(Test-Path $folder)){
New-Item -Path $folder -ItemType Directory -force
}
}
}

And for the groups

function LocalGroupExist($groupName)
{
return [ADSI]::Exists("WinNT://$env:COMPUTERNAME/$groupName,group")
}
Which can be run through for each.

Assuming the groups exist and the folders exist having a list of both in a txt file how do I go about adding the right group to the right folder?


Reply To: Adding groups to folders

$
0
0

I assume you mean "adding a group to the folder's ACL." Check out the Get-ACL and Set-ACL commands; natively, they're the only real way to manipulate ACLs.

Reply To: Edit aspnet.config file

$
0
0

The configuration file is just XML, but I've not run across a resource specifically for ASP.NET. You would need to build out your own generic XML resource or an ASP.NET-specific resource.

Reply To: Automate GPO settings

$
0
0

First of all thanks for the script it works as a charm,

Now to my question:

I'm not a powershell master nor a C# master, but i would like to delete a reg entry in the local policy file.
I found the "DeleteValue" in the PolFilEditor.cs but i have tried to use in the powershell script provided here but it does not work.
Do you have any suggestion how-to accomplish this?

Brgds,
Joel

Bulk ADGroup Import Performance

$
0
0

Hello all,

I'm having an issue that I understand but I'm not really sure how to make things bigger. I need to import a large group of users into an AD group that they may already be a part of. The problem is that even with 500ish computer objects, this script is so slow! I've heard of ways to import something like group membership into a temporary table but I'm not 100% sure how to build that out. Possible work flow?…

1. Import CSV for list of computers
2. Import ADGroupMembership and store as a temporary table
3. If $_.computer exists in temp table, write to log ":)"
4. If $_.computer doesn't exist in temp table, add to ad group and write to log unless computer exists in exception list (had to through that one in ;))

Here is what I have so far….

# Connect Quest
Add-PSSnapin quest.active*
 
#var declaration
 
$date = (Get-Date -f MMddyy)
$transcript = "./$date.log"
$csvpath = "./computers.csv"
 
Start-Transcript -Path $transcript
 
If ((Test-Path -Path $csvpath) -eq $false)
{
 
	Write-Verbose -Verbose "FILE NOT FOUND!! $csvpath"
}
Elseif ((Test-Path -Path $csvpath) -eq $true)
{
 
	$Computers = Import-Csv -Path $csvpath
	$Exceptions = @("Junk1","Junk2")
 
 
	# Loop through computers
	$Computers | ForEach-Object {
 
		If ($Exceptions -contains $_.ComputerName)
		{
 
			#give warning
			Write-Warning "Skipping $($_.ComputerName) due to manually specified exception"
 
		}
		else
		{
			# Add computer as member to the group with verbose console output and nulling output object
			Add-QADGroupMember -Identity 'SomeGroup' -Member $_.ComputerName -Verbose | Out-Null
		} # if/else
 
 
	} # End computers Loop
 
	#Disconnect Quest
	Disconnect-QADService -Service vwoaahvp199.vwoa.na.vwg -proxy
	Remove-PSSnapin quest.active*
 
}
 
Stop-Transcript

Reply To: Adding groups to folders

$
0
0

Pretty much so. Thanks for the tip.

Reply To: Bulk ADGroup Import Performance

$
0
0

Let me maybe re-state the problem to make sure I have it.

You have List A, and you want to make AD look like List A.

This involves enumerating List A, checking each item in it, and fixing the items that aren't right (e.g., computer isn't a member of a group).

Your slow bits are going to be querying AD for each item in List A, and then performing the actual add-to-group operation.

Your proposed alternative is simply dumping all the group memberships from AD in one operation, and putting them in (say) SQL Server Express, which cane queried much more quickly than AD.

That's probably a valid approach to at least try. You can look at one of our ebooks, "Creating Historical and Trend Reports," for some code examples on how to use PowerShell to query SQL Server. A local Express install should work quite well for this. You'll have to query the group memberships, enumerate them, and fire off a SQL INSERT statement for each one. That'll populate your database. Then, your script can check against SQL Server rather than AD directly. When you find a missing item, you add it to AD appropriately.

I can't say how MUCH this will speed things up – it's something you kind of have to test to see, because there are a lot of environmental specifics.

Reply To: Bulk ADGroup Import Performance

$
0
0

Don,

Yes you have the idea. I actually found what I was trying remember also….http://powershell.org/wp/forums/topic/csv-to-csv/

Dave provided a method for "building" a search base when I was attempting to generate an AD report that sped things up 80% at least…just have to remember how to use it…:)

Dave Wyatt · October 20, 2014 at 9:54 am #19867 Reply | Quote

Dave Wyatt
Moderator
Topics: 14
Replies: 1491

You can make a single call to Get-Qaduser which stores the information you need in memory, then use that information to perform the CSV transformations. Depending on how many users are in your domain, though, you may run into memory problems here. (Memory usage and execution time are often competing with each other in these situations.)

You can try something like this:

$csv= 'c:\somefolder\master.csv'

$userTable = @{}

filter UpdateUserTable
{
$userTable[$_.SamAccountName] = [pscustomobject] @{
FirstName = $_.FirstName
LastName = $_.LastName
Email = $_.Email
CostCenter = $_.PhysicalDeliveryOfficeName
}
}

Get-QADUser | UpdateUserTable

filter UpdateObject
{
$csvEntry = $_
$userEntry = $userTable[$csvEntry.UserID]

[pscustomobject] @{
Computer = $csvEntry.Computer
UserID = $csvEntry.UserID
FirstName = $userEntry.FirstName
LastName = $userEntry.LastName
Email = $userEntry.Email
'Cost Center' = $userEntry.CostCenter
Date = $csvEntry.Date
DeviceID = $csvEntry.DeviceID
ProviderName = $csvEntry.ProviderName
DriveType = $csvEntry.DriveType
}
}

Import-Csv $csv |
UpdateObject |
Export-Csv -Path 'C:\somefolder\master_final.csv' -N


Object comparison

$
0
0

Hey guys, would really appreciate some help here.
I'm building a powershell script to retrieve and delete adcomputers which haven't logged in for a certain amount of time. However, there are some computer which I use once or twice a year which I do not want to remove. I have therefore created a white list.
My script is as follows:

# get list of computers
$computerList = Get-ADComputer -Filter {LastLogonDate -lt $time} -Properties Name,LastLogonDate | select -Property Name,LastLogonDate
# import white list
$importedWhiteList = Import-Clixml -Path "$filePath\whitelist.xml"
#check which computer are not in the white list and add them to another list
$filteredList = foreach($c in $computerList) {if($importedWhiteList -notcontains $c) {$c}
# I then delete the old computers from the filtered list…..

The issue is that even if $c is a computer which I know exists in the white list, it still comes out as false, as if the computer is not there.
If I pipe a computer from the $importedWhiteList | gm it is the same type object as if I pipe from get-adcomputer | gm and the same object as $c | gm
The white list was created by piping get-adcomputer -filter…. | export-clixml , it was not created manually so I don't think the list is the issue.

Help would be really appreciated. I'm new to powershell, so if you have a better practice way of solving my issue I would really appreciate that too.

Thanks.

Reply To: Object comparison

$
0
0

The objects that get re-hydrated by Import-CliXML aren't precisely the same as what's produced by Get-ADComputer. You might try running Get-ADComputer to Export-CliXML, and then comparing imported vs. imported, rather than imported vs. live.

Reply To: Object comparison

$
0
0

Hi Don

Thanks for helping. Is there a way to specify the parameter which the comparison uses? for example, not to compare them as objects but to compare the computer.Name as strings?

Reply To: Object comparison

$
0
0

Not so much. It actually does an every-property comparison. If you want to do something else, it gets more complex and you end up writing your own code. Me, I'd probably just create arrays of strings and then use -contains on those.

Creating a new VM and VHD with HyperV

$
0
0

I have this script that creates a new VM, creates a VHD, points to an ISO and starts installing. This script works perfectly:

New-VM -Name "Server2012" -MemoryStartupBytes 512MB -path C:\HyperV
New-VHD -path C:\HyperVStorage\Server2012\Server2012dynamic.vhdx -SizeBytes 60GB -Dynamic
Add-VMHarddiskDrive -VMName Server2012 -path C:\HyperVStorage\Server2012\Server2012dynamic.vhdx
Set-VMdvddrive -VMname Server2012 -ControllerNumber 1 -path C:\users\dbrooks\desktop\en_windows_server_2012_x64_dvd_915478.iso
Add-VMNetworkAdapter -VMName Server2012 -SwitchName vSwitch1
Start-VM Server2012

—————————————————-
I would like to be able to input the VM name, memory size, the harddrive size. I'm running into an error when trying to give it a specified amount of RAM and HDD. Any suggestions?

function New-Server2012r2VM
{
Param(
[int]$RAM,
[string]$Name,
[int]$HDD
)
$Name = Read-Host 'Name your VM:'
$RAM = Read-Host 'How much RAM?'
$HDD = Read-Host 'How much storage?'
New-VM -Name $Name -MemoryStartupBytes ($RAM * 1gb) -path C:\HyperV\$Name
New-VHD -path C:\HyperVStorage\$Name.vhdx -SizeBytes ($HDD * 1gb) -Dynamic
Add-VMHarddiskDrive -VMName $Name -path C:\HyperVStorage\$Name\$Name.vhdx
Set-VMdvddrive -VMname $Name -ControllerNumber 1 -path C:\users\dbrooks\desktop\en_windows_server_2012_x64_dvd_915478.iso
Add-VMNetworkAdapter -VMName $Name -SwitchName vSwitch1
Start-VM $Name

Viewing all 13067 articles
Browse latest View live