Powershell and gpo inheritance
Gods of comm, hear my plea!
I've been playing around with powershell, trying to make a script to pull gpo settings and compare it to gpo inheritance on all objects upon my network to show me where there's discrepancies// doubly applied coverage on said objects
but I have got nowhere at all, and I got there fast. If anyone has anything, it would be a great help
if anyone has any direction, it would be a great help.
Thankyou, and may Google always be there for you
GP inheritance is not set on the GPO it is set on the container. A GPO can be linked to many containers. THe GOP link determines how the GPO is applied.
To learn about and understand GP you can post in the GP forum.
https://technet.microsoft.com/en-us/library/ee461032.aspx
¯\_(ツ)_/¯
Similar Messages
-
Powershell Edit GPO deploy Printer
Hi Guys,
I tried to make Powershell script with GUI to add printers to print server. I would like that my super user just write new printer name and IP adresse in textbox and script suppose to add printer to printer server, create new ADGroupe to each
printer (name of groupe = printer name), create GPO to each AD Groupe (GPO name = <Printer name>64bit)with premissions level assign to the AD group.
Everything is working fine, script is adding printer, adding port for the printer, creating AD Group, creating (empty) GPO, i don´t know how to edit gpo via powershell and deploy printer to the AD Group.
Have you got any suggetions?
to make a GUI i followed this guide:
blogs.technet.com/b/heyscriptingguy/archive/2014/08/01/i-39-ve-got-a-powershell-secret-adding-a-gui-to-scripts.(a)(s)(p)(x)
my PS script code :
Import-Module Activedirectory
Import-Module Grouppolicy
.\loadDialog.ps1 -XamlPath ".\MainWindow.xaml"
Get-PrinterDriver | ForEach-Object {$x=$cbPrinterDriver.Items.Add($_.Name)}
$tbPrinterName.add_TextChanged({
$tbADGroupeName.Text = "PRN-"+$tbPrinterName.Text
$tbGPOName.Text = $tbPrinterName.Text+"-64bit"
$tbSkoleName.Text = $tbPrinterName.Text.Substring(0,[system.math]::min(3,$tbPrinterName.Text.Length))
$btnCreate.add_Click({
$btnCreate.IsEnabled = $FALSE
$PrinterName = $tbPrinterName.Text
$PrinterIP = $tbPrinterIP.Text
$ADGroupeName = $tbADGroupeName.Text
$GPOName = $tbGPOName.Text
$Driver = $cbPrinterDriver.SelectedItem.ToString()
$SkoleName = $tbSkoleName.Text
$NL = "`r`n"
Add-PrinterPort -PrinterHostAddress "$PrinterIP" -Name "$PrinterIP"
$tbInfo.AppendText("Printer port created: $PrinterIP$NL")
Add-Printer -Name "$PrinterName" -PortName $PrinterIP -DriverName "$Driver" -shared -ShareName "$PrinterName" -Published
$tbInfo.AppendText("Printer created: $PrinterName$NL")
New-ADGroup -name "$ADGroupeName" -GroupScope Global -GroupCategory Security -DisplayName "$PrinterName" -path "ou=XXXXXXXXXX,ou=$SkoleName,ou=XXXX,ou=XXXXX,dc=XXXXXXX,dc=XXXX" -Description "Members of this group get $PrinterName
added"
$tbInfo.AppendText("Active Directory group created: $ADGroupeName$NL")
New-GPO -Name "$GPOName" | new-gplink -target "ou=XXXXXXX,ou=$SkoleName,ou=XXXXXX,ou=XXXXX,dc=XXXXXX,dc=XXXX"
$tbInfo.AppendText("GPO created: $GPOName$NL")
Set-GPPermission -name "$GPOName" -permissionlevel gporead -replace -targetname "Authenticated Users" -targettype Group
Set-GPPermission -name "$GPOName" -permissionlevel gpoapply -replace -targetname "$ADGroupeName" -targettype Group
$tbInfo.AppendText("GPO permissions set.$NL")
$tbInfo.AppendText("Done!.$NL")
#$btnCreate.IsEnabled = $TRUE
$xamGUI.ShowDialog() | out-null
My loadDialog.ps1
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$XamlPath
[xml]$Global:xmlWPF = Get-Content -Path $XamlPath
#Add WPF and Windows Forms assemblies
try{
Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms
} catch {
Throw "Failed to load Windows Presentation Framework assemblies."
#Create the XAML reader using a new XML node reader
$Global:xamGUI = [Windows.Markup.XamlReader]::Load((new-object System.Xml.XmlNodeReader $xmlWPF))
#Create hooks to each named object in the XAML
$xmlWPF.SelectNodes("//*[@Name]") | %{
Set-Variable -Name ($_.Name) -Value $xamGUI.FindName($_.Name) -Scope Global
My MainWindow.xaml
<Window
Title="Pirinter tool" Height="413.298" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="23*"/>
<ColumnDefinition Width="10*"/>
<ColumnDefinition Width="28*"/>
<ColumnDefinition Width="21*"/>
<ColumnDefinition Width="126*"/>
<ColumnDefinition Width="24*"/>
<ColumnDefinition Width="285*"/>
</Grid.ColumnDefinitions>
<TextBox Name="tbADGroupeName" HorizontalAlignment="Left" Height="23" Margin="68,148,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top"
Width="120" Grid.Column="4" Grid.ColumnSpan="3"/>
<TextBox Name="tbPrinterIP" HorizontalAlignment="Left" Height="23" Margin="68,76,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"
Grid.Column="4" Grid.ColumnSpan="3"/>
<TextBox Name="tbPrinterName" HorizontalAlignment="Left" Height="23" Margin="68,45,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"
RenderTransformOrigin="0.049,3.073" Grid.Column="4" Grid.ColumnSpan="3"/>
<Label Content="AD Groupe" HorizontalAlignment="Left" Margin="11,148,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.599,-0.868" Grid.ColumnSpan="3"
Grid.Column="2"/>
<Label Content="IP" HorizontalAlignment="Left" Margin="11,72,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.435,0.329" Grid.ColumnSpan="2" Grid.Column="2"/>
<Label Content="Printer Name" HorizontalAlignment="Left" Margin="11,41,0,0" VerticalAlignment="Top" Grid.ColumnSpan="3" Grid.Column="2"/>
<TextBox Name="tbGPOName" HorizontalAlignment="Left" Height="23" Margin="68,185,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top"
Width="120" Grid.Column="4" Grid.ColumnSpan="3"/>
<ComboBox Name="cbPrinterDriver" HorizontalAlignment="Left" Margin="67,114,0,0" VerticalAlignment="Top" Width="169" Grid.Column="4" Grid.ColumnSpan="3"/>
<Label Content="Driver" HorizontalAlignment="Left" Margin="10,114,0,0" VerticalAlignment="Top" Grid.ColumnSpan="3" Grid.Column="2"/>
<Label Content="GPO Name" HorizontalAlignment="Left" Margin="11,182,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.599,-0.868" Grid.ColumnSpan="3"
Grid.Column="2"/>
<Button Name="btnCancel" Content="Cancel" HorizontalAlignment="Left" Margin="68,339,0,0" VerticalAlignment="Top" Width="75" Grid.Column="4"
IsCancel="True" Grid.ColumnSpan="2" Height="33"/>
<Button Name="btnCreate" Content="Create" HorizontalAlignment="Left" Margin="45,339,0,0" VerticalAlignment="Top" Width="75" Grid.Column="6"
IsDefault="True" Height="33"/>
<TextBox Name="tbSkoleName" Grid.ColumnSpan="3" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"
Grid.Column="4" Margin="68,227,0,0"/>
<Label Content="Skole" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="2" Margin="15,224,0,0" Grid.ColumnSpan="3" Width="76"/>
<TextBox Name="tbInfo" Grid.Column="2" HorizontalAlignment="Left" Height="79" Margin="0,255,0,0" TextWrapping="Wrap" VerticalAlignment="Top"
Width="447" IsReadOnly="True" Grid.ColumnSpan="5" ScrollViewer.CanContentScroll="True" SelectionBrush="{x:Null}" VerticalScrollBarVisibility="Auto"/>
</Grid>
</Window>
I will be gratefull for any help.Print Manager does all of that and is already installed in Windows. Why do you want to recreate it? It sets up the printers and the GPO for assigning the printers.
Start here:
https://technet.microsoft.com/en-us/library/cc753109(v=ws.10).aspx
Post questions about printer management in the server forum for you OS.
¯\_(ツ)_/¯ -
Powershell and Sharepoint workflow
Oke I got this a really strange problem.
I got a ps1 file with powershell code in it. The code create a list item in sharepoint with all information and on the information I want to trigger a workflow.
But now if I activated the ps1 file powershell as administrator(automatic) and then run the code thats in the file. But no Workflow tiggered in sharepoint the workflow is automatic activated when a new item is created.
And the strange thing is if I open my script with notepad copy the text insert it into powershell and press enter my workflow runs...
So any1 have an idea to fix this?Below is code snippet in c#.net for fetching all the attachements for a specific list item.
try
// Set the Site Url
SPSite objSite = new SPSite("http://Testsite/");
using (SPWeb objWeb = objSite.OpenWeb())
objWeb.AllowUnsafeUpdates = true;
// Get the List
SPList objList = objWeb.Lists["MyList"];
// Get the item by ID
SPListItem objItem = objList.GetItemById(1);
// Get the attachments of the item
SPAttachmentCollection objAttchments = objItem.Attachments;
// Iterate the attachments
foreach (string fileName in objItem.Attachments)
// Perform action on
the extracted attachment
Hope it
answer the questions.Any suggestions are appreciated.
Cheers, Eliza -
Hi,
I have a little problem with powershell and "contains"
In this situation works well and return "true"
$test = "where is the word"
($test).Contains("word")
but in this other return always "false"
$test = Get-Process
($test).Contains("winlogon")
Why?
Thanks
Andrea Gallazzi
windowserver.it - blog:
andreagx.blogspot.com
This posting is provided AS IS with no warranties, and confers no rights.Hi,
Try looking at the ProcessName property:
PS C:\Scripts\PowerShell Scripts\Misc Testing\1-10-2014> $test = Get-Process
PS C:\Scripts\PowerShell Scripts\Misc Testing\1-10-2014> $test.ProcessName.Contains('winlogon')
True
EDIT: If I remember correctly, I believe this requires PS3+ though.
EDIT2: This will work if you only have v2 (I'm sure there's a better way to do this, but this'll work in a pinch):
PS C:\> $found = $false
PS C:\> $test = Get-Process
PS C:\> $test | ForEach { If ($_.ProcessName.Contains('winlogon')) { $found = $true } }
PS C:\> $found
True
Don't retire TechNet! -
(Don't give up yet - 12,575+ strong and growing) -
Powershell and robocopy pausing
I am using powershell and Robycopy to move files from volume to another. Server 2008R2 iSCSI volumes on
It seems that powershell window occasionally pauses. When I hit enter the process just starts up again. It is taking more that a day to move 2TB of data. Command is: robocopy h:\ j:\ /e /mov /R:5 /W:10 /log:c:\movedidson.log /TEE /NP /ETA
Also an empty folder remains on the first drive. Why is it not deleting the folders after it copies.
Thanks,
MarkHi Mark,
Total shot in the dark, perhaps this will help:
http://social.technet.microsoft.com/Forums/en-US/ab36656d-bfbd-4ff1-ac7a-84e2ac975c1d/powershell-hangs?forum=winserverpowershell
EDIT: Also, this isn't exactly a PowerShell question. You may be using PowerShell to launch robocopy, but that's pretty much the end of anything PowerShell related.
Don't retire TechNet! -
(Don't give up yet - 12,575+ strong and growing) -
I've updated the Groups Description (About Me) using the GUI / Website. Then running a script to output the Group's Description like:
$siteUrl = "site url"
$web = Get-SPWeb $siteUrl
$web.SiteGroups
$web.Dispose()
The description doesn't change. I can then update the Description of the group using PowerShell and close the window then and run the above code the changes are reflected. However, the GUI / Website doesn't have the changes. Very odd!
raymHi raym,
Does this still work for you?
I am rapidly losing my mind over this...
Is there anything that you left out or perhaps assumed that Noobs (like myself) would already know or have considered? ;)
I have tried about ten different solutions and Nothing works.
All I get is plain text.
Set
Group Description to HTML via PS Script (This will explain what I have - from my original request of the same)
Please!! If anyone can shed some light on this before I scrap SP altogether and revert back to DOS. It is the Only thing of Microsoft that actually worked. Oh! and AOE2!! ;)
TIA,
Neil -
Hi there,
I've recently deployed 2 GPOs in a test environment that create and map user homefolders, as per http://www.alexcomputerbubble.com/using-group-policy-preferences-gpp-to-map-user-home-drive/
I've noticed that all PCs equipped with SSDs fail at mounting the home letter drive until restarted at least 3 times.
No such issues observed with PCs equipped with regular HDDs.
Before someone throws the infamous "Computer Configuration\Administrative Templates\System\Logon\ Always wait for the network at computer startup and logon" resolution, know that it's been tried and produced no results.
I have encountered these SSD issues in the past when creating GPOs, logon scripts, and each time i NEVER was able to find any sensible explanation as to why this is such a stinger in my bubble. After trying many common suggestions, like the one mentioned above,
it always ends up with: SSDs are just too bloody fast, and GPOs/logon scripts execute before network resource has a chance to become available. SSDs have become so common that arguably it makes little sense to consider HDDs as a primary drive in any worktation.
My company runs 90% SSDs on 90 PCs.
I am running Windows Server 2008 R2 with Windows 7 clients.
Is Windows 2008/7 just not able/meant to deal with SSDs in a corporate environment? This is my runt for the day:)Check if the is a bios update or SSD update you can install.
Try this hot fix: http://support.microsoft.com/kb/2459530
Look at this post, there is a similar issue to yours. they opened a case at MS and ended up with creating a host entry in DNS for the NetBios domain name:
http://community.spiceworks.com/topic/291388-windows-doesn-t-recognize-domain-until-60-seconds-after-startup
Please take a moment to Vote as Helpful and/or Mark as Answer where applicable. Thanks. -
Windows Powershell and HP Open Test Architect (TDApiOle80)
I'm not sure that this is the correct forum to place this in. Please feel free to move it if needed...
I have a task to create a new script using powershell and the OTA. When trying to log into quality center via the open test architecture in powershell I get this error.
At my computer char:22+ $td.InitConnectionEx $qualityCenterLink+ ~~~~~~~~~~~~~~~~Unexpected token '$qualityCenterLink' in expression or statement.
At my computer char:11+ $td.Login $qualityCenterUsername, $qualityCenterPassword+
~~~~~~~~~~~~~~~~~~~~~~
This is the code that I am using.
$td = New-Object -ComObject "TDApiOle80.TDConnection"
$td.InitConnectionEx $qualityCenterLink
$td.Login $qualityCenterUsername, $qualityCenterPassword
This code currently works in a script written with VBscript. I am just modifying the td variable to use powershell instead of vbscript. Do you all have any idea what it is that is causing this not to run? Also, Is powershell compatible with the OTA? I am assuming
so only because the OTA is a COM package.it appears it doesn't like the formatting. It doesn't know how to handle the varibles
Powershell thinks thinks these are 2 variable next to each other
$td.InitConnectionEx $qualityCenterLinkmaybe put $td.InitConnectionEx($qualityCenterLink)$td.Login $qualityCenterUsername, $qualityCenterPasswordPowershell thinks thinks these are variable next to each other, with a comma separating two of themmaybe put $td.Login ($qualityCenterUsername, $qualityPasswrod)Maybe you can do $td | get-member, may that will show you how the arguments should look. I have neverused the OTA, just guessing here. -
Learning about Powershell and IPV6 for 70-410
I was reading up on the 70-410 exam as I am trying to study up before I take it at the end of the month and it appears knowing Powershell and IPv6 is necessary. Alot of the links I've searched don't seem to cover how Powershell interacts with managing
a Server 2012 R2 machine and cover things like scripting, etc. Also, I want to know how would one study IPv6 since this is also important to the exam.Hi Matthew,
For IPV6 you can read:
" http://technet.microsoft.com/en-us/library/dn610908.aspx "
The best way to study PowerShell is to practice with PowerShell (i.e. Configure the Server Core). This is what I did. :) Good Luck
Greets,
Kenan
P.s. : " Training Guide: Installing and Configuring Windows Server 2012 " is a good book that can help you for preparing for 70-410 exam -
Hi -
I'm wondering if anyone has had any luck/experience with getting DB2 command file scripts to run via Powershell?
In addition, I have a situation where I need to query two different DB2 databases for information. First database has a list of customers that use a GUID for their identification. I would like to run a Powershell/DB2 script to dump the
list of customers to a .CSV file.
I then need to hop over to another server and would like to run another Powershell/DB2 script that basically reads the .CSV file with list of customers and executes against another table on current server and matches the customer GUID identification against
the GUID's in the current DB2 tables. If these two databases where on the same servers, I could probably do a JOIN or something, but since they're not -- I have do to this mickey-mouse routine.
Anyway, if anyone has any ideas, it would be greatly appreciated. Trying to match up GUIDs to determine what customer is what is no fun and very tedious.
I didn't write this software, do don't blame me! ;-)I've done a little with DB2 and powershell, the trick is to open the DB2 prompt, and then run powershell, that will allow you to run db2 commands in powershell.. if you run powershell and then db2, it doesn’t work...
im not sure you really need that, you could probably just use ODBC or some other .NET database method.
I've almost been able to rip the provider out of the a DB2 service pack so that I can run queries remotely. I've done it, just not sure exactly how I did it so I cant provide steps yet.
very interested in the work youve done here. do you have an update on this? -
Hi guys,
I have to modify a registry key with GPO for my IT enviroment (for disabling "Network" in the navigation pane --> like for a kiosk workstation), but i got some trouble that i can't figure out...
The key that i have to change is (inside this direcotry) in this location:
HKEY_CLASSES_ROOT\CLSID\{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}\ShellFolder
And i know that there is like an alyas for this registry key:
HKLM:\SOFTWARE\Classes\CLSID\"{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}"\ShellFolder
So I just tryed to change it with GPO (modify registry key) but there is a permission problem (admin can only read and not write inside this directory).. Therefore i decided to create a script that takes ACL from an exported key in a shared location (with
right permissions), and "Paste" them in the "ShellFolder" for making work my gpo law. But i got some errors...
I tryed to use this "easy" powershell script:
PS C:\>$Stdkey= Get-Acl 'C:\Stdkey.reg' ---> Example: Random key in a random location
PS C:\>Set-Acl -Path HKLM:\SOFTWARE\Classes\CLSID\"{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}"\ShellFolder -AclObject $StdkeyBut it doesn't work.. it gives me an error about an invalid argument "securityDescriptor" (but as you can see this script doesn't call or changes nothing)Did I make something wrong? Is there a better way for doing it (I mean with another powershell script)?Thanks.Th3nshi.NB: English is not my main language, I hope that you can understand :)Hi Th3nshi,
For the GPO part in this issue, please post in the dedicated Group Policy forum for more efficient support, and changing registry value or the registry permission is on your own risk:
https://social.technet.microsoft.com/Forums/windowsserver/en-US/home?forum=winserverGP
However, To change the permission of registry value via powershell, I checked the registry and found its permission is inherited by parent by default, and the owner is system:
To change the permission we need takeownership and add current logon user has full controll permission, I tested the script below:
function enable-privilege {
param(
## The privilege to adjust. This set is taken from
## http://msdn.microsoft.com/en-us/library/bb530716(VS.85).aspx
[ValidateSet(
"SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege",
"SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege",
"SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege",
"SeDebugPrivilege", "SeEnableDelegationPrivilege", "SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege",
"SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege", "SeLoadDriverPrivilege",
"SeLockMemoryPrivilege", "SeMachineAccountPrivilege", "SeManageVolumePrivilege",
"SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege",
"SeRestorePrivilege", "SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege",
"SeSystemEnvironmentPrivilege", "SeSystemProfilePrivilege", "SeSystemtimePrivilege",
"SeTakeOwnershipPrivilege", "SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege",
"SeUndockPrivilege", "SeUnsolicitedInputPrivilege")]
$Privilege,
## The process on which to adjust the privilege. Defaults to the current process.
$ProcessId = $pid,
## Switch to disable the privilege, rather than enable it.
[Switch] $Disable
## Taken from P/Invoke.NET with minor adjustments.
$definition = @'
using System;
using System.Runtime.InteropServices;
public class AdjPriv
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
public int Count;
public long Luid;
public int Attr;
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
public static bool EnablePrivilege(long processHandle, string privilege, bool disable)
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = new IntPtr(processHandle);
IntPtr htok = IntPtr.Zero;
retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
if(disable)
tp.Attr = SE_PRIVILEGE_DISABLED;
else
tp.Attr = SE_PRIVILEGE_ENABLED;
retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
return retVal;
$processHandle = (Get-Process -id $ProcessId).Handle
$type = Add-Type $definition -PassThru
$type[0]::EnablePrivilege($processHandle, $Privilege, $Disable)
start-sleep 10
enable-privilege SeTakeOwnershipPrivilege
$user= whoami
$path="SOFTWARE\Classes\CLSID\{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}\ShellFolder"
#take ownership
$key1 = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($path,[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::takeownership)
$acl1 = $key1.GetAccessControl()
$me = [System.Security.Principal.NTAccount]$user
$acl1.SetOwner($me)
$acl1
$key1.SetAccessControl($acl1)
#change permission add fullcontrol to logon user
$key2 = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($path,[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::ChangePermissions)
$acl2 = $key2.GetAccessControl()
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ($user,"FullControl","Allow")
$acl2.addAccessRule($rule)
$acl2.access
$key2.SetAccessControl($acl2)
The function enable-privilege is quoted from this article:
Adjusting Token Privileges in PowerShell
If there is anything else regarding this issue, please feel free to post back.
Best Regards,
Anna Wang -
Question about GPO inheritance
See the attached link for a picture of my GPO layout http://tinypic.com/r/18nate/8
My user accounts reside in the "ALG" OU and they logon to Terminal Servers in the "RDS Hosts" OU
Will the "Mapped Drives (new)" GPO not be applied when a user logs into one of the RDS hosts because inheritance is blocked? I think no, because its a GPO lower in the tree, but for some odd reason I don't see it applied when doing a gpupdate /force
& gpresult /R.
The GPO itself is GPP User drive mappingsI found the answer to my own question here (I have two other linked GPOs applied to the same OU with Loopback Replace enabled) Great read!
Loopback Replace
Loopback replace is much easier. During loopback processing in replace mode, the user settings applied to the computer “replace” those applied to the user. In actuality, the Group Policy service skips the GPOs linked to the user’s OU.
Group Policy effectively processes as if user object was in the OU of the computer rather than its current OU."
http://blogs.technet.com/b/askds/archive/2013/02/08/circle-back-to-loopback.aspx -
How to add calendar enries to all users in organization using powershell and EWS.
I am one of the exchange admins for our organization. Every year, we publish academic calendar data to all faculty and staff calendars. We recently updated and migrated from Exchange 2003 to Exchange 2010 which, of course, desupported MAPI and
ADO. The processes we previously used had to be re-written using Exchange Web Services API (EWS). Because I find that powershell is easy to work with, I wanted to integrate the calendar dispersal using powershell.
Having not found much help online using the EWS .NET library in powershell for this purpose, I decided to share my code:
# Bulk load calendar entries script
# Description:
# Script used to deploy Academic Calendar entries to all Exchange account calendars
# Prerequisites:
# Service account must have ApplicationImpersonation ManagementRoleAddisgnment
# New-ManagementRoleAssignment -Name:impersonationRole -Role:ApplicationImpersonation -User:<srv_account>
# Usage:
# .\academicCalendar.ps1 calEntries.csv
# Where calEntries.csv = list of calendar entries to add
Param ([string]$calInputFile = $(throw "Please provide calendar input file parameter..."))
$startTime = Get-Date
$strFileName = "<path to log file>"
if(Test-Path $strFileName)
$logOutFile = Get-Item -path $strFileName
else
$logOutFile = New-Item -type file $strFileName
# Load EWS Managed API library
Import-Module -Name "C:\Program Files\Microsoft\Exchange\Web Services\1.0\Microsoft.Exchange.WebServices.dll"
# Load all Mailboxes
$exchangeUsers = Get-Mailbox -ResultSize Unlimited | Select PrimarySmtpAddress
# Load all calendar Entries
# Input file is in the following format
# StartDate,EndDate,Subject
# 8/29/2011,8/30/2011,First Day of Fall Classes
$calEntries = Import-Csv $calInputFile
# Setup the service for connection
$service = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010)
$service.Url = new-object System.Uri("https://<CAS_server_URL>/ews/exchange.asmx")
$service.Credentials = new-object Microsoft.Exchange.WebServices.Data.WebCredentials("<service_account>","<password>","<domain>")
$totalCount = $exchangeUsers.Count
$currentCount = 0
Write-Output "Exchange Version: $service.RequestedServerVersion"
Write-Output "Mailbox Count: $totalCount"
# Add message to log file
$timeStamp = Get-Date -Format "MM/dd/yyyy hh:mm:ss"
$message = "$timeStamp -- Begin Calendar Deployment `n"
$message += "Total Exchange Accounts: $totalCount"
Add-Content $logOutFile $message
# Perform for each Mailbox
$error.clear()
foreach($mailbox in $exchangeUsers)
$currentCount++
if($mailbox.PrimarySmtpAddress -ne "")
# Output update to screen
$percentComplete = $currentCount/$totalCount
Write-Output $mailbox.PrimarySmtpAddress
"{0:P0}" -f $percentComplete
# Setup mailbox parameters for impersonation
$MailboxName = $mailbox.PrimarySmtpAddress
$iUserID = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$MailboxName)
$service.ImpersonatedUserId = $iUserID
# Indicate which folder to work with
$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar)
$CalendarFolder = [Microsoft.Exchange.WebServices.Data.CalendarFolder]::Bind($service,$folderid)
# For each entry in the input file
$error.clear()
foreach($entry in $calEntries)
# First check to make sure the entry is not already in the calendar
# use a calendarview object to pull the entries for the given date and make sure an entry with the same subject line doesnt already exist
$cvCalendarview = new-object Microsoft.Exchange.WebServices.Data.CalendarView([System.DateTime]($entry.StartDate),[System.DateTime]($entry.EndDate))
$cvCalendarview.PropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$frCalendarResult = $CalendarFolder.FindAppointments($cvCalendarview)
$entryFound = $False
foreach ($appointment in $frCalendarResult.Items)
if($appointment.Subject -eq $entry.Subject)
$entryFound = $True
# If entry was found, then skip this entry
if($entryFound)
$entryFound = $False
else # Create the appointment object and save it to the users calendar
$appt = New-Object Microsoft.Exchange.WebServices.Data.Appointment($service)
$appt.Subject = $entry.Subject
$appt.Start = [System.DateTime]($entry.StartDate)
$appt.End = [System.DateTime]($entry.EndDate) #For AllDayEvent, end date must be after start date
$appt.IsAllDayEvent = $True #Set event as "All Day Event"
$appt.LegacyFreeBusyStatus = "Free" #Make sure free/busy info shows user as "free" rather than "busy"
$appt.IsReminderSet = $False #Make sure reminder is not set to remind the user of the event
$appt.Save([Microsoft.Exchange.WebServices.Data.SendInvitationsMode]::SendToNone)
if($error)
$timeStamp = Get-Date -Format "MM/dd/yyyy hh:mm:ss"
$message = $timeStamp + "...Exception Occurred while processing Save for: `n"
$message += " Account: " + $MailboxName + "`n"
$message += " Subject: " + $entry.Subject + "`n"
$message += " Exception: " + $error[0].Exception + "`n"
Add-Content $logOutFile $message
$error.clear()
if($error)
$error.clear()
else
$message = "" + $MailboxName + "`t Success! `n"
Add-Content $logOutFile $message
Write-Output $currentCount
$endTime = Get-Date
$duration = New-TimeSpan $startTime $endTime
$totalMin = $duration.TotalMinutes
# Build and send email notification upon completion
$body = "The Calendar deployment has completed. `n `n "
$body += "Start Timestamp: $startTime `n "
$body += "End Timestamp: $endTime `n "
$body += "Duration: $totalMin min `n "
$body += "Exchange accounts affected: $currentCount `n"
$smtpServer = "<mysmtpserver>"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg = new-object Net.Mail.MailMessage
$msg.From = "<from_email_address>"
$msg.To.Add("<to_email_address>")
$msg.Subject = "Calendar Deployment"
$msg.Body = $body
$smtp.Send($msg)
# Add closing message to log file
$timeStamp = Get-Date -Format "MM/dd/yyyy hh:mm:ss"
$message = "Accounts affected: $currentCount"
Add-Content $logOutFile $message
$message = "$timeStamp -- Completed in $totalMin min."
Add-Content $logOutFile $message
Please let me know if you think I can make any performance modifications.
Daniel
--Edit-- I have updated the script for Exchange 2010 SP1, also added logging, error checking and email notifications. This new script also checks first to make sure the appointment doesn't already exist before adding it. (To prevent multiple
entries of the same event... Note: This check, although necessary in my opinion, is very time consuming.)Hi Daniel
I am trying to add addition propertires like TV, Copier etc. to Room Mailbox in Exchange 2010 using following commands:-
[PS] C:\Windows\system32>$ResourceConfiguration = Get-ResourceConfig
[PS] C:\Windows\system32>$ResourceConfiguration.ResourcePropertySchema+=("Room/Whiteboard")
Upper two commands run fine but following command gives error:-
[PS] C:\Windows\system32>Set-ResourceConfig -ResourcePropertySchema $ResourceConfiguration.ResourcePropertySchema
The term 'Set-ResourceConfig' is not recognized as the name of a cmdlet, function, script file, or operable program. Ch
eck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:19
+ Set-ResourceConfig <<<< -ResourcePropertySchema $ResourceConfiguration.ResourcePropertySchema
+ CategoryInfo : ObjectNotFound: (Set-ResourceConfig:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I also tried with space after set but still getting error:
[PS] C:\Windows\system32>Set -ResourceConfig -ResourcePropertySchema $ResourceConfiguration.ResourcePropertySchema
Set-Variable : A parameter cannot be found that matches parameter name 'ResourceConfig'.
At line:1 char:20
+ Set -ResourceConfig <<<< -ResourcePropertySchema $ResourceConfiguration.ResourcePropertySchema
+ CategoryInfo : InvalidArgument: (:) [Set-Variable], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetVariableCommand
Pl advise the solution at [email protected] . I got this help from
http://zbutler.wordpress.com/2010/03/17/adding-additional-properties-to-resource-mailboxes-exchange-2010/ -
Is it possible using PowerShell to compare the contents of two text files line by line and if a line is found output that line to a third text file?
Lets say hypothetically someone asks us to search a text file named names1.txt and when a name is found in names1.txt we then pair that with the same name in the second text file called names2.txt
lets say the names shown below are in names1.txt
Bob
Mike
George
Lets say the names and contents shown below are in names2.txt
Lisa
Jordan
Mike 1112222
Bob 8675309
Don
Joe
Lets say we want names3.txt to contain the data shown below
Mike 1112222
Bob 8675309
In vbscript I used search and replace commands to get part of the way there like this
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("testing.txt", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Mike ", "Mike 1112222")
Set objFile = objFSO.OpenTextFile("testing.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close
That script works great when you know the name you are looking for and the correct values. Lets say someone gives you a list of 1000 employees and says import these names into a list in the correct format and one sheet has the correct names only and
the other sheet has lots of extra names say 200000 and you only need the 1000 you are looking for in the format from names2.txt.Sure,
Here's a simple one:
$names1 = "C:\names1.txt"
$names2 = "C:\names2.txt"
$names3 = "C:\names3.txt"
Get-Content $names1 | ForEach-Object {
$names1_Line = $_
Get-Content $names2 | Where-Object {$_.Contains($names1_Line)} | Out-File -FilePath $names3 -Append
This basically just reads $names1 file, line by line, and then read $names2 file line by line as well.
If the line being evaluated from $names2 file contains the line being evaluated from $names1 file, then the line from $names2 file gets output to $names3 file, appending to what's already there.
This might need a few more tinkering to get it to perform faster etc depending on your requirements. For example:
- If either $names1 or $names2 contain a lot of entries (in the region of hundreds) then it will be faster to load the whole content of $names2 into memory rather than opening the file, reading line by line, closing and then doing the same for every single
line in $names1 (which is how it is currently works)
- Make sure that your comparison is behaving as expected. The .Contains method always does a case sensitive comparison, this might not be what you are after.
- You might want to put a condition to ignore blank lines or lines with spaces, else they'll also be brought over to $names3
Hopefully this will get you started though and ask if you have further questions.
Fausto -
Powershell and Outlook 2007, trying to delete messages in a folder older than date
I was hoping to get a powershell script that would do the following
1) Connect to outlook 2007
2) Go to Mailbox folder (not an inbox subfolder) called 'Processes'
3) Delete all email from that folder older than 3 days old
I did some searching, I have found very useful things like how to empty a deleted items folder. I can even display all messages in that folder using this script snippet. But whenever I try to filter it down to email older than 3 days old, it blows up on me. I was attempting to use a | Where-Object pipe to reduce it and there are thousands of messages in that folder.
$outlook = New-Object -ComObject Outlook.Application
$olFolderInbox=6
$n = $outlook.GetNamespace("MAPI")
$f = $n.GetDefaultFolder($olFolderInbox)
$mailbox = $n.Folders.Item($f.Parent.Name)
$folder = $Mailbox.Folders.Item("Processes")
$folder.Items
#Clean out any open connections
$outlook = $n = $f = $mailbox = $folder = $null;I thought I might offer another solution for this. I came across this post looking to do the same, but I found it didn't always delete messages. Based on some other information on another site I was able to come up with a modified version.
The two other sites I referenced were:
http://gallery.technet.microsoft.com/ScriptCenter/en-us/966637b9-0b70-41c0-99d0-4647a89da70a
http://msdn.microsoft.com/en-us/library/bb220369%28office.12%29.aspx
----Script----
#Name of folder to access. You can specify subfolders by using FolderName\Subfolder
$folderPath = "FolderName"
#Filter older than 7 days
$olderThan = (get-date).AddDays(-7)
#Set format of date to use
$dateFormat = "g" # This will base on time to do just date choose "M/dd/yyyy"
#Create filter
$sFilter = "[LastModificationTime] < `'$($olderThan.tostring($dateFormat))`'"
$outlook = New-Object -ComObject Outlook.Application
$olFolderInbox=6
$n = $outlook.GetNamespace("MAPI")
$f = $n.GetDefaultFolder($olFolderInbox)
$mailbox = $n.Folders.Item($f.Parent.Name)
$folders = $mailbox.Folders
#Navigate to the proper folder
foreach ($folderName in $folderPath.split("\"))
$folder = $folders.Item($folderName)
$folders = $folder.Folders
$Items=$folder.items
$FilteredItems = $Items.Restrict($sFilter)
for ($i = $FilteredItems.Count; $i -gt 0; $i--) {
Write-Host "Deleting $($FilteredItems.Item($i).Subject)"
$FilteredItems.Item($i).Delete()
#Clean out any open connections
$outlook = $n = $f = $mailbox = $folder = $folders = $Items = $FilteredItems = $null;
Maybe you are looking for
-
On windows 8.1 I cannot update iCloud 3.1 to 4
I have installed iCloud (3.1) about 6 months ago on my windows 8.1 computer, I have tried to update iCloud to version 4. It start to load then towards the end it says "THERE IS A PROBLEM WITH WINDOW INSTALLER PACKAGE. A PROGRAM RUN AS PART OF THE SET
-
Losing Logic instrument presets between sessions
PLEASE HELP! I can't find the answer to this anywhere. Why do the instruments I use in my logic 8 sessions reset themselves when i return to the same session? I am Saving my sessions and doing all I can to retain it but when i come back to the sessio
-
HT201209 how to tell how much you have left on your apple gift card
how much money do i have left on my apple gift card?
-
Quantity confirmed in sales order change mode not in display mode !!!
Dear All !! We have a problem in sales order . In sales order the line item 580 quantity confirmed 15 pc in change mode VA02 if I open the sales order in display mode VA03 the quantity confirmed "0" More details refer the attachment . Kindly advise w
-
Passing variables with page redirect
I have a cfform. After it is filled out and submitted, the action page generates a random reference_no and puts the data into a database. I then do a cflocation url and pass the reference_no to another page. This page takes the reference_no and does