Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Powershell to Enable "Protect from Accidental Deletion" on ALL OU's

$
0
0

Howdy folks...

The client I am currently working with has partially set the "Protect from Accidental Deletion" attribute on their AD...I want to extend this feature to ALL organisation units (OUs) in their forest (but only to the OUs and nothing else). I know how to use PS to do for ALL objects however, I'm having problems with the "Filter". I've attempted the following command (and various iterations) but they seem to fail on the filter;

Get-ADobject -Filter "organizationalUnit" -SearchBase “OU=OU1,DC=DomainComponet2,DC=DomainComponent1” | Set-adobject -ProtectedFromAccidentalDeletion $true

Does anyone know what the { -Filter "organizationalUnit" } part should be...?

Rgds

FMcFF


Export users membership and attribute

$
0
0

Hi

I need to search my AD for users that have an "extensionAttributte2" field populated and if they do I also need to know if they are members of the "AccountsGroup" AD Group.

How can I create a report that will show me

Username                   ExtensionAttribute2                 AdGroup

Mike                               (whatevervalue)                       AccountsGroup

Thanks, Maelito


Maelito

Problem with looping...

$
0
0

Hi,

I'm in the process of writing a script which will update groups based on AD Attributes (department). This works great and reads a CSV with a list of groups and departments and adds uses to the relevant groups. The second section of the script reads the current group members and removes them if they are disabled - this part works too. But the part I am struggling on is where it reads the group members, checks if someone that is a member of the group shouldn't be anymore, by looking at their department. If there is only one member in the group it works fine, if there are more members in the group then it can't process them. I think it's because I need to loop it to check each user, but can't seem to get it to work.

I've commented the lines that are causing me the issue

#Script variables
#Make edits below this line

#Enter path to CSV file containing headers for ADDepartment,GroupName
$CSVFile = "c:\Source\Scripts\Depatmentalgroups\DepartmentalGroups-test.csv"
#Enter Log file path
$LogFile = "c:\Source\Scripts\Depatmentalgroups\logfile.txt"


#Don't change anything after this line
###############################################################################################################
#Get todays date
$today = Get-Date -DisplayHint Date

#Imports data from CSV file containing department names and group names - data is case sensistive
import-csv $csvFile | foreach {

#Adds users to group based on attributes
$dept = $_.DeptName
$ADGroup = $_.GroupName

$user = Get-QADUser -Department $dept -NotMemberOf $ADgroup -Enabled
If (!($user)) {Write-output  "$Today,$Dept,No-Matching-Users-Found" >> $LogFile}
	Else {Add-QADGroupMember $adgroup -member $user 
			Write-Output "$Today,$Dept,$user Was-Added-To-Group" >> $LogFile
			} 


#Removes any disabled users from group
$disableduser = Get-QADGroupMember $ADgroup -Disabled #check to see if users in group are disabled
If(!($disableduser)) {Write-Output "$Today,$Dept,No-Disabled-Users-To-Remove" >> $Logfile} #if no disabled users are found write it to logfile
	Else {Remove-QADGroupMember $ADGroup $disableduser  #if disabled users are found, remove them from the group
		Write-Output "$Today,$Dept,$disableduser,Was-Removed-From-Group" >>$logfile
		}

#Remove any user no longer in department
$groupmember = Get-QADGroupMember $ADGroup #gets all users left in group

If(!($groupmember)) {Write-Output "$Today,$Dept,Group-Was-Empty" >>$LogFile} #if no members are in the group write it to log file
	Else {$nolongermember = Get-QADUser $groupmember | Where-Object {$_.department -ne $dept} #otherwise get all users who are in the group but that don't match the required department
	#if more then one user is found in the above line, the get-qaduser fails with 'idenity' specified method is not supported - so i think i need to do something like foreach but struggling to figure this part out
	}

If(!($nolongermember)) {Write-Output "$Today,$Dept,No-Users-To-Remove" >> $LogFile}
	Else {Remove-QADGroupMember $ADGroup $nolongermember
		Write-Output "$Today,$Dept,$nolongermember,Was-Removed-From-Group" >>$logfile
		}
}

################################################################################################################


Regards,

Denis Cooper

MCITP EA - MCT

Help keep the forums tidy, if this has helped please mark it as an answer

My Blog

LinkedIn:

windows 2012 cmdlet to rescan storage?

$
0
0

After expand a vmdk file, I log onto the Windows 2012 server, and open up Server Manager | File and Stoage Services | Volumes | Disks. At TASKS drop-down, choose Rescan Storage.

Windows 2012 has a Storage module. But I can't find a cmdlet that will rescan all disks. In the past, I can use Diskpart, then issue Rescan command.

Current Date output of export file

$
0
0

Hi

I am using below script to get HR samaccount from AD. Now I want to output should come with date name when the script run.

Also can send that current date output to my email address.

========================

Import-Module Activedirectory
Get-ADUser -Filter {(SamAccountName -like "*HR*") -and (enabled -eq"True") -and (pager -like "*")} -Properties * | select name,SamAccountName,pager | Export-Csv C:HR.csv -NoTypeInformation

================

Problems with running get-childitem on directory structure

$
0
0

I have the test script below that I am working on that dies when it gets to the System Volume Information folder with error shown at the bottom.  I know that it is this folder because I can put a test file right before and right after it and it finds the one before but not the one right after.  Why is it having a problem getting past this folder?

Second question:  If I started up PS under the system account and point this script to c:\users, it still gets access denied when trying to access user profile folders.  I would have thought running under the system account that it would be able to read what is in those folders.  Any ideas why it can't read the contents of the folders?

Test script:

$intDaysOld = '-' + 30
$strFileType = 'bat'
$path = "c:\users"
Get-ChildItem -path "c:\" -recurse -include "*.bat" -force -ErrorAction continue | where  {$_.LastWriteTime -le ((get-date).AddDays($intDaysOld).ToShortDateString())} | Remove-Item -WhatIf

Unexpected error:

Get-ChildItem : Access is denied
At line:5 char:1
+ Get-ChildItem -path "c:\" -recurse -include "*.bat" -force -ErrorAction continue ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetChildItemCommand

how to export csv without doublequote

$
0
0

I ran the following comand

ls |export-csv "d:\a.csv"

The result is like the following, every field is double quoted, is there any way to not export double quote. Currently the silly approach I used is to first export-csv, and then read the file in and replace all the double quote with empty string.

#TYPE System.IO.DirectoryInfo

"PSPath","PSParentPath","PSChildName","PSDrive","PSProvider","PSIsContainer","BaseName","Mode","Name","Parent","Exists","Root","FullName","Extension","CreationTime","CreationTimeUtc","LastAccessTime","LastAccessTimeUtc","LastWriteTime","LastWriteTimeUtc","Attributes"

"Microsoft.PowerShell.Core\FileSystem::C:\Users\Daniel.Wu\.fcm","Microsoft.PowerShell.Core\FileSystem::C:\Users\Daniel.Wu",".fcm","C","Microsoft.PowerShell.Core\FileSystem","True",".fcm","d----",".fcm","Daniel.Wu","True","C:\","C:\Users\Daniel.Wu\.fcm",".fcm","10/6/2010 10:33:39 AM","10/6/2010 2:33:39 AM","10/15/2010 3:28:57 PM","10/15/2010 7:28:57 AM","10/15/2010 3:28:57 PM","10/15/2010 7:28:57 AM","Directory"


I need help about script to bulk remove something

$
0
0

Hi all,

I need to compose a PowerShell script to bulk remove some items
Here is an example:
1. First, I run:

PS C:\Users\> Get-ManagementRoleEntry "test1\*"

Name                           Role                      Parameters
----                           ----                      ----------
Add-MailboxFolderPermission    test1                {AccessRights, Confirm, ErrorAction, ErrorVariable...}
Add-MailboxPermission          test1                {AccessRights, AutoMapping, Confirm, Deny...}
Add-RecipientPermission        test1                {AccessRights, Confirm, ErrorAction, ErrorVariable...}
a
b
c

2. The cmdlets (too many) to remove something is:
Remove-ManagementRoleEntry -Identity "test1\Add-MailboxFolderPermission"
Remove-ManagementRoleEntry -Identity "test1\Add-MailboxPermission"
Remove-ManagementRoleEntry -Identity "test1\Add-RecipientPermission"
Remove-ManagementRoleEntry -Identity "test1\a"
Remove-ManagementRoleEntry -Identity "test1\b"
Remove-ManagementRoleEntry -Identity "test1\c"

We can find that it uses the value of the Name coloum of the output in the first cmdlet. Maybe we have some ways to just call the values of the Name coloum got from the first cmdlet (in text mode?) and use it to bulk run the second cmdlet (Remove-ManagementRoleEntry)?
I can accept involve other things to achieve the goal, such as using CSV files.

TIA


Getting Outlook folder permissions for all Exchange users

$
0
0

I have a script that will pull permissions for all Exchange mailboxes for the calendar folder. This works quite well for just the calendar folders. However, I need to search all folders (not just default folders) for all mailboxes in my environment. I know it will be an intense script. Bottom line we are attempting to clean up our distribution lists that are set to security objects and need to know where someone has granted permissions to a security group.

FYI...I did search the archives for folder permissions and only got 10 hits. I am fairly new to PowerShell scripting so I apologize for my ignorance but would greatly appreciate any assistance you can provide.

# Get the mailboxes 
$Mailboxes = Get-Mailbox -Filter {RecipientTypeDetails -eq "UserMailbox"} -ResultSize unlimited
# An array for the output 
$Output = @()   
# Loop through the mailboxes 
ForEach ($Mailbox in $Mailboxes) {
  # Get the name of the calendar folder  
  $Calendar = (($Mailbox.PrimarySmtpAddress.ToString())+ ":\" + (Get-MailboxFolderStatistics -Identity $Mailbox.DistinguishedName -FolderScope Calendar | Select-Object -First 1).Name)    
  # Get the permissions on the folder  
  $Permissions = Get-MailboxFolderPermission -Identity $Calendar   
  # Loop through the permissions, populating the output array  
  ForEach ($Permission in $Permissions) {
  $Permission | Add-Member -MemberType NoteProperty -Name "Mailbox" -value $Mailbox.DisplayName   
  $Output = $Output + $Permission 
  } 
  }   
  # Write the output to a CSV file 
  $Output | Select-Object Mailbox, User, {$_.AccessRights}, IsValid | Export-Csv -Path e:\_logs\CalendarPermissions.csv -NoTypeInformation

Find all TotalSeconds

$
0
0

Hi,

Pls, I have find all TotalSeconds

$xtime = "00:03:20"
$xSec = new-timespan -Hours $xtime
$xSec = $xSec.TotalSeconds
$xSec

How i have to do?

My best regards

Arnold

How can I create a share with New-SmbShare and specify a Local Group

$
0
0

Using the New-SmbShare cmdlet in Powershell 3.0, I would like to create a share and specify a Local Group as the ReadAccess group. Code looks basically like:

$serverName = "Server01"
$groupName = "Share Readers"
$secGroup = "$serverName\$groupName"

$shareName = "TEMP"
$sharePath = "C:\TEMP"

New-SmbShare -Name $shareName -Path $sharePath -ContinuouslyAvailable $TRUE -ReadAccess $secGroup -CachingMode NONE

When I run this, I get the following output:

New-SmbShare : The request is not supported.
At line:1 char:1
+ New-SmbShare -Name "TEMP" -Path "C:\TEMP" -ContinuouslyAvailable $TRUE ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (MSFT_SMBShare:ROOT/Microsoft/Windows/SMB/MSFT_SMBShare) [New-SmbShare
], CimException
+ FullyQualifiedErrorId : Windows System Error 50,New-SmbShare

HELP!!!!

Check Whether drive exists

$
0
0
function get-checkdrive($server)
{	
		write-verbose "check drive -started"
	    $check= 'D:\' # no escape 
		$testobj=get-wmiobject win32_volume -filter  "DriveLetter= 'D:'" -computername $server
		$caption= $testobj.Caption
		if($check -contains ($caption) )
		{ 
			$TotalGB=@{Name="Capacity(GB)";expression={[math]::round(($_.Capacity/1073741824),2)}}
			$FreeGB=@{Name="FreeSpace(GB)";expression={[math]::round(($_.FreeSpace /1073741824),2)}}
			$test=$testobj|Select Name , $TotalGB,$FreeGB	
		    write-verbose "check drive -Completed"
            return ($test)
        }
        else                
        { 
			write-output "$check doesnt exist"
        }
}

I have wriitten this script to check whether the D DRIVE exist or not. the script works fine but the problem is if D doesn't exist it doesn;t print drive doesnt exist instead print

@{Name=D: , Freespace(GB)=0 , Capacity(GB)=0). please help.

read csv files and produce email with attachment

$
0
0

 I have csv  files being created that have a header record than row 2 has corresponding data.

\\servera\csv\*.csv

 shippernbr|email|emaillCC|Returnemail|returnemailcc
"091",me@hotmail.com,mecc@hotmail.com,mertn@hotmail.com,mertncc@hotmail.com

 I need to format that data into an email then after reading shippernbr value(091) go find that file in
\\servera\pdf directory and send that pdf as an attachment to the email. When completed(email sent) move the csv and pdf to an
archive directory.  I'm using PSv2 and would like to log all events to keep a audit trail of what gets sent.

 Thanks.

How to querry an specific OU for users with the same last name and first name ?

$
0
0

Hello,

I have an OU called "COMPANY - New Users" but i am trying to code the scenario where there is a user already with identical firstname and lastname as new user to be created.

Currently on that OU, I have the following:

SamAccountName  : morgana
Surname         : Morgan
GivenName       : Alex
Name            : Morgan, Alex

SamAccountName  : morgana1
Surname         : Morgan
GivenName       : Anna
Name            : Morgan, Anna

SamAccountName  : morgana2
Surname         : Morgan
GivenName       : Anna
Name            : morgana2

But, when creating the other Morgan Anna, it will not let me. So I would like to replace morgana2 under Name by Morgan-DUP, Anna. Here is the code I have so far to debug it, but I am not going anywhere. :(

Import-Module ActiveDirectory
$sam = "morgana2"
$FistName = "Anna"
$LastName = "Morgan"
$SameFirstNameLastName = Get-ADUser -SearchBase "OU=COMPANY - new users,DC=DOMAIN,DC=COM"  -Filter * -Properties SamAccountName,Surname,GivenName | ? {$_.SamAccountName -eq $sam -and $_.givenName -eq $FirstName -and $_.Surname -eq $LastName}
#$SameFirstNameLastName = Get-ADUser -SearchBase "OU=COMPANY - new users,DC=DOMAIN,DC=COM"  -Filter * -Properties Surname,GivenName,Name,Department,Title,TelephoneNumber,EmployeeID,EmployeeNumber | where { $_.SamAccountName -match $sam } | ? {$_.givenName -eq $FirstName -and $_.Surname -eq $LastName}
if (!($SameFirstNameLastName)) {
   $SameFirstNameLastName | Select SamAccountName,Surname,GivenName,Name,Department,Title,TelephoneNumber,EmployeeNumber
}
$SameFirstNameLastName | Select SamAccountName,Surname,GivenName,Name,Department,Title,TelephoneNumber,EmployeeNumber
Thanks for your help

date join and emp id bulk add

$
0
0

Dear Team

The following objects have been added to the active directory 2008 R2. there are about thousand of users in my existing environment. My question is possible way of adding join date automatically rather than adding manually?

Is it possible for me to create a CSV file and input the date join and emplyee id to add the employee id or what is the easiest way to add. 

  1. Employee ID
  2. Date join(Employee)

Please help me.

Thank you

Mahesh Leema

Dear Team

The following objects have been added to the active directory 2008 R2.  there are about thousand of users in my existing environment. My question is possible way of adding join date automatically rather than adding manually?

Is it possible for me to create a CSV file and input the date join and emplyee id to add the employee id or what is the easiest way to add. 

1.       Employee ID

2.       Date join(Employee)


Please help me.

Thank you

Mahesh Leema


Script block literals are not allowed in restricted language mode or a Data section

$
0
0

Here i execute power shell Scripts by using in C#:

PSCredential psc = new PSCredential(@"domainname\username", SecurePswd);
WSManConnectionInfo wsmConn = new WSManConnectionInfo(new Uri(strSystemURI), strShellURI, psc);
Runspace rs = RunspaceFactory.CreateRunspace(wsmConn);
rs.open();

String Script = " Get-Mailbox adminuser Select-Object name,primarysmtpaddress, DisplayName,Database,@{e = {$MBXstat = Get-MailboxStatistics $_.name; $MBXstat.totalItemsize.value.toMB()}},@{e = {$MBXstat = Get-MailboxStatistics $_.name ; $MBXstat.itemcount}}";

Pipeline pl = rs.CreatePipeline();
pl.Commands.AddScript(Script);
Collection<PSObject> psCol = pl.Invoke();//Here for me the error occurs "Script block literals are not allowed in restricted language mode or a Data section"

If any knows why this occurs..Tel  me..Thanks a lot.


Some Storage CMDLets do not work under WinPE

$
0
0

I have built a custom WinPE based on W2012 and included Powershell and a number of the Powershell CMDLets such as SMB, DISM, and Storage. Everything works fine. When you boot the WinPE disk and do a get-command -module Storage, it shows all of the Storage CMDlets. I am trying to do some simple automation and wrote a very simple script to initialize, partiion and format a disk

Initialize-disk 1 -PartitionStyle MBR
New-Partition  -diskNumber 1 -DriveLetter L -UseMaximumSize | `
  Format-Volume -FileSystem NTFS -NewFileSystemLabel "Stuff"

When I run this script on a W2012 server it works fine. When I run it from by WinPE disk the Format does not work. No error messages. Nothing. The first 2 statments work but the disk never is formatted and no label is assigned. The same is true with the Clear-Disk Cmdlet. I execute it under W2012 and it works fine. When I execute it under Win-PE it just returns to me and does nothing. I even tried just executing the Format-Volume Cmdlet by itself on WinPE and got the same result -- it immediately came back with no error message and did nothing.

It seems like some cmdlets work and some don't. Anyone have any thoughts?

Thanks

Roger


Roger

Script for Delete a specific Folder and Move the other one to rhe C:\

$
0
0

Hi

I need a PowerShell script for  Delete a specific Folder and Move the other one to the C:\

at the moment I have a folder called FileNotToBackup

under this folder I have 2 folder called Script and Utility

I want a script to delete script folder and move Utility folder to the C:\

this script will be used at the end of server creation from a template

thanks

 


reza

Dynamic Where-Object Filter

$
0
0

I'm trying to use a dynamic where-object filter by building it and assigning it to a variable and then using that variable, something like the following:

$filter = "`$_.thing -match `"criteria`""

get-thing $things | ? {$filter}

But this fails to match, whereas the following matches:

get-thing $things | ? {$_.thing -match "criteria"}

What am I missing?

When I look at $filter after the assignment above, it looks exactly like what's in the curly brackets in the second get-thing call.

I want to be able to do this because there may be multiple criteria and I need to dynamically add -or clauses. If there's a better way, please let me know what that is.

Thanks.

Powershell Audit workstations

$
0
0

Hello guys,

I am starting with powershell and I'd like to verify with you about how can I proceed with a work I need to do...

I want to create a script to audit workstations comparing the software versions with the expected sw versions... but I don't know the best logic for create that..

I thought about create two files. 1 with the results and another with the expected value and compare it in a foreach..

is it the best option?

I would like to confirm values as dns addresses, dhcp servers, domain name.. etc.

can you help me abuot how can I create a good logic for that please?

Thanks in advance

Viewing all 21975 articles
Browse latest View live




Latest Images