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

Bulk drop and create Local Users in windows 2003 servers standalone

$
0
0

I have local standalone Windows 2003 which is not part of any Active Directory. I have a list of users (containing UserName & Password per line) in a CSV file and contain about 300+ user accounts.  I am looking for a VBS script that will loop through this file of users and perform the following tasks on the local windows 2003 servers.  There will be two CSV files, one containing users account to be deleted or drop from windows server, and the other will contain users who needs to be created or not already existed on the server

Part A:  Drop users from the Drop List

Drop/Delete users accounts & Permissions for those already existing on the server and listed in the Drop CSV file

Part B:  Add new users who are not already on the servers

1)  Create the UserName and Password, and set to never expire

2) Create Home Directory on a local share which already exists

3) Create a roaming profile for each user

Drop/Delete users accounts & Permissions for those already existing on the server and listed in the Drop CSV file

I know you may be thinking, what is the purpose for this.   We have a local community education center and one windows 2003 server.  No funds to upgrade to windows 2008.   We train students for 3 months interval and need a way to automatically control access to the server for training resource delivered through Home Directory local share.  Instead of manually creating 300+ students account every 3 months, and have to delete them is extraneous.  The two user CSV files (Drop and Create) users, will be created by the administrator and place on the windows server to use by this VBS program which we can schedule on windows tasks manager. 

I will really appreciate such a script or any better way to do the job above

Thank You Very Much for your help


Does anyone know if the Get-Random cmdlet uses System.Security.Cryptography.RandomNumberGenerator ?

$
0
0

I recently worked on a script where generating random passwords for accounts was a requirement.  I found several examples of random password generator functions in PowerShell online, but every one I looked at made use of the Get-Random cmdlet.  I looked over the documentation for Get-Random, and searched around a bit, and haven't been able to determine whether it uses the System.Random pseudorandom number generator, or the stronger classes in System.Security.Cryptography.

I was in a hurry, so I wrote my own quick function for it instead, but I'm still curious to know if Get-Random meets strong crypto standards.

function New-RandomPassword {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$false,Position=0)]
        [ValidateRange(1,10000)]
        [System.UInt32]
        $Length = 8,

        [switch]
        $AsSecureString
    )

    # For now, this is hard-coded to use a full complexity US-English password (upper/lower case letters, numbers, common printable symbols),
    # and is not guaranteed to produce a password that meets complexity rules (it's random, so it's entirely possible you might get an all lower-case
    # password once in a while).  That's extremely unlikely if you're using a password length that's long enough to be cryptographically strong, but
    # possible.

    $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
    
    $bytes = New-Object System.Byte[]($Length)
    $rng.GetBytes($bytes)
    
    if ($AsSecureString) {
        $ssPassword = New-Object System.Security.SecureString

        for ($i = 0; $i -lt $Length; $i++) {
            $ssPassword.AppendChar([char]($bytes[$i] % 94 + 33))
            $bytes[$i] = 0
        }

        $ssPassword.MakeReadOnly()
        $ssPassword | Write-Output
    } else {
        $password = New-Object System.Text.StringBuilder

        foreach ($byte in $bytes) {
            $password.Append([char]($byte % 94 + 33)) | Out-Null
        }

        $password.ToString() | Write-Output
    }
}

Trapping if the CMD.ExE fails?

$
0
0

Hello!

What I need to do is that I have a cmd.exe running a script and it either comes back as Pass or Fails. What I need to do is use a try catch block in my script so that when the cmd.exe fails, it will be handled in the catch block.

I have tried to do this but it is not working. Can anyone assist?


Thanks!
Mike


Mike Kiser

Quickly delete large folders with PS

$
0
0

I have a script right now that goes through and deletes a list of directories (old users home directories).  It does this just fine and here is a code sample:

Get-Content $UsersFile | ForEach-Object {
    $pathcheck = Test-Path "$basePath\$_"
    If ($pathcheck -eq $false){
        Write-Host "'$basePath\$_' could not be found"
        LogWrite "'$basePath\$_' could not be found"
    } Else {
        Remove-Item "$basePath\$_" -Recurse -Force -Verbose
        Write-Host "$ScriptContext has removed '$basePath\$_'"
        LogWrite "$ScriptContext has removed '$basePath\$_'"
    }
}

As you can see I'm using "Remove-Item <Path> -Recurse -Force -Verbose" to delete the targeted folder and all of it's contents.  While that is working, it seems to take longer to delete a single large folder than if I were to simply right-click on that large folder and say delete permanently.  Is there a faster way to completely delete a directory and all of its contents?

Find all files on a drive with user input using powershell

$
0
0

Hello,

First I would like to state that I am not new to Powershell, but I am definetly a novice scripter trying to better his skills. I am currently trying to write a Powershell Script that A. Asks the user what drive they would like to search B. Input the file name or extension (i.e. Filename: New File for Project, OR Filename: *.xlsx). This should then export to a .csv format. I have an idea of how it should look but honestly I cant seem to find the correct set of cmdlets that will help me do this, here is a couple ideas I had:

$drive = read-host "Input Drive "

$filename = read-host "Input Filename "

$objItems = get-childitem $drive\$filename

foreach($item in $objItems){

$item.something

$item.something

}

The problem with this method is it is only searching the properties of a folder path. I cant seem to figure out how to search for a string. I have also tried standard commands and piping such as: 

get-childitem $drive\$filename | get-unique

This technique has got me closer than anything else I have tried. Please let me know what you guys think.

Thank you.

REGEX not matching

$
0
0

This is the string I am trying to match:

"START /WAIT  %MMMCPPROD%\cpfs -i ldtst -I HDM_ADT -P HDM_ADT -s"

And this is my regex:

^(?!rem)(?!\:\:)(?:START /WAIT )?[\w\%]*\\cpfs -i ldtst -I HDM_ADT -P HDM_ADT -s$

Not sure why this one is false, any ideas?

Set-Location : Cannot find drive. A drive with the name 'P' does not exist.

$
0
0

Hello All,

I have a strange Problem with network drives I am mapping and using in Powershell. If I map a network drive the first time I could set-location and able to browse thought the drive. If I dissconect the drive and re-create the drive again, I am not able to set-location and browse to the drive anymore...

$PDrive = "\\ShareName\Projects$\P1757_xxx"
(new-object -com WScript.Network).MapNetworkDrive("P:",$PDrive)
Set-Location P: WORKING :-)
Set-Location C:
(new-object -com WScript.Network).RemoveNetworkDrive("P:")

$PDrive = "\\ShareName\Projects$\P1757_xxx"
(new-object -com WScript.Network).MapNetworkDrive("P:",$PDrive)
Set-Location P: NOT WORKING :-(

Set-Location : Cannot find drive. A drive with the name 'P' does not exist.
At line:1 char:13
+ Set-Location <<<<  P:
    + CategoryInfo          : ObjectNotFound: (P:String) [Set-Location], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

Share is showing up in PsDrive and on net use, but I Am Not able to use it thought PowerShell. Same Problem if I Map and Remove the NetworkDrive with net use... In CMD the Network Drive is accessiable after Recreation?????

using send-mailmessage to have resulted attachment html file placed in the body of message

$
0
0
Hi. Thanks for the time. I guess the title is a bit confusing. What I am trying to is 1) export a list to an htm file and then 2) email that htm into the body of the email.  Can this be done using send-mailMessage? This is what I have below and it works as an attachment but I want to put it the attachment into the body of the email.

get-messagetrackinglog -resultsize unlimited -recipient me@domain.com -start (get-date).adddays(-1) |select messageid -unique | measure | ft count > c:\myfolder\emails.htm

Send-MailMessage -to "me@domain.com" -subject "Daily" -smtpserver smtp -from "me@domain.com" -attachment "c:\myfolder\emails.htm"

Powershell - script to add user to security group if user does not already exist

$
0
0

Hi Everyone,

I'm not too good when it comes to writing powershell scripts, but hopefully someone could be kind enough to either point me in the right direction, or (if you really feel like it) write the script for me! ^_^

Currently I have a GPO in place with which we disable local logons and via Terminal Services for our Service Accounts in AD. The GPO stops this via a Security Group which contains our service accounts.

At the moment, when we create a new service account, we need to add the account to the security group (a manual process obviously).

What I would like to do is to automate this process by:

  • Use a powershell script to search for service accounts in active directory that matches a naming convention (e.g. _svcAPACxxx), and compare this list with the membership of the security group listed in the GPO.
  • If the account does not exist as a member of the group, add account to group. If it already exists, great!

I would look to set this up via a scheduled task, and send an e-mail as to a DL as to whether accounts were added at the last run point (and which accounts were added at the time).

Compare-Boject $._Sideindicator

$
0
0

I've got some simple script to compare the contents of a folder as follows:

$folder1 = get-childitem $source | where-object {$_.lastwritetime –gt $DateToCompare}
$folder2 = get-childitem $destination | where-object {$_.lastwritetime –gt $DateToCompare}

#Compare the 2 folders - RSCLIVE4
Compare-Object $Folder1 $Folder2 -Property Name | Where-Object {$_.SideIndicator -eq "<="} | ForEach-Object {

        #Copy the files that are not there
        copy-Item "$source\$($_.name)" -Destination "$destination" -Force
write-host RSCLIVE4 + $source\$($_.name) -foregroundcolor red
        }

If $folder2 doesn't contain any files I get this error:

Compare-Object : Cannot bind argument to parameter 'DifferenceObject' because it is null.
At C:\jb\Scripts\Compare_Sync_SeleniumtoElementsFSIISLogs\Compare_syncSelen_to_elementsFS.ps1:73 char:15
+ Compare-Object <<<<  $Folder1 $Folder2 -Property Name | Where-Object {$_.SideIndicator -eq "<="} | ForEach-Object {
    + CategoryInfo          : InvalidData: (:) [Compare-Object], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.CompareObjectCommand

I'm assuming that its somthign to do with the fact there is no "<=" in the side indicator.  Is it possible to add an {or is NULL} in there to compensate for this?

Thanks


Alter De Ruine

export disabled users that have mail attribute

$
0
0

hello. thanks for the time.  i have another question.  I had 2 tasks.  1 to get a list of all disabled users in the last 90days with no email attribute. i was able to achieve that. next is to get a list of all disabled users in the last 90days with an mail attribute only.  I guess it sounds dumb that I got the first but not the second.  I am just confused and hit a wall...

I combed through and pieced this together for AD users with null mail attribute:

$90Days= (get-date).adddays(-90)

get-aduser -searchbase "OU=disabled,DC=corporation,dc=com" -filter {(lastlogondate -notlike "*" -OR lastlogondate -le $90Days) -AND (passwordlastset -le $90days) -AND (enabled -eq $false)} | where-object {$_.mail -eq $null} | select-object name,lastlogondate,passwordlastset,mail

This one gives me all disabled users with or without mail attribute. I just want the ones with mail attributes:

$90Days= (get-date).adddays(-90)
get-aduser -searchbase "OU=disabled,DC=corporation,dc=com" -filter {(lastlogondate -notlike"*" -OR lastlogondate -le $90Days) -AND (passwordlastset -le $90days) -AND (enabled -eq $false)} -properties lastlogondate,passwordlastset,mail | select-object name,lastlogondate,passwordlastset,mail |Export-csv c:\scripts\disabled\aliases.csv

thanks for the efforts and input.

backup and restore a specific registry key in powershell

$
0
0

I am building a 2 scripts one to backup a large number of files and system settings and one to restore them after the system is re-imaged.  I have everything set in the script but 1 thing I dont know how to do. I am looking to backup the following registry key.

HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook

If someone can give me both commands to backup the registry key and restore it.

Help for New-Mailcontact and Set-Contact

$
0
0

Hi,

Objective for the script: 

I have been trying to write a script so I can create New-Mailcontact using CSV file, if not already exist in ActiveDirectory.

If already exist in Active Directory then skip New-MailContact command and  just run Set-Contact.

Problem in the script: -

It does create  new Mailcontact if not already exist in AD.

1) If MailContact exist in the AD it still tries to create that MailContact and then it errors it out since AD would not let it create because it is not unique and then it moves to next entry and does the same until it finds the entry which is new then obviously AD let it creates it.

2) It create a new Mailcontact but it never goes to Set-Contact.

In summary 2 problems

1) It does not skip the entry if that already exist in AD.

2) It never goes to Set-Contact.

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

$CSV = Import-CSV F:\contacts\contacts1.csv
$Abc =  Get-MailContact -OrganizationalUnit "OU=company_Contacts,OU=Contacts,DC=test,DC=com" $_.alias | Select alias

foreach ($entry in $Csv) {

if ($entry.mailnickname -ne $abc.alias)
{
    New-MailContact -Name $entry.DisplayName -DisplayName $entry.DisplayName -FirstName $entry.givenName -LastName $entry.sn -OrganizationalUnit "OU=company_Contacts,OU=Contacts,DC=test,DC=com" -ExternalEmailAddress $entry.mail -Alias $entry.mailNickname
 }
Else
{ set-contact -identity $entry.mailNickname -Phone $entry.telephoneNumber -MobilePhone $entry.Mobile -Office $entry.physicalDeliveryOfficeName -Title $entry.Title -Department $entry.Department
}
}

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

Where am I going wrong?



Raman

Examples of using Powershell to import SharePoint Content Types from a CSV file

$
0
0

Hi, I am working on a script to import Content Types from a CSV document.  Does anyone have a good working sample of being able to do this on the SharePoint 2013 platform?

Thanks


Leland Usher SharePoint Developer/Administrator

How to grant permission to private key from powershell

$
0
0
I'm trying to find a way to grant permissions for private key from powershell script. Certificate is stored in CNG. All ideas are welcome.

Help to run a blinking text code in background

$
0
0

Hi All,

I found a code on internet ,working code of  a function to blink a text. I am using the function in my pwershell application . But I want the blinking code to run in background.

The function is 

$function = {
function Blink-Message {
 param([String]$Message,[int]$Delay,[int]$Count,[ConsoleColor[]]$Colors) 
    $startColor = [Console]::ForegroundColor
    $startLeft  = [Console]::CursorLeft
    $startTop   = [Console]::CursorTop
    $colorCount = $Colors.Length
    $line = "$message"
    for($i = 0; $i -lt $Count; $i++) {
        [Console]::CursorLeft = $startLeft
        [Console]::CursorTop  = $startTop
        [Console]::ForegroundColor = $Colors[$($i % $colorCount)]
        [Console]::WriteLine($Message)
        Start-Sleep -Milliseconds $Delay
    }
    [Console]::ForegroundColor = $startColor
}
}

# Set-Alias blink Blink-Message

#write-host -NoNewline "hello  "; Blink-Message "blink" 1000 15 "red,black" | Receive-Job 
write-host -NoNewline "hello1  "; start-job -InitializationScript $function -ScriptBlock {Blink-Message} -InputObject "blink1",1000,15,"red,black" | Receive-Job
write-host -NoNewline "hello2  "; start-job -InitializationScript $function -ScriptBlock {Blink-Message} -InputObject "blink2",1000,15,"red,black" | Receive-Job  
write-host -NoNewline "hello3  "; start-job -InitializationScript $function -ScriptBlock {Blink-Message} -InputObject "blink3",1000,15,"red,black" | Receive-Job

I am expecting output like

hello1 blink1

hello2 blink2

hello3 blink3

where blink1,blink2,blink3 all blink synchronously . I have PS ver 2.0 .

I tried few methods but did not help . Please help.

Thanks.

Spark.

powershell, replace an Array object with nothing

$
0
0

I need to get rid of an object ($deletehostname) in an array and have the following code:

if ($BackConnectionHostnamesExists) { $zero="" $ExistingHostnames = ($BackConnectionHostnamesExists.BackConnectionHostnames) $ExistingHostnames = $ExistingHostnames.replace($deletehostname, $zero) Set-ItemProperty HKLM:\System\CurrentControlSet\Control\Lsa\MSV1_0 -Name "BackConnectionHostnames" -value $ExistingHostnames }

$deletehostname is successfully removed, but it is replaced by an open line.

so if $deletehostname = test3, my result is:

test1

test2



test4

test5

I would love to get rid of that empty space! So is it possible to replace by nothing?

br

Bjorn


GroupPolicy - List GPO's where specific ADgroup dont have modify-permission

$
0
0

Hey,

I want a list of GPO's where specific ADgroup dont have modify-permission. This is what I have so far:

Function Get-AllGPPermissions {

[CmdletBinding()]

Param()

Begin 
    {
    # Set strict-mode
    Set-Strictmode -version 2
    
    # Import the Group Policy Module
    Import-Module GroupPolicy
    
    $Dato = (Get-Date).ToString('yyyy-MM-dd')
    $Path = "\\server\folder\script\PowerShell\GroupPolicy"
    $CSV  = $path + "\" + $dato + "-Output.csv"
    }#END:Begin

Process 
    {
    $Array = $null
    $Array = @()
    $Domains = "domain.com","domain2.com"    
    Foreach ($Domain in $Domains)
        { 
        $GPOs = Get-GPO -All -Domain $Domain | Where {$_.GpoStatus -ne "AllSettingsDisabled"}
        Foreach ($GPO in $GPOs)
            {
            $Name = $GPO.DisplayName
            $Permissions = Get-GPPermissions -Name $Name -Domain $Domain -TargetType Group -All
            Foreach ($Permission in $Permissions)
                {
                $Rettighet = $Permission.Permission
                $Gruppe    = $Permission.Trustee.Name<#
                Write-Host "`nGruppe:" $Gruppe
                Write-Host "Rettighet:" $Rettighet
                Write-Host "Gpo:" $Name
                #>
                $Out = New-Object PSObject
                $Out | Add-Member -Type NoteProperty -Name Navn -Value $Name
                $Out | Add-Member -Type NoteProperty -Name Rettighet -Value $Rettighet
                $Out | Add-Member -Type NoteProperty -Name Gruppe -Value $Gruppe
                $Out | Add-Member -Type NoteProperty -Name Domene -Value $Domain
                $Array += $out
                }
            }
        }
    $Array #| Export-Csv $CSV -delimiter ";" -en unicode -notype"$CSV"
    }#END:Process
End
    {

    }#END:End

}#END:Function
Get-AllGPPermissions

Import-Module Keep Prompting for Credentials!

$
0
0

Hello,

I'm trying to establish "Implict Remoting" session and exported all of the imported cmdlets into a module. But when I first execute any command, it asking me to enter password when it's trying to establish a implicit-remoting session regardless of -Credential parameter.

Import-Module -Name "MyModules" -Credential $Creds

Import-Module : A parameter cannot be found that matches parameter name 'Credential'.

Due to this, I'm unable to fully automate the script that I'm developing. Is there anyway to pass credentials when "Import-Module" trying to establish Implicit Remoting session?

Any further help/guidance would be greatly appreciated. Thank you!

UPDATE

When I first execute Import-Module command:

Creating a new session for implicit remoting of "Get-Mailbox" command...

When I click "Cancel" button twise at Password Prompt window:

WARNING: Commands available in the newly opened remote session are different than when the

implicitremoting module was created. Consider recreating the module using Export-PSSession cmdlet.






how to controll slow response times for negative? when using $tcpobject = new-Object system.Net.Sockets.TcpClient

$
0
0

hi,

I am trying to quickly scan some servers to see what ports are open and have come across this:

$tcpobject = new-Object system.Net.Sockets.TcpClient

It works fine but  the time out for a NEGATIVE answer is very long (~20seconds !), how can I control /wrap this so if  a positive answer is not received in x mSecs then I will consider this a negative.

I see a sendtimeout property but I cannot figure out how to set it

I also intend to try this for UDP

Roy


roys99



Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>