Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

remove users disable from a group

$
0
0

Hi

 

I would like to remove all the user disable in a specific group. Because I have users in a group that are no more used (disabe in the active directory). How can I do that:

 

Remove-QADGroupMember -identity lotusnotes -member ......

 

Thank you

Nathalie


How to add user to multiple groups from .csv

$
0
0

Hi All,

I have tried researching previous posts, but didn't find anything in relation to adding users to multiple groups from .CSV file import.  I have been able to get the below script to work on adding multiple users to a group, but now would like to modify it to add a user to multiple groups.  Any assistance would be greatly appreciated. 

File comma delimited import file; (*.CSV)

NameDomainMemberOf
<UserName><DomainName><SecurityGroup1>
<UserName><DomainName><SecurityGroup2>

 

Import-ModuleActiveDirectory

 

$members

 

 

=Import-CSV'H:\posh\Scripts\Adding Users to Multiple Groups.csv'

$members

 

 

|ForEach-Object {Add-QADGroupMember-Identity'SecurityGroup1,SecurityGroup2'-Service'DomainName'-Credential <Cred> -Member$_.samAccountname}

This script is only 3 lines.

Shared Printer and its associated machines

$
0
0

Hi

I would like to run a powershell script that looks at a specific shared network printer in AD and returns a list of all PCs\laptops that are attached to it in the form of a CSV file. Is this possible.

Thank you

Adding Users to AD in Bulk From CSV File

$
0
0

 

I am trying to write a script that will add users from a csv file and then add them to a group. I am currently testing with just one user at the is time. The csv file has the following headers

 

Contents of the Script:

Import-Module ActiveDirectory


$csvfile = Import-Csv -Path C:\PowerShell\Mac_AddUsers.csv
foreach( $user in $csvfile ) {
New-ADUser -Name $user.Username -GivenName $user.GivenName -UserPrincipalName $user.UserPrincipalName -SamAccountName $user.Username -DisplayName $user.DisplayName -Description $user.Description -Path $user.Path -AccountPassword (ConvertTo-SecureString $user.Password -AsPlainText -force) -Enabled $True -PasswordNeverExpires $True -PassThru }

 #Adding the Users to the Groups
foreach ( $user in $csvfile ) {
add-adgroupmember -identity $user.Groupname -Name $user.Username

}

I keep getting the following error when running the script. I am running with domain admins permissions. I have tried with and without quotes for the path in the csv as well.

PS C:\powershell> .\Add_New_User.ps1
New-ADUser : The server is unwilling to process the request
At C:\powershell\Add_New_User.ps1:6 char:1
+ New-ADUser -Name $user.Username -GivenName $user.GivenName -UserPrincipalName $u ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (CN=60c5476d4bee...,DC=example,DC=com:String) [New-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.NewADUser

Add-ADGroupMember : A parameter cannot be found that matches parameter name 'Name'.
At C:\powershell\Add_New_User.ps1:10 char:45
+ add-adgroupmember -identity $user.Groupname -Name $user.Username
+                                             ~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Add-ADGroupMember], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember

Set-ADAccountPassword : A parameter cannot be found that matches parameter name 'PasswordNeverExpires'.
At C:\powershell\Add_New_User.ps1:15 char:128
+ ... inText -force) -PasswordNeverExpires $True -PassThru
+                    ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-ADAccountPassword], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADAccountPasswor
   d

 

 

Powershell script to move user to new OU

$
0
0

Currently I have a PowerShell script to create new users, modify settings and set a AD Group or disable the user.

I receive my input file and at the end of line there is a code at tells the script what to do with the person.  Create, Modify, Disable

I'm wanting to start moving users around between different OU in AD. 

The way I'm envisioning this working is at the end of the line the is a new code ie MoveOU.

This would call a new function that would find the user and move them to the new OU.

I am needing help on how to code this.  Or if you have a better way to handle this I'm all ears.

Thanks.

Report on selected AD users with groups for each user

$
0
0

Hi everyone, I'm new-ish to PowerShell, but have been more recently made aware of it's prowess so i'm going to start using it more!  ;)

Let me set the scene; our AD structure is arranged so that users who use App-V'd (v4.6) applications are in global security groups named appropriately, so for example the Firefox group is called "App V Firefox".

I need to get a CSV report of all App V users, and the App V groups they are in... it's proving quite frustrating so far.  The command I'm using (basic) is:

Get-ADGroupMember -identity "App V Firefox" | Select name | Export-Csv -Path c:\Temp\Groupmembers.csv

...which only gives me the names of people in that group.  What I would like ideally is the "App V Firefox" bit to be a wildcard for ALL App V groups (along the lines of "App V*"), the person's Username rather than their actual name and in the CSV next to the username, all the groups they are members of (App V groups only preferably).  Is this possible?

Thanks in advance all!

Home drive and looking for blanks

$
0
0

Back again, with a change of direction. Another project has befallen me. Id rather take a ring to Mordor to be honest. LDAP is useful but so unreadable so again i look to powershell.

from many thousands of users i would like to find all ad users in a certain OU without a profile path set.

Using get-QADUser -searchroot i gather all the people/items. and i see i can filter them however this seems backwards to me. would it not be better to get all users without the path rather than all users then filter. can it be done?

tried test path home drive doesnt work and -filter "" doesnt work 

Feeling woefully inadequate. Been here 6 months now i should have powershell down to an art...

or not

 

Active directory backup & recovery by powershell

$
0
0

Hello 

I must write a powershell script, which must backup and recovery an active directory by powershell script (with GUI). Do you have any ideas? Can you help me?

Thanks in advance.

Best regards 

winkid


Adding Global group from one forest into a Domain Local group in another trusted forest

$
0
0

Hi everyone...  I've been trying to create a script to nest groups from one forest into another forest.  I can do it with no issues from the ADUC.  I've read some articles on what they suggested to create the connection to the other forst but it is not working.  Here is what I am trying to.

Forest A

  • Perform all work from this domain
  • This is where the Domain Local groups are located.

Forest B

  • This is where the Global groups are located.
  • These groups need to be nested into Forest A Domain Local group.

The two forest have a two way trust and as stated I can nest the groups through ADUC with no issues.  So I don't think its a rights issue.

Can anyone please help how I can perform the group nesting using Powershell? 

Thanks...

CSV File Import into AD

$
0
0

Human Resources is going to start providing a .CSV file to me on a regular basis to be imported into AD.

The file will only contain "employeeID" "department" and "company".  It will not have the UPN, name or any other info.

I need assistance writing a script that will cycle through the .CSV file, find someone in AD based upon their "employeeID" and then update the "department" and "company".

I really don’t know where to begin with this one.

So, any help would be greatly appreciated!

Thank you!

SkyRocketGuy

Ignoring blank fields of csv file

$
0
0

Hi, I am new to powershell and I need some help if you are kind :)

I have one  script for adding users to my AD and I want to import a csv file. The script is working, but I want to add one user to more groups, and I have some empty fields in my CSV file and I think this is the cause for this error:

Add-QADGroupMember : Cannot resolve directory object for the given identity: ''.

 

This is  my script

Import-Csv "UsersGroups.csv" | ForEach-Object {

 $PrincName = $_."Logon Username" + "@info.rusu.lab"

 New-QADUser -Name $_."Display Name" `

 -ParentContainer $_."Container" `

 -SamAccountName $_."Logon Username" `

 -UserPassword "p@SSword" `

 -FirstName $_."Prenume" `

 -LastName $_."Nume" `

 -Description $_."Departament" `

 -UserPrincipalName $PrincName `

 -DisplayName $_."Display Name" ;`

 $groups= $_."Group" ,$_."Group2",$_."Group3",$_."Group4",$_."Group5"

 foreach ($grupe in $groups) {

 $grupuri=$grupe

 Add-QADGroupMember -identity $grupuri -Member $_."Logon Username";}`

  Set-QADUser -identity $_."Logon Username" `

 -UserMustChangePassword $true `

 }

 

Please support me to avoid this error.

Thank you

DNS SERVER Backup Script

$
0
0

I am writing a DNS server backup script with additional options. 

Backing Up DNS Server Daily
Create a folder based on current date
Copy the backup from source to newly created folder based on date

Complicated part (well, for me anyway :) )

keeping current month's backup (30 different copies/Folder of backup for each day)
Create a folder every calender month and and copy all 30 copies of backups within this folder
Email Results of copying process either success or failed

So Far i have the following which covers half of what is required! 

$date =Get-Date-Format yyyyMMddNew-Item C:\dnsbk\DNSBackup$date-ItemTypeDirectory
$1st =Export-DnsServerZone-Name test.ac.uk -Filename backup\test.ac.uk.bk 
$2nd =Export-DnsServerZone-Name _msdcs.test.ac.uk -FileName backup\_msdcs.test.ac.uk.bk
$source ="C:\windows\system32\dns\*"
$destination ="C:\dnsbk\DNSBackup$date"
$copy =Copy-Item-Recurse $source $destination
$successSubject ="Backup Completed Successfully"

$SuccessBody ="$1st,$2nd,$copy"<<<<<<This does not work >>>>>Send-MailMessage-From"admin@test.ac.uk"-To"jbloggs@test.ac.uk"-Subject $successSubject -SmtpServer192.168.0.1-Body $SuccessBody

Reading the HKCU Registry keys from a list of remote computers

$
0
0

I am trying to query the registry of remote computers to obtain of list of devices, specifically printers.  I have used the remote registry on the past, but I was querying the HKLM (local machine) keys i.e. :

[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey 'LocalMachine',$Computer).OpenSubKey('SOFTWARE.......

How would I do this using the HKCU?  (I don't know where to input my $computer variable
into the mix.

Thanks.

Phillip

 

Runas a different user on a remote server

$
0
0

Hi...

I am trying to create a remote powershell session from which I have to run a PS script which resides on the target server. I need to run this target script with a different user other than which is used to create the remote session. At the end of script I am getting access denied error when the "Start-Process " part executes. I would like to understand what's going wrong with this script.

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

$remoteSession=New-PSSession $deplServer -credential $credential1


Invoke-Command -session $remoteSession -scriptblock {
$newcredential = New-Object System.Management.Automation.PsCredential("domain\myuser", (ConvertTo-SecureString "password" -AsPlainText -Force))

Start-Process powershell.exe -Credential $credential2 -ArgumentList "Start-Process powershell.exe -Verb runAs"


}

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

 

And the error:

This command cannot be executed due to the error: Access is denied.

    + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOp

   erationException

    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.C

   ommands.StartProcessCommand

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

Need some Help with executing a ps1 on a remote machine

$
0
0

Hi all I have been working on this for two days now to no avail. My company is in the middle of changing its spam service from postini to Proof point. In outlook we point the junk mail folder to a site url via Junk mail properties home page tab.

If i run the following on my local machine all works perfectly. If i try to run it on a remote machine failure

Script1:  saved locally on my desktop

[Reflection.Assembly]::LoadWithPartialname("Microsoft.Office.Interop.Outlook") | out-null

$olFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]

$outlook = new-object -ComObject "outlook.application"

$namespace = $outlook.GetNameSpace("MAPI")

$folder = $namespace.getDefaultFolder($olFolders::olFolderJunk)

$folder.WebViewURL = "https://internal address:#####" (Can't share that) 

$folder.WebViewOn = $true

I then enabled Winrm via GPO to a select set of machines for testing 

Finally I wrote a new script to remotely execute on the the test machines.

Script2: 

Enable-PSRemoting -Force

Invoke-Command -ComputerName (Get-Content "c:\Users\username\Desktop\testpcs.txt") -FilePath c:\Users\username\Desktop\SetJunkmailURL.ps1 -Credential domain\username

 

ERROR:

Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80010001.

    + CategoryInfo          : ResourceUnavailable: (:) [New-Object], COMException

    + FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand

 

You cannot call a method on a null-valued expression.

    + CategoryInfo          : InvalidOperation: (GetNameSpace:String) [], RuntimeException

    + FullyQualifiedErrorId : InvokeMethodOnNull

 

You cannot call a method on a null-valued expression.

    + CategoryInfo          : InvalidOperation: (getDefaultFolder:String) [], RuntimeException

    + FullyQualifiedErrorId : InvokeMethodOnNull

 

Property 'WebViewURL' cannot be found on this object; make sure it exists and is settable.

    + CategoryInfo          : InvalidOperation: (WebViewURL:String) [], RuntimeException

    + FullyQualifiedErrorId : PropertyNotFound

 

Property 'WebViewOn' cannot be found on this object; make sure it exists and is settable.

    + CategoryInfo          : InvalidOperation: (WebViewOn:String) [], RuntimeException

    + FullyQualifiedErrorId : PropertyNotFound

 

Again this works on my local machine just not on a machine i'm trying to execute remotely.

 

Any help with this will greatly be appreciated. 


PowerShell 3.0 Remoting vs PS 2.0

$
0
0

For the past few months I've been using PowerShell 2.0 with Remoting set up through Group Policy. Recently, the Microsoft Management Framework 3.0 came out as an optional update. We sent that update to our systems. Now when I want to get on to a remote computer I'm getting

[MACHINENAME] Connecting to remote server MACHINENAME failed with the following error message : The WS-Management
service cannot process the request. Cannot find the Microsoft.PowerShell session configuration in the WSMan: drive on
the MACHINENAME computer. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (MACHINENAME:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : InvalidResourceUri,PSSessionStateBroken

 

Does PS 3.0 change the way Remoting works? I can still remote to PS 2.0 computers. I haven't done a lot of looking into this yet since it's FRIDAY.

Manage User Workstations with Remote Powershell via SSL

$
0
0

Hey Folks,

I am looking for a solution to remotely manage around 100 workstations.

I will be connecting to these systems to complete several local system tasks. (3rd party updates, security auditing, incident response)

Remote Powershell over SSL seems ideal.

To enable the HTTPS listener on each workstation - will I need a local certificate installed on every workstation? I believe this is correct, I just want to be sure.

Is there a more graceful way to implement a solution like this?  Or will I have to physically visit each workstation I wish to remote into - to install a certificate?

I'd also welcome any suggestions that do not use powershell or winrm at all!

Thanks! 

remoting server execution powershell script show Sysocmgr error

$
0
0

I'm want remoting server win2003  auto install iis6 with powershell script.

so the mananger server the system path D:\PS\  have 2 ps file :

RemoteRunScritpion.ps1  &  Install-CN_IIS60_x86_K3.ps1

I run command on powershell

sl D:\PS

.\RemoteRunScritpion.ps1

i can look result  on powershell windows:

----------------------------------

$installPath=E:\Test\
edit i386 registry path
builder iis components file
out file path:E:\Test\iis.txt
begin uninstall iis
0

----------------------------------

but the remote server "192.168.1.20" why noting to do,i can'n see process is worker?

and the winrm service is change to stop?(on the server, powershell log see: Enginestatus has beenchangedfrom theavailablestopped)

why?

Who can help me!!!

Thank you!

1.RemoteRunScritpion.ps1

 

$User="administrator"
$PWord = ConvertTo-SecureString –String "password01" –AsPlainText -For
$_credentail = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PWord
$pso = New-PSSessionoption -OperationTimeout (1000*60*5)
$session1 =New-PSSession  -computer "192.168.1.20" -Credential $_credentail -ErrorAction Stop -SessionOption $pso
Invoke-Command -Session $session1   -FilePath .\Install-IIS60_x86_K3.ps1

2.

Install-IIS60_x86_K3.ps1

param([string] $evenPath)
[string] $userRoot = "HKEY_LOCAL_MACHINE"
function BuilderIISTxt
{
        param([string] $installPath,[string] $InstallOrUnInstallStr)
        $contentStr="[Components]"+"`r`n"
        $contentStr+="iis_common = $InstallOrUnInstallStr"+"`r`n"
        $contentStr+="iis_www = $InstallOrUnInstallStr"+"`r`n"
        $contentStr+="iis_www_vdir_scripts = $InstallOrUnInstallStr"+"`r`n"
        $contentStr+="iis_asp = $InstallOrUnInstallStr"+"`r`n"
        $contentStr+="iis_inetmgr = $InstallOrUnInstallStr"+"`r`n"
        $contentStr+="aspnet= $InstallOrUnInstallStr"+"`r`n"
        $contentStr+="ftp_extensions= $InstallOrUnInstallStr"+"`r`n"
        $contentStr+="iis_ftp= $InstallOrUnInstallStr"+"`r`n"
        $outPath=$installPath+"iis.txt"
        $contentStr  | out-file $outPath -Encoding unicode
        Write-Host "out file path:$outPath"
}
function BeginProcessExecuse
{
    param([string] $argumentListStr)
    $result = Start-Process Sysocmgr.exe -ArgumentList $argumentListStr -Wait -PassThru
    $result.WaitForExit()
    Write-Host $result.ExitCode
}

function Install-IIS60_x86_K3
{
    param([string] $installPath,[bool] $InstallOrUnInstall)
    if (!(Test-Path $installPath))   
    {
      Write-Host "Files : $installPath already exists in destination folder" 
    }
    else
    {
        Write-Host  "`$installPath=$installPath" 
        #Get-Date -UFormat "%Y%m%d"  
        [string] $keyName ="HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Setup"
        $Registry=[Microsoft.Win32.Registry]
        [string] $newInstallPath=$installPath 
        $newInstallPath+="CN_IIS60_x86_K3\"

        [string] $InstallOrUnInstallStr="ON"
        if(!$InstallOrUnInstall)
        {
            $InstallOrUnInstallStr="OFF"
        }   

        Write-Host  "edit i386 registry path"  
        $Registry::SetValue($keyName,"ServicePackSourcePath",$newInstallPath,[microsoft.win32.RegistryValueKind]::String) 
        $Registry::SetValue($keyName,"SourcePath",$newInstallPath,[Microsoft.Win32.RegistryValueKind]::String) 
        Write-Host  "builder iis components file"  
        BuilderIISTxt $installPath $InstallOrUnInstallStr
        if($InstallOrUnInstall)
        {
            Write-Host  "begin install iis" 
        }
        else
        {
             Write-Host  "begin uninstall iis" 
        }
        #Sysocmgr.exe /i:sysoc.inf /u:$installPath\iis.txt  /q  /w
        $argumentListStr="/i:sysoc.inf /u:$installPath"+"iis.txt"
        BeginProcessExecuse $argumentListStr 
    }  
}

Install-IIS60_x86_K3 "E:\Test\" $false


3.E:\Test\  Folder have i386 files:

\IIS60_x86_K3\i386\

 

 

 

 

Problem running PSSession from within a script

$
0
0

Hello All

Can someone please help me with the followng question please.

If is run the following from a command line it works find

$Session = new-pssession -computername remote1
enter-pssession $session
"now on computer $env:computername"
exit-pssession
get-pssession | remove-pssession

Now if I put copy the above and put it into say c:\myscript.ps1 and execute it

PS > c:\myscript.ps1

it gives no errors but rather returns my local computername rather than the computer I am trying to open a remote session to.

same issue on PowerShell 2 and 3

any ideas please?

Thanks all
Ernie

 

 

 

powershell script to enable "Offer Remote Assistance" automatically for all windows 7 computers in the office

$
0
0

Hello guys,

Just a question, is there a way to create a powershell script to enable "Offer Remote Assistance" automatically for all windows 7 computers in the office ?

I know to set up through gpedit locally and GPO edit as well but there are some procedures here that not allow me deploy it by GPO.

 

Thanks a lot

 

Viewing all 10624 articles
Browse latest View live