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

Comparing cmdlets: [search-adaccount -accountdisabled] vs. [get-aduser -ldapfilter "(&(objectcategory=person)(objectclass=user)(useraccountcontrol:1.2.840.113556.1.4.803:=2))"]

$
0
0

Hello all,

I have searched on Google but have not been able to find much information about a comparison between the following 2 cmdlets, which return a different ".count" number for the number of disabled users, so the underlying queries must be different and I'm wondering how:

Search-ADAccount -AccountDisabled

get-aduser -ldapfilter "(&(objectcategory=person)(objectclass=user)(useraccountcontrol:1.2.840.113556.1.4.803:=2))"

I can of course tell what the second command is doing, but I can't find any explanations on what exactly the first cmdlet is doing.

The only thing I can find is info from TechNet, on the [Search-ADAccount -AccountDisabled] cmdlet:

"Specifies a search for accounts that are disabled. An account is disabled when the ADAccount Enabled property is set to false."

I can't find any information on this "ADAccount Enabled" property. Does anyone know what this means, and what criteria this cmdlet is using to find disabled users?


Powershell script to list last reboot and number of updates needed on all servers on domain

$
0
0
Need a powershell script that list number of updates needed and last reboot time for all servers in the domain.

~ Paul

Working with variables with spaces

$
0
0

I am trying to use the following script to generate DFSR Health Reports:

$date=Get-Date-formatd-MMM-yyyy

$ReplicationGroup1="SiteA"

$ReplicationGroup1="Site B"

$MemberServer="servername.com"

$SaveReportLocation1="C:\Reports\$ReplicationGroup1-$date"

$SaveReportLocation2="C:\Reports\$ReplicationGroup2-$date"

dfsradminhealthnew/RgName:$ReplicationGroup1/RefMemName:$MemberServer/repname:$SaveReportLocation1

dfsradminhealthnew/RgName:$ReplicationGroup2/RefMemName:$MemberServer/repname:$SaveReportLocation2

Send-MailMessage -From$from-To$to-SmtpServer$SMTPserver-Subject$subject-Body$emailbody-Attachments"$SaveReportLocation1.html","$SaveReportLocation2.html

No problems with $ReplicationGroup1 with no spaces but can't get it to work when the site name has spaces i.e. $ReplicationGroup2"

I've tried enclosing in every double quote/single quote combination I could find on the web with no success.  Haven't gotten that far yet, but I suspect I'll also have an issue with the $SaveReportLocation2 variable, within the dfsradmin string, as well as the e-mail attachment (which I need to append ".html" to as well for the same reasons.

Help!!

Thanks

Handle double semicolons in CSV with Powershell

$
0
0

Hi,

I have a challenge for a project of mine where I have to import CSV files.
A line in the CSV file will look something like this:

column1;column2;column3;column4;column5;column6
abc;def;ghi;ijk;lmn;opq
def;def;ghi;ijk;lmn;xyz

Almost all the files are handled easily but I have an issue with some of the CSV files where a semicolon is present in the data. If I import these files an import would look like this:
column1;column2;column3;column4;column5;column6
abc;def;ghi;ijk;lmn;opq
def;def;ghi;ijk;lmn;NULL;xyz

You see that a NULL value is now present in the table and that the amount of columns don't add up.

Does anybody know of a method to capture these errors and how to solve it?

Thanx in advance


importing a txt file

$
0
0

I am using the following code i found to import a text file that will contain some param:

Get-Content "C:\settings.txt" | foreach-object -begin {$h=@{}} -process { $k = [regex]::split($_,'='); if(($k[0].CompareTo("") -ne 0) -and ($k[0].StartsWith("[") -ne $True)) { $h.Add($k[0], $k[1]) } }

when get the contents of the file,  URLTORSource gets chopped, and cuts off "=1.1.1.1&port="", and can't figure out why.

URLTORSource="https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=1.1.1.1&port="

Thank you for your Help.

The settings.txt file are as such:


[General]
MySetting1=value

[Locations]
InputFile=""
OutputFile=""

[Files]
Blocklist=Blocklist.txt
ArchiveLocation=C:\Scripts\Tor\Archive\

[URL]
URLTORSource="https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=1.1.1.1&port="


[Other]
Profile=Any 
Interface=Any  
WaitForTime=20
VerboseLogging=True

Passing line breaks in paramaters

$
0
0

Hi,

I am new at this sorry and looking for some help.  I have put together a script using New-OSCEXOAppointment to create exchange appointments via powershell and using it to integrate with one of our products.  I need to execute the script via a bat file.

The command is:

New-OSCEXOAppointment -Identity $Identity -Subject $Subject -Body $Body -EndDate $EndDate -Location $Location -StartDate $StartDate -RequiredAttendees $RequiredAttendees -BusyStatus $BusyStatus -Category $Category

So the BAT file runs (for example):

powershell.exe -ExecutionPolicy Bypass -File c:\calendarscripts\CreateCalendarItem.ps1 -Identity "ben" -subject "test subject" -Body "Test body text:" -EndDate "2014-07-03T17:00:00" -Location "test location" -StartDate "2014-07-03T09:00:00" -RequiredAttendees "ben" -BusyStatus "oof" -Category "Green Category"

This runs successfully.  Unfortunately for the -Body parameter, i need to pass through multi line text like below:

Customer Name
Status
Test Body Text

Is it possible to pass this sort of text through as a parameter?

I hope that makes sense?
Many thanks

Ben

importing Contacts from csv into AD

$
0
0

Hi,

i have a csv file with one name and 4 phone number columns. I want to import those data into AD as a Contact. I get an error when i import a contact that has an empty phone number (does not matter which column is empty).

So i tried to make an if statement to check if the variable has data in it, but i cant get it to work.

CSV content (Outlook export):

Name;Telefon geschäftlich;Telefon geschäftlich 2;Weiteres Telefon;Mobiltelefon
Test 123;+00 1234677;;;+00 1234677
Test 123 456;+00 1234677;;;+00 1234677

Powershell Script:

$contacts = import-csv .\contacts.csv -delimiter ";" -Encoding UTF8
For ($i=1; $i -le $contacts.count; $i++) {

    New-ADObject -name $contacts[$i-1].Name -Path "OU=Contacts,OU=ACPOOE,DC=acpooe,DC=demo" -ProtectedFromAccidentalDeletion $false -Type Contact -OtherAttributes @{
        if ($contacts[$i-1]."Mobiltelefon") {mobile=$contacts[$i-1]."Mobiltelefon";}
        if ($contacts[$i-1]."Telefon geschäftlich") {telephoneNumber=$contacts[$i-1]."Telefon geschäftlich";}
        if ($contacts[$i-1]."Telefon geschäftlich 2") {homePhone=$contacts[$i-1]."Telefon geschäftlich 2";}
        if ($contacts[$i-1]."Weiteres Telefon") {ipPhone=$contacts[$i-1]."Weiteres Telefon"}
    }
}

I get the following Error:

At C:\Users\Administrator\Desktop\test\Untitled1.ps1:6 char:11+         if ($contacts[$i-1]."Mobiltelefon") {mobile=$contacts[$i-1]."Mobiltelefo ...+           ~
Missing '=' operator after key in hash literal.
At C:\Users\Administrator\Desktop\test\Untitled1.ps1:2 char:42+ For ($i=1; $i -le $contacts.count; $i++) {+                                          ~
Missing closing '}' in statement block.+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException+ FullyQualifiedErrorId : MissingEqualsInHashLiteral



Create Monthly Schedule Tasks for Managed Service Accounts in Windows Server 2012 R2

$
0
0

Understand about managed service accounts and how it can create schedule tasks using powershell commands.  I have created daily and weekly scheduled tasks successfully without issue.  Problem is I was not able to create a monthly schedule task for the MSA as the powershell commands does not support month options.  I have read the link below which suggested importing a working daily scheduled task, modify the XML and then import it back.  I tried that but will hit the "Launch failure" with error code "2147942402". 

http://social.technet.microsoft.com/Forums/windowsserver/en-US/18eb3f7e-ea54-4f60-8c0b-8659cad5e2d9/creating-a-scheduled-task-using-powershell-v4

  

I also tried creating a monthly task using GUI, and then change the user using the Set-ScheduledTask powershell command.  It also hit the same error.

   

Further testing shows the following behavior:

-  if I create a daily task using GUI, and modify the user using Set-ScheduleTask command, it works.  Monthly tasks fails.

-  If I use the import and export XML method, it works for daily tasks, but not for monthly task.

  

My server setup is as follows:

host: Windows Server 2012 R2

Domain Controller:  Windows Server 2008 R2

   

Did anyone manage to create a monthly Scheduled task for MSA?


Searching multiple arrays

$
0
0
I am attempting to assign servers in an array into 3 separate groups.  I am using PoshWSUS which populates the array with the FQDN of my servers as follows:
$wsus_unassigned = Get-PoshWSUSClientsInGroup "unassigned Computers" | select FulldomainName | Sort FulldomainName
In order to segregate the groups, I am using ADGroup Membership as a guide, populating them as follows:
$ad_alpha = Get-ADGroup "wsus alpha" -Properties * | Select -ExpandProperty members | Get-AdComputer | Select DNSHostName | Sort DNSHostName
I have two other groups called "Beta Servers" and "Production Servers" populated in the same manner.  I've verified that the formats of all the arrays match (ie. "server.domain.com") but my attempt to filter with the following gives me nothing:
Foreach ($server in $wsus_unassigned) {
 If ($ad_alpha -contains $server) { Write-Output "$($server.FullDomainName) is in alpha" | Out-File e:\WSUS\wsus_group_update.log -Append  }
 elseIf ($ad_beta -contains $server) { Write-Output "$($server.FullDomainName) is in beta" | Out-File e:\WSUS\wsus_group_update.log -Append }
 else { Write-Output "$($server.FullDomainName) is in production" | Out-File e:\WSUS\wsus_group_update.log -Append }
} 

I have tried using $server.FullDomainName and $($server.FullDomainName) for the -contains part but no joy.
Any ideas/suggestions on what I'm doing wrong or a better way to do this?

Use XML file to store configuration

$
0
0

Hi,
we have a script that store a password inside an XML file, the tag I find are:

<Password>
  <By>98</By>
  <By>226</By>
...
</Password>

well but when I esecute commands:

$secure = read-host -assecurestring

$encrypted = convertfrom-securestring -securestring $secure

$encrypted

to retrieve encrypted password I receive a text like: 01000000d08c9ddf0115d1118c7a00c04fc297eb01000...
when i can convert this tring to <by>011</by> etc...

Thanks!

Powershell script written on windows 8 not working on windows 7

$
0
0

Hi There 

I have written a script to convert media to h264 aac and i cant get it to work on windows 7 it fails to find paths eg bellow

if anyone could have a look and see what they think "Feel free to tidy up my code im not the best coder"

The Script works perfectly on windows 8

PS C:\FFMPEG> C:\FFMPEG\Media.ps1
------------------------------------------------------------------------------------

Not H264
Not AAC
Needs Encoding

Test Running
Not AAC
Not H264
Not MP4
Failed
Remove-Item : Cannot bind argument to parameter 'Path' because it is an empty string.
At C:\FFMPEG\Media.ps1:65 char:20
+         Remove-Item <<<<  $newVideo+ CategoryInfo          : InvalidData: (:) [Remove-Item], ParameterBindingValidationException+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.RemoveItemCommand
Remove-Item : Cannot find path 'C:\FFMPEG\bin\.json' because it does not exist.
At C:\FFMPEG\Media.ps1:67 char:20+         Remove-Item <<<<  $del2+ CategoryInfo          : ObjectNotFound: (C:\FFMPEG\bin\.json:String) [Remove-Item], ItemNotFoundException+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

Powershell Script in Question

#Set Media Location
$MediaStore = "Z:\Media\TV Shows\"
#Gets List Of Media
$VideoList = Get-ChildItem -Include @("*.mp4", "*.avi", "*.divx", "*.mov", "*.mpg", "*.wmv", "*.mkv") -Path $MediaStore -Recurse;
#Sets Working directory
Set-Location -Path "c:\FFMPEG\bin\";
#Conversion Codex
$SetVCodex = "libx264"
$SetACodex = "aac"
$SETFFProbArguements = "-v quiet -print_format json -show_format -show_streams"
#Only replace inbetween `"###`"  e.g `"h264`" becomes `"newcodec`" 
$vcodex = "            `"codec_name`": `"h264`","
$acodex = "            `"codec_name`": `"aac`","

#Probe
function Probe ($Media)
{
$resultst = "Success"
$newVideo = [io.path]::ChangeExtension($Item.FullName, 'ENC.mp4')
$newVideorevert = [io.path]::ChangeExtension($Item.FullName, 'mp4')
$finalVideo = [io.path]::ChangeExtension($Item.FullName, 'mp4')
$Encode = "NO"
$ffprobeArguments = "/C c:\FFMPEG\bin\ffprobe.exe $SETFFProbArguements `"$Media`" > `"$Media.json`""
Start-Process -FilePath C:\Windows\System32\CMD.exe -ArgumentList $ffprobeArguments -Wait
$json = "$Item.json"
$FoundVCodex = Get-Content $json | Select-String $vcodex
$FoundACodex = Get-Content $json | Select-String $acodex
Write-Host -ForegroundColor Magenta "------------------------------------------------------------------------------------"
Write-Host -ForegroundColor White "$Item"
#Checks Video test 1
    If($vcodex -notlike $FoundVCodex)    
    {
        Write-Host -ForegroundColor Yellow "Not H264"
        $Encode = "ENC"
    }
#Checks Audio test 2
    If($acodex -notlike $FoundACodex)
    {
        Write-Host -ForegroundColor Yellow "Not AAC"
        $Encode = "ENC"
    }
#Checks whether video needs encoding
    If ($Encode -eq "ENC")
    {
        #Starts Encoding if it does
        Write-Host -ForegroundColor Red "Needs Encoding"
        $ffmpegArguments = "/C c:\FFMPEG\bin\ffmpeg.exe -y -i `"$Item`" -vcodec $SetVCodex -acodec $SetACodex -strict -2 `"$newVideo`""
        Encode
        $result = testfile($newVideo)
        $del = "$Item`.json"
        $del2 ="$newVideo`.json"
            if($result -like $resultst)
            {
            Write-Host -ForegroundColor Green $result
            Rename-Item $Item "$Item`.old"
            Rename-Item $newVideo $newVideorevert
            Remove-Item $del
            Remove-Item $del2
            return
            }
        Write-Host -ForegroundColor Red $result
        Remove-Item $newVideo
        Remove-Item $del
        Remove-Item $del2
        return
}

#Checks whether video is already mp4 with ACC and H264
IF($Item.Extension -eq ".mp4")
{
        #Check if the Video Has passed test 1 and 2
        If ($Encode -eq "NO")
        {
            Write-Host -ForegroundColor Green "MP4 H264 and AAC - Looks Good"
            Remove-Item $json
            return
        }
}

#Checks whether video is already ACC and H264 but a different Container
IF($Item.Extension -ne ".mp4")
    {
            If ($Encode -eq "NO")
            {
                #Changes Container and cleans up
                Write-Host -ForegroundColor Green "Encoding"
                $ffmpegArguments = "/C c:\FFMPEG\bin\ffmpeg.exe -y -i `"$Item`" -vcodec copy -acodec copy `"$newVideo`""
                Encode
                $result = testfile($newVideo)
                $del = "$Item`.json"
                $del2 ="$newVideo`.json"
                if($result -like $resultst)
                {
                Write-Host -ForegroundColor Green $result
                Rename-Item $Item "$Item`.old"
                Rename-Item $newVideo $newVideorevert
                Remove-Item $del
                Remove-Item $del2
            return
                }
                Write-Host -ForegroundColor Red $result
                Remove-Item $newVideo
                Remove-Item $del
                return
            }
    }
}

#Encoding
function Encode ($Media)
{
Start-Process -FilePath C:\Windows\System32\CMD.exe -ArgumentList $ffmpegArguments -Wait
}

#Rename
function Rename($CleanItem)
{
Rename-Item $CleanItem "$CleanItem`.old"
Rename-Item $newVideo $finalVideo
}


#Tests file
function testfile($file)
{
Write-Host -ForegroundColor Cyan $file
$result = "Success"
$ffprobeArguments = "/C c:\FFMPEG\bin\ffprobe.exe $SETFFProbArguements `"$file`" > `"$file.json`""
Start-Process -FilePath C:\Windows\System32\CMD.exe -ArgumentList $ffprobeArguments -Wait
$testjson = "$file.json"
$TestFoundVCodex = Get-Content $testjson | Select-String $vcodex
$TestFoundACodex = Get-Content $testjson | Select-String $acodex
Write-Host -ForegroundColor Magenta "Test Running"
    If($acodex -notlike $TestFoundACodex)
    {
        Write-Host -ForegroundColor Yellow "Not AAC"
        $result = "Failed"
            If($vcodex -notlike $TestFoundVCodex)
            {
                Write-Host -ForegroundColor Yellow "Not H264"
                $result = "Failed"
                IF($file.Extension -notlike ".mp4")
                {
                    Write-Host -ForegroundColor Yellow "Not MP4"
                    $result = "Failed"
                }
            }
    }
$returnedresult = $result
return $returnedresult
}

#For Each file run the following
foreach ($Item in $VideoList) {
Probe($Item)
}




Using PowerShell 1.0 copy-item GroupPolicy Folder(C:\WINDOWS\system32\GroupPolicy)

$
0
0

Hello everybody,

This is my first time posting in this forum and i have encounted an issue i hope you can help i'm trying to create a powershell 1.0 script as this is for Windows XP to copy default policy back to their original folder then do a gpupdate on the copmuter so that the Local policy are returned to their default but i'm having access denied as this is user account and needed a way to make it run as an administrator but without success as i'm new powershell. 

Copy-Item 'C:\WINDOWS\system32\GroupPolicy\Original Group Policy for User and Machine\Machine\*' 'C:\WINDOWS\system32\GroupPolicy\Machine\'

Copy-Item 'C:\WINDOWS\system32\GroupPolicy\Original Group Policy for User and Machine\User\*' 'C:\WINDOWS\system32\GroupPolicy\User\'

Your help is much appreciated.

Script that enables mail users and kicks out two csv files

$
0
0

I am working on a script that will mainly be used as a scheduled task to enabled mailuser by calling the update-recipient command. 

But before it calls that command it will get for various issues that can cause errors.

Missing PrimarySMTP

Display name having a space at front or back.

The external email address being blank.

I have IF statements setup to check for those and then call a function that will save into an array the issue for that user. 

Here is the script

<#
    .SYNOPSIS
    Enable-MailUsers Synced Mail Users in the Exchange environment 
	THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE 
	RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
	Version .9, 30 June 2014
    .DESCRIPTION
    This script mail-enables Synced Mail Users and creates a CSV report of mail users that were enabled. 
    The following is shown:
	* Report Generation Time
	.PARAMETER SendMail
	Send Mail after completion. Set to $True to enable. If enabled, -MailFrom, -MailTo, -MailServer are mandatory
	.PARAMETER MailFrom
	Email address to send from. Passed directly to Send-MailMessage as -From
	.PARAMETER MailTo
	Email address to send to. Passed directly to Send-MailMessage as -To
	.PARAMETER MailServer
	SMTP Mail server to attempt to send through. Passed directly to Send-MailMessage as -SmtpServer
	.PARAMETER ScheduleAs
	Attempt to schedule the command just executed for 10PM nightly. Specify the username here, schtasks (under the hood) will ask for a password later.
	.EXAMPLE
    Generate the HTML report 
    .\Enable-MailUsers.ps1 -SendMail -MailFrom Chuck@Contoso.com -MailTo Admindl@contaso.com -MailServer ex1.contoso.com -ScheduleAs SvcAccount
    #>
param(
	[parameter(Position=0,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Send Mail ($True/$False)')][bool]$SendMail=$false,
	[parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail From')][string]$MailFrom,
	[parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail To')]$MailTo,
	[parameter(Position=3,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail Server')][string]$MailServer,
	[parameter(Position=4,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Schedule as user')][string]$ScheduleAs
	)



# Sub Function to neatly update progress
function _UpProg1
{
	param($PercentComplete,$Status,$Stage)
	$TotalStages=5
	Write-Progress -id 1 -activity "Mail enabled Objects" -status $Status -percentComplete (($PercentComplete/$TotalStages)+(1/$TotalStages*$Stage*100))
}

#Sub Function create ErrObject output
function _ErrObject{
Param($name,
      $errStatus
      )
If(!$err){
    Write-Host "error detected"
    $script:err = $True
    }
$ErrObject = New-Object -TypeName PSObject
$Errobject | Add-Member -Name 'Name' -MemberType Noteproperty -Value $Name
$Errobject | Add-Member -Name 'Comment' -MemberType Noteproperty -Value $errStatus
$script:ErrOutput += $ErrObject
}

# 1. Initial Startup

# 1.0 Check Powershell Version
if ((Get-Host).Version.Major -eq 1)
{
	throw "Powershell Version 1 not supported";
}

# 1.1 Check Exchange Management Shell, attempt to load
if (!(Get-Command Get-ExchangeServer -ErrorAction SilentlyContinue))
{
	if (Test-Path "D:\Exchsrvr\bin\RemoteExchange.ps1")
	{
		. 'D:\Exchsrvr\bin\RemoteExchange.ps1'
		Connect-ExchangeServer -auto
	} elseif (Test-Path "D:\Exchsrvr\bin\Exchange.ps1") {
		Add-PSSnapIn Microsoft.Exchange.Management.PowerShell.Admin
		.'D:\Exchsrvr\bin\Exchange.ps1'
	} else {
		throw "Exchange Management Shell cannot be loaded"
	}
}

# 1.2 Check if -SendMail parameter set and if so check -MailFrom, -MailTo and -MailServer are set
if ($SendMail)
{
	if (!$MailFrom -or !$MailTo -or !$MailServer)
	{
		throw "If -SendMail specified, you must also specify -MailFrom, -MailTo and -MailServer"
	}
}


# 1.3 Check Exchange Management Shell Version
if ((Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Admin -ErrorAction SilentlyContinue))
{
	$E2010 = $false;
	if (Get-ExchangeServer | Where {$_.AdminDisplayVersion.Major -gt 14})
	{
		Write-Warning "Exchange 2010 or higher detected. You'll get better results if you run this script from an Exchange 2010/2013 management shell"
	}
}else{
    $E2010 = $true
    $localserver = get-exchangeserver $Env:computername
    $localversion = $localserver.admindisplayversion.major
    if ($localversion -eq 15) { $E2013 = $true }

}

#Get date
$filedate = get-date -uformat "%m-%d-%Y" 
$filedate = $filedate.ToString().Replace("0", "")


#Get the valid users that are not mail-enabled
_UpProg1 1 "Getting User List" 1
#$Users = Get-mailuser -ResultSize unlimited -OrganizationalUnit "R0018.COLLABORATION.ECS.HP.COM/Accounts/AbbVienet/Users" | ?{$_.legacyexchangeDN -eq ""}

$i = 0
$output = @()
$errOutput = @()
$err = $False

#2 Process users
ForEach ($User in $Users){
    $i++
    _UpProg1 ($i/$Users.Count*100) "Updating Recipients" 2
    If ($user.ExternalEmailAddress -eq $null){
    _ErrObject $user.Name, "Missing External Email Address"
    }
    ElseIf($user.DisplayName -NotLike "* "){ 
    _ErrObject $user.Name, "DisplayName contains a trailing space"
    }
    ElseIf($user.DisplayName -NotLike "_*"){ 
    _ErrObject $user.Name, "DisplayName contains a Leading space"
    }
    ElseIf($user.PrimarySmtpAddress -eq $null){ 
    _ErrObject $user.Name, "Missing Primary SMTP address"
    }
    Else{
    #Disable EmailAddressPolicy on these users
    Set-Mailuser $User.Name -EmailAddressPolicyEnabled $false
    #pass to Update-recipient 
    Update-Recipient $User.Name
    $LEDN = Get-MailUser $User.Name | Select {$_.LegacyExchangeDN}
        If ($LEDN -ne ""){
        $object = New-Object -TypeName PSObject
        $X500 = "x500:" + $LEDN.'$_.LegacyExchangeDN'
        $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value $User.Name
        $object | Add-Member -Name 'x500' -MemberType Noteproperty -Value $X500
        $output += $object
        }
    }
}

#Creating CSVFile Output
_UpProg1 99 "Outputting CSV file 3" 3
$CSVFile = "c:\scripts\Mail-enable\Mailenabled_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
If($err){
$ErrCSVFile = "c:\scripts\Mail-enable\ProblemUsers_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
$errOutput | Select-Object Name, Comment | ConvertTo-CSV -NoTypeInformation > $ErrCSVFIle
}
$Output | ConvertTo-Csv -NoTypeInformation > $CSVFile


if ($SendMail)
{
	_UpProg1 95 "Sending mail message.." 4
    If($err){
	Send-MailMessage -Attachments $CSVFile,$ErrCSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
    }
    Else{
    Send-MailMessage -Attachments $CSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
    }
}

if ($ScheduleAs)
{
	_UpProg1 99 "Attempting to Schedule Task.." 4
	$dir=(split-path -parent $myinvocation.mycommand.definition)
	$params=""
	if ($SendMail)
	{
		$params+=' -SendMail:$true'
		$params+=" -MailFrom:$MailFrom -MailTo:$MailTo -MailServer:$MailServer"
	}
	$task = "powershell -c \""pushd $dir; $($myinvocation.mycommand.definition) $params\"""
	Write-Output "Attempting to schedule task as $($ScheduleAs)..."
	Write-Output "Task to schedule: $($task)"
	schtasks /Create /RU $ScheduleAs /RP /SC DAILY /ST 22:00 /TN "Enable Mail Users" /TR $task
}

The Problem is that when I look at the $errOutput I see things but when I pipe the $erroutput to convertTo-CSV I get this within the CSV file. I think its because I an calling a function to do the updating. But not sure.


Jeff C

create buld user and modify attributes

$
0
0

Hi 

I just started with powershell and really could need some help regarding creating bulk users accounts.

I need to create new users with the follwing attributes filled in.

GidNumer                         65050
loginShell/bin/sh
mssFU30nameblblblbl
uidhdfhdfhdh
uidNumber65555
unixHomeDirectory           /home/1245

I cannot find these attributes in Set-aduser.

Is there a way in powershell that I can create new users by cvs and sets the needed attributes?

Kind regards

Rene de Vries





how to abort an advanced function from within the BEGIN block? and what about the rest of the pipeline?

$
0
0

Hello,

What is the proper way to abort processing of an advanced function from within the BEGIN block?

e.g., I need to test for a condition within the BEGIN block and if met, abort the function altogether... don't run the PROCESS and END blocks...

1. how would I do this?

2. If I do, will processing of the pipeline abort? In other words, my function may be used in the pipeline, it's output as input to the next in the chain... obviously if I abort my function, I need the whole chain to stop, otherwise the next in the chain would break.

Essentially I'm creating a group of functions that can all work nicely together via the pipeline... however I have a couple cases where I will be required to prompt a user to confirm what is about to happen (I need logic in the BEGIN block to determine if I need to prompt for confirmation) and allow them the opportunity to abort.... if they are only running the one function, no problem (but I'm still not sure how? break? return?), but if they are pipeing that function to another, then I assume there will be a problem, can the whole pipeline be aborted?



Is there an Exclude switch for TAKEOWN?

$
0
0

I have a large number of old XP profile folders and all the new .V2 profile folders in the same directory on a server share.

Unfortunately when these profiles were created, they used default Windows NTFS settings which did not include the Administrators group.

So now I want to take ownership of all the XP profile folders so I can delete them while leaving the *.V2 profile folders alone.

TAKEOWN works great but I am unable to figure out how to exclude *.V2 folder names.

Does TAKEOWN not have an -Exclude switch or a way to accomplish what I'm trying to do? Thanks in advance.

Printer info on Citrix servers

$
0
0

I am trying to write a Powershell script to gather information from my Citrix servers.  Specifically, I am trying to find out which servers have the XPS Document Writer installed on them.  The first script I wrote gave me all the servers that had the XPS Document Writer driver installed however,  I don't care if the driver is installed, I only want to know if it appears in the Devices and Printers on the server.  The second script I wrote gave me all the servers that had the XPS Document Writer in the Devices and Printers on each server however these are live servers with users connected so it also gave me all users that had their XPS Doc Image Writer mapped (ie: Microsoft XPS Document Writer (from xxx in session xxx)) when connecting to the server.  Again, I am only trying to identify which servers have the XPS Document Writer  in the Devices and Printers.
Does anyone know how I can filter to get the server information only and none of the clients?  Here is the code I am currently using:

$servers = Get-Content C:\Scripts\servers.txt
ForEach ($server In $servers)
{
$outfile = "C:\Scripts\printerlist.csv"
Get-WmiObject -Class Win32_Printer -ComputerName $server | where {$_ -match 'Microsoft XPS Document Writer'} | select @{N="ServerName";E={$server}},Name | export-csv -NoTypeInformation -append $outfile
}
Thanks for any insight!

problem loadin snapin

$
0
0

Hello.

I got this simple script:

'start' | Set-Content 'c:\scripts\log.txt'

if ( (Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue) -eq $null ){   

'in if pre add' | Add-Content 'c:\scripts\log.txt'   

Add-PsSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010

'end if' | Add-Content 'c:\scripts\log.txt'

}


If I run it as intercative user (in remote dsktop), all went well. If I run it with zabbix agent (run as service with local system account) the script dies and "end if" string is not write to file. This is the call from zabbix: powershell.exe -File c:\scripts\DiscoveryMBS.ps1

adding

get-pssnapin -registered | Add-Content 'c:\scripts\snapin.txt' 

before if block, this list is written to file:

Microsoft.Exchange.Management.PowerShell.E2010
Microsoft.Exchange.Management.PowerShell.Setup
Microsoft.Exchange.Management.Powershell.Support

so I don't understand why it cannot run add-pssnapin and the script dies. I try to catch exception, but it doesn't work, script simply dies on add-pssnapin call

Giovanni


Problem with pulling computer names from txt file or a csv file

$
0
0

Hi there.

I am having an issue with being able to pull computer names from a file in order to fun some commands on them. Here is the main issue. Below is a copy of my code that pulls new computers added to AD in the last 3 hours and creates a txt file with the list. I am then just trying to test-connection but it never runs anything on the contents of the file. Weird though, I can manually copy and paste into another text file, and then it works fine.. Not sure whats going on. Any help??? Feel free to leave tips if you know an easier way than the way I am trying to pull these computers.

Get-ADComputer -Filter {name -like $temp} -Properties whenCreated | Where-Object { (((Get-Date).Day) -eq ($_.whenCreated).Day)  -and (((Get-Date).Hour - ($_.whenCreated).Hour) -le 3)} | Select Name | Sort -Descending whencreated | Out-File .\test.txt
Btw. I don't get any errors when trying things with the file. Just nothing ever happens. And the $temp is a placeholder for earlier in the code the user can enter what to search AD for to be more specific like room number or division.

Get-ADGroupMember - raising "MaxGroupOrMemberEntries" limit produces error "Unable to contact the server"

$
0
0

Hi out there,

actually i have a problem with the Powershell command "Get-ADGroupMember". One customer has a few groups with more then 5.000 members, so this command will run into the "MaxGroupOrMemberEntries" limit.

Domain functional level is "Windows Server 2003", but there are already a few Windows 2008 R2 DC´s installed with ADWS service configured.

With default "MaxGroupOrMemberEntries" setting the command will result with the limitation error:

Get-ADGroupMember "Sharepoint Users" -Server DC-w2k8r2
Get-ADGroupMember : The size limit for this request was exceeded
At line:1 char:1
+ Get-ADGroupMember "Sharepoint Users" -Server DC-w2k8r2
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Sharepoint Users:ADGroup) [Get-ADGroupMember], ADException
    + FullyQualifiedErrorId : The size limit for this request was exceeded,Microsoft.ActiveDirectory.Management.Comman
   ds.GetADGroupMember

When changing the value to "10000" (    <add key="MaxGroupOrMemberEntries" value="10000" /> ), and restarting service (for troubleshooting also the whole server) i will get this error:

Get-ADGroupMember "Sharepoint Users" -Server DC-w2k8r2
Get-ADGroupMember : Unable to contact the server. This may be because this server does not exist, it is currently
down, or it does not have the Active Directory Web Services running.
At line:1 char:1
+ Get-ADGroupMember "Sharepoint Users" -Server DC-w2k8r2
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (Sharepoint Users:ADGroup) [Get-ADGroupMember], ADServerDownE
   xception
    + FullyQualifiedErrorId : Unable to contact the server. This may be because this server does not exist, it is curr
   ently down, or it does not have the Active Directory Web Services running.,Microsoft.ActiveDirectory.Management.Co
  mmands.GetADGroupMember

BUT, i can query other security groups successfully! I´ve changed the value on two different W2k8 R2 DC´s with the same result. The query runs round about one minute before the (timeout?) message is coming up.

Does anyone has an idea? Do i have to change this value on all DC´s running ADWS? The idea was to only change it on one DC and fix the query against this server (with the parameter "-Server").

Thanks in advance.

Dennis

Viewing all 21975 articles
Browse latest View live


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