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

What am I missing exactly?

$
0
0

Hello everyone, so I have coded this a couple of different ways and I am looking for the most efficient way of doing this (I'm new to PS so please bear with my incompetence -- I am going through PS training so one day I will be answering questions rather than asking them :) )

Essentially I need to be able to recurse a directory and log all files to a txt document when matched against an array. My code currently looks like this, however, it's not returning any results:

$audioFileExtensions = @(".aac",".aif",".aiff",".asf",".asx",".au",".avi",".flac",".m3u",".m4a",".mid",".midi",".mov",".mp1",".mp2",".mp3",".mp4",".mpa",".mpe",".mpeg2",".mpeg3",".mpg",".ogg",".qt",".qtw",".ram",".rm",".mi",".mvb",".snd",".swf",".vob",".wav",".wax",".wma",".wmv",".wvx")

Get-ChildItem -Path \\MHT-FS1\UserHomeDrives -Recurse | Where-Object {$_.Extension -contains $audioFileExtensions} | Select-Object FullName > C:\audioFileResults.txt

I've also created a forEach statement and although this works, it seems to be very inefficient and slow as it is looping through each item in the array and performing the recursive GCI method. 

How would I best write this code to produce the results I am looking for in the most efficient manner?

Thanks in advance!

Cheers,

G-


check a Socket to machine C(IP & port) to machine B (IP) and from my local machine A.

$
0
0
Team,

I am trying to check a Socket to machine C(IP & port) to machine B (IP) and from my local machine A.


AliahMurfy

An attempt to connect to WMI on 'lsd' failed with the

$
0
0

Hi,

When I attempt to join a secondary replica to an availability group I get the warning below.

Anyone know how I can worked around this ?

Thanks,

WARNING: Could not obtain SQL Server Service information. An attempt to connect to WMI on 'lsd' failed with the
following error: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
WARNING: Could not obtain SQL Server Service information. An attempt to connect to WMI on 'lsd' failed with the
following error: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
WARNING: Could not obtain SQL Server Service information. An attempt to connect to WMI on 'lsd' failed with the
following error: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Install SCCM client remotely with admin rights

$
0
0

Hi,

I want to deploy SCCM 2012 R2 clients remotely via PowerShell script running on an admin computer with the following commands :

$Computers = Get-Content C:\Computers.txt

$Computers | % { Copy-Item -Path C:\Temp\ccmsetup.exe -Destination \\$_\C$\RemoteTemp\ }

Invoke-Command -ComputerName $Computers -ScriptBlock {\\$_\C$\RemoteTemp\ccmsetup.exe /mp:MP01}

When I run the PS script, the client is not installed on remote computers. When I run the ccmsetup via command line locally, there is a popup displaying if I want to allow the EXE execution. When I click on YES, the client is well installed. So I want to know if there is a solution to do it from my PS script with admin right bypassing UAC on remote computers ?

Thanks.

PowerShell question on Using the New-ADUser command along with something called -Name

$
0
0

I m studying for the server 2008 R2 AD Microsoft certification. In addition, its covering power shell right now which is something I really enjoy learning about, but get confused with as well.

The command they use in the book is the following.

PS C:\Users\Administrator> New-ADUser -SamAccountName "TestOut" -UserPrincipleNa
me "TestOut@Bwcat.net.int" -GivenName "Test" -Surname "out" -DisplayName "Testout" -Name "Testout" -Enabled $true -Path "CN=users,DC=bwcat,DC=net,DC=int" -AccountPassword {Read-Host -AsSecureString "Enter Account Password"}

ERROR I GET

New-ADUser : Cannot evaluate parameter 'AccountPassword' because its argument i
s specified as a script block and there is no input. A script block cannot be evaluated without input.
At line:1 char:224
+ New-ADUser -SamAccountName "TestOut" -UserPrincipleName "TestOut@Bwcat.net.int" -GivenName "Test" -Surname "out" -DisplayName "Testout" -Name"Testout" -Enabled $true -Path "CN=users,DC=bwcat,DC=net,DC=int" -AccountPassword <<<<  {Read-Host -AsSecureString "Enter Account Password"}
    + CategoryInfo          : MetadataError: (:) [New-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.ActiveDirectory.Management.Commands.NewADUser

PS C:\Users\Administrator>

I just threw together a AD DC on Virtual Box and called the domain name BWCAT.NET.INT.  I have not setup anything else on the server except for the power shell stuff. no DNS, or DHCP, no exchange or anything like that.  Just a server 2008 R2 virtual box for learning.

I can create the user account using the simple form of the command (New-ADUser, as well as delete using Remove-ADUser), but cannot figure out some of the other stuff he does as he does not explain it out fully in the video.   I am using the Administrator Active Directory Module for windows PowerShell.

If someone could shed some light on this that would be great.

there are currently no logon servers available to service the logon request

$
0
0

Hello All,

I have a windows server 2012 R2 in that i have almost 15 Vms running. So recently i configured NIC Teaming. After this all the VMs are working fine except one VM which is my ADFS server. I am unable to login with my domain id, i am only able to login with local admin account. i am not able to connect to internet also. i am even unable to ping my local gateway or DNS. Please help me in this


Thanks

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

Approve Updates By Computer Groupt

$
0
0
I've found this script to ApproveUpdatesByComputerGroupt and it works, my problem is now, I only need to approve Classification  'Critical Updates' 'Security Updates' 'Updates', because I will not approve service packs for OS / SQL, etc. 

I'm using SCCM, but Failover Cluster should I use WSUS.

But no matter what I've tried, I can not really get it to work, so .. 


Help Help

# ApproveUpdatesByComputerGroup.ps1
 
[void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")
 
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer()
 
$ComputerTargetGroups = $wsus.GetComputerTargetGroups()
Write-Host "Warning: This will approve all NotApproved updates for a Computer Group" -ForegroundColor Red
Write-Host "Computer Groups"
$Count = 0
foreach ($ComputerTargetGroup in $ComputerTargetGroups) {
    Write-Host $Count - $ComputerTargetGroup.Name
    $Count++
}
$ComputerGroupToUpdate = Read-Host "Select Computer Group to update. [0 - $($Count-1)]"
Write-Host "Finding all updates needing approval and approving them"
 
$ComputerGroupName = $ComputerTargetGroups[$ComputerGroupToUpdate].Name
$ComputerGroupId = $ComputerTargetGroups[$ComputerGroupToUpdate].Id
 
$ComputersToScan = $wsus.GetComputerTargetGroup($ComputerGroupId).GetComputerTargets()
foreach ($ComputerToScan in $ComputersToScan) {
 
    $ComputerTargetToUpdate = $wsus.GetComputerTargetByName($ComputerToScan.FullDomainName)
    # Get all Not Installed updates available to the computer
    $NeededAndNotInstalled = $ComputerTargetToUpdate.GetUpdateInstallationInfoPerUpdate() | where {
                                                                                                   ($_.UpdateInstallationState -eq "NotInstalled") `
                                                                                                   -and ($_.UpdateApprovalAction -eq "NotApproved")}
    foreach ($UpdateToApprove in $NeededAndNotInstalled)
    {
        Approve-WsusUpdate -Action Install -TargetGroupName $ComputerGroupName -Update $(Get-WsusUpdate -UpdateId $UpdateToApprove.UpdateId) -Verbose
    }
 
}
Write-Host "Done approving updates"
sleep -Seconds 5

Assist with my SQL Reporting Script

$
0
0

I have started writing a HTML SQL reporting script based off of Jeffrey Hicks tutorial

Here is my entire script:

###################START SCRIPT#####################################

#requires -version 3.0

#Create a SQL Server report of said SQL environment

[cmdletbinding()]

Param(
[string]$computername=$env:computername,
[string]$path="$env:temp\sqlrpt.htm"
)

#define an empty array to hold all of the HTML fragments
#the fragments will break apart each HTML section in the final output so that you can out whatever information you like
$fragments=@()

#save current location so I can set it back after importing SQL module
$curr = get-location

#import the SQL module
Import-Module SQLPS -DisableNameChecking
#change the location back
set-location $curr

#get uptime
Write-Verbose "Getting SQL Server uptime"
$starttime = Invoke-Sqlcmd -Query 'SELECT sqlserver_start_time AS StartTime FROM sys.dm_os_sys_info' -ServerInstance $computername -database master
$version = Invoke-Sqlcmd "Select @@version AS Version"

#create an object
$uptime = New-Object -TypeName PSObject -Property @{
 StartTime = $starttime.Item(0)
 Uptime = (Get-Date)-$starttime.Item(0)
 Version = $version.Item(0).replace("`n","|")
}

$tmp = $uptime | ConvertTo-HTML -fragment -AS List
#replace "|" place holder with <br>"
$fragments += $tmp.replace("|","<br>")


#SQL Host Information
$smo = new-object ('Microsoft.SqlServer.Management.Smo.Server') $computername
$fragments += "<h3>SQL Host Information Details</h3>"
$fragments += $smo | select ComputerNamePhysicalNetBios,Name, Processors, ProcessorUsage, PhysicalMemory, PhysicalMemoryUsageInKB, MasterDBPath, BackupDirectory | ConvertTo-HTML -Fragment


#Get Status of all SQL related Services
Write-Verbose "Querying services"
$services = Get-Service -DisplayName *SQL* -ComputerName $computername |
Select Name,Displayname,Status
$fragments += "<h3>SQL Services</h3>"
$fragments += $services | ConvertTo-HTML -Fragment

#get databases
#path to databases
Write-Verbose "Querying datases"
$dbpath = "SQLServer:\SQL\Localhost\default\databases"

$fragments += "<h3>Database Utilization</h3>"
$fragments += dir $dbpath | Select Name,Size,DataSpaceUsage,SpaceAvailable,
@{Name="PercentFree";Expression={ [math]::Round((($_.SpaceAvailable/1kb)/$_.size)*100,2) }} |
Sort PercentFree | ConvertTo-HTML -fragment


#get database backup information
# Create an SMO connection to the instance
$smo = new-object ('Microsoft.SqlServer.Management.Smo.Server') $computername
$dbbackups = $smo.Databases
$fragments += "<h3>Last Database Backup Information</h3>"
$fragments += $dbbackups | select Name,LastBackupDate, LastLogBackupDate | ConvertTo-HTML -Fragment

#Login & Service Account Information#SQL Host Information
$smo = new-object ('Microsoft.SqlServer.Management.Smo.Server') $computername
$fragments += "<h3>Login & Service Account Information</h3>"
$fragments += $smo | select ServiceAccount, Logins | ConvertTo-HTML -Fragment


#volume usage
Write-Verbose "Querying system volumes"
$data = Get-CimInstance win32_volume -filter "drivetype=3" -ComputerName $computername

$drives = foreach ($item in $data) {
    $prophash = [ordered]@{
    Drive = $item.DriveLetter
    Volume = $item.DeviceID
    Compressed = $item.Compressed
    SizeGB = $item.capacity/1GB -as [int]
    FreeGB = "{0:N4}" -f ($item.Freespace/1GB )
    PercentFree = [math]::Round((($item.Freespace/$item.capacity) * 100),2)
    }

    #create a new object from the property hash
    New-Object PSObject -Property $prophash
}

[xml]$html = $drives | ConvertTo-Html -fragment

#check each row, skipping the TH header row
for ($i=1;$i -le $html.table.tr.count-1;$i++) {
  $class = $html.CreateAttribute("class")
  #check the value of the last column and assign a class to the row
  if (($html.table.tr[$i].td[-1] -as [int]) -le 25) {                                         
    $class.value = "danger" 
    $html.table.tr[$i].Attributes.Append($class) | Out-Null
  }
  elseif (($html.table.tr[$i].td[-1] -as [int]) -le 35) {                                              
    $class.value = "warn"   
    $html.table.tr[$i].Attributes.Append($class) | Out-Null
  }
}

$fragments += "<h3>Volume Utilization</h3>"
$fragments += $html.innerxml

#define the HTML style
Write-Verbose "preparing report"
$imagefile = "c:\scripts\db.png"
$ImageBits = [Convert]::ToBase64String((Get-Content $imagefile -Encoding Byte))
$ImageHTML = "<img src=data:image/png;base64,$($ImageBits) alt='db utilization'/>"

$head = @"
<style>
body { background-color:#FAFAFA;
       font-family:Arial;
       font-size:12pt; }
td, th { border:1px solid black;
         border-collapse:collapse; }
th { color:white;
     background-color:black; }
table, tr, td, th { padding: 2px; margin: 0px }
tr:nth-child(odd) {background-color: lightgray}
table { margin-left:50px; }
img
{
float:left;
margin: 0px 25px;
}
.danger {background-color: red}
.warn {background-color: yellow}
</style>
$imagehtml
<br><br><br>
<H2>SQL Server Report: $Computername</H2>
<br>
"@

#create the HTML document
ConvertTo-HTML -Head $head -Body $fragments -PostContent "<i>report generated: $(Get-Date)</i>" |
Out-File -FilePath $path -Encoding ascii

Write-Verbose "Opening report"
Invoke-Item $path

######################END SCRIPT##################################

I have 2 questions for help in regards to the above script:

1)  For the Login and Service Account portion I can't get my output to show up properly.  Here is the snip from the script:

#Login & Service Account Information#SQL Host Information
$smo = new-object ('Microsoft.SqlServer.Management.Smo.Server') $computername
$fragments += "<h3>Login & Service Account Information</h3>"
$fragments += $smo | select ServiceAccount, Logins | ConvertTo-HTML -Fragment

Here is how the output shows for this portion:

ServiceAccountLogins
domain\svcAcct             Microsoft.SqlServer.Management.Smo.LoginCollection

I would like top have the login information show in the above table of the all the different logins.  When I run the script without HTML for that portion and just output to console it shows the login info as I would expect.

2)  The 2nd question is, how do I add a variable to the bottom of the script to email the report to said email address.  This is probably simple but can't get my head wrapped around this part.

Thanks all in advance!

Download xml file using InternetExplorer.Application

$
0
0

I've been trying to write a ps that logs onto a website via internet explorer then navigates to a xml file so I can download it. The problem is, I when the link to the xml file is activated, it opens a new tab for the xml file and unfortunately the ie variable still points to the previous tab which contains the link to the xml file.

I've tried to just navigate to the url with the xml file once I've logged on but I get a 403 error.

Can someone advise me how I can get a reference to the new tab thanks

Here's some code I've been using:

$ie = new-object -comobject InternetExplorer.Application

#...

$xmlfeedlink 



ForEach ($child in $doc.getElementById("id").getelementsbytagname('a')) {
     $xmlfeedlink =   $child         #I can't get array reference to work so using a loop
     break
}
$xmlfeedlink.Click()

$ie.document.execCommand("SaveAs",0,$destinationfile) #saves the page containing the link and not the xml file







Socket check on multiple addresses

$
0
0

Hey there,

I would like to build a script that checks a port on a server IP address using the System.Net.Sockets.TCPClient namespace. I have tested against one address adding the server and port to the argument list but I need to test against a second server also on a different port. I am running it in PRTG and only need to output a value of 2 to stdout if both servers don't respond. I am not sure how to parameterize it to test both.

Powershell and Zip Files

$
0
0

I want to be able to use Powershell to list the contents of a zip file as well as extract the files. Using Powershell v 3.0

I've been looking, but havn't found what I'm looking for yet.


Paul Arbogast

cannot call a method on a null-valued expression

$
0
0
function new-zipfile {
                param ($zipfile)
                if (!$zipfile.endswith('.zip')) {$zipfile += '.zip'}
                set-content $zipfile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
                (dir $zipfile).IsReadOnly = $false
}
#define variables here
$thismonthint = get-date -f "MM"
$prevmonthint = (get-date).addmonths(-1).tostring("MM")
$thismonthstr = get-date -f "MMM"
$prevmonthstr = (get-date).addmonths(-1).tostring("MMM")
$thisyearlongint = get-date -f "yyyy" 
$thisyearshortint = get-date -f "yy"
$thislogdir = 'C:\rad1\'
$thiszipfile = $thislogdir + $prevmonthstr + $thisyearlongint + '.zip'
$zipexists = test-path $thiszipfile
$mask = "*.txt"
$date = (get-date).AddDays(-30)
#$files = dir $thislogdir -Recurse -Include $mask | where {($_.LastWriteTime -lt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins))
#start program here
#first pass, check for .zip files of previous months. if exists exit. if not exist, create empty .zip file
if (! $zipexists)
{
                echo 'zip file does not exist, creating zip file'
                new-zipfile $thiszipfile
}
else
{
                echo 'zip already exists'
}
# move all log files where the month number matches the month number of the .zip file
# Jan = 01, Feb = 02, Mar =03 etc. etc.
foreach($file in Get-ChildItem $thislogdir -exclude "*.zip" | where {$_.LastWriteTime -lt $date})
{
                # exclude the .zip files already in the directory (just in case we get a random month match in their filename
                if (! $file.name.endswith(".zip"))
                {
                                                $zipfile = (New-Object -ComObject shell.application).NameSpace($thiszipfile)
            $zipPackage = $shellApplication.NameSpace($zipfilename)
                                                $zipfile.MoveHere($file.fullname)
               }
}

the above script runs by given an error cannot call a method on a null-valued expression.

At C:\Users\rthakur\Desktop\Powershell\Untitled6.ps1:52 char:54
+             $zipPackage = $shellApplication.NameSpace <<<< ($zipfilename)
    + CategoryInfo          : InvalidOperation: (NameSpace:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Pleaseee help me...


Radhika Thakur

How to run a Powershell workflow with WinPE 5.0?

$
0
0

I have a powershell workflow script to validate a tool. It worked well with Windows 8.1 system. As the tool can be used with both Win8.1 and WinPE 5.0 environment, I would like the workflow script to run with WinPE environment to make sure the tool works well.  I created a WinPE UFD with Powershell module and the workflow script and the tool. And I run it and got the error message below.  I guess powershell workflow is not supported in WinPE 5.0, am I right?

----

X:\Windows\61ProductInformationWinPE>ProdInfoWTool.cmd
ワークフローを作成できません。'PSWorkflow' モジュールの型 'Microsoft.PowerShell
.Workflow.AstToWorkflowConverter, Microsoft.PowerShell.Activities, Version=3.0.
0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' を読み込むことができませ
んでした。
発生場所 X:\Windows\61ProductInformationWinPE\ProdInfoWTool.ps1:1 文字:1
+ # Standard BIOS Product Information Writing Tool Support検証項目 スクリプト
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], NotSupportedException
    + FullyQualifiedErrorId : System.NotSupportedException

Combine Two Arrays and Format Into Columns and Rows

$
0
0

Okay, I feel as if the answer to this should be pretty simple but I am for some reason just not getting it. I am basically trying to perform two WMI queries to two different classes and then combine the results into an array that is formatted nicely as a readable table. I don't seem to have a problem combining (such as in the commented out area) but the results look funky like each column has all of the data jammed into a single row. What I have tried now is creating a custom object but then I hit a brick wall when I try to loop through the second set of results and add it to the custom object to create the table. Here's my code of what I've been playing with:

$failedos = @()
$failedcs = @()

$ccs = get-adcomputer -property operatingsystem -filter {name -like "*-CC*"} | select name | sort name

$cs = foreach ($cc in $ccs){$cc.name | % {if ($c=get-wmiobject -computername $cc.name -class win32_computersystem -ErrorAction SilentlyContinue){$c | select @{Name="Name";Expression={$_.Name}}, @{Name="Model";Expression={$_.Model}}} else {$failedcs += "$_"}}}

$os = foreach ($cc in $ccs){$cc.name | % {if ($o=get-wmiobject -computername $cc.name -class win32_operatingsystem -ErrorAction SilentlyContinue){$o | select @{Name="OperatingSystem";Expression={$_.caption}}} else {$failedos += "$_"}}}

#[array]$osprops = @{'Name'=$cs.Name;'Model'=$cs.Model;'OperatingSystem'=$os.OperatingSystem}

$result = @()
Foreach ($Line in $cs){
 $MyCustomObject = New-Object -TypeName PSObject
 Add-Member -InputObject $MyCustomObject -MemberType NoteProperty -Name "Name" -Value $Line.name -Force
 Add-Member -InputObject $MyCustomObject -MemberType NoteProperty -Name "Model" -Value $Line.Model -Force
 $result += $MyCustomObject
}

foreach ($Line2 in $os){
 $MyCustomObject = New-Object -TypeName PSObject
 Add-Member -InputObject $MyCustomObject -MemberType NoteProperty -Name "OperatingSystem" -Value $Line2.OperatingSystem -Force
 $result += $MyCustomObject
}

Feel free to bash on my code however you see fit. The more criticism you guys can dish out, the better! Any thoughts? Let me know if I need to include more detail. SO sorry for the poor formatting (shame on me for using Notepad and then copy and paste...). If you need me to clean it up first I'll do that if it makes it easier to read. Thanks in advance!


Is it possible to using Powershell, Unzipping, force 'yes' to all, rename, don't overwrite existing files.

$
0
0

I've been reading and experimenting with a number for forums, solutions, and technet articles. What I haven't found yet is a method/mode to allow me to unzip an archive that has multiple files with the same filename.

I have system generated zip files that have multiple files that have the same filename. They are indeed different files though.

Some folks have provided some really great resources and examples of how to use system.io.compression, but I haven't found the answer to my problem.

I 'think' if it were possible, I would find it here.

http://msdn.microsoft.com/en-us/library/system.io.compression.zipfile_methods%28v=vs.110%29.aspx

I found this article that makes it seem like I should switch to using the cli version of 7zip.

http://social.technet.microsoft.com/Forums/windowsserver/en-US/8f98f06e-79fe-401c-92f0-a548d4304dcc/how-to-zip-files-and-folders-using-powershell?forum=winserverpowershell

Ultimately, my goal via powershell is to:

unzip the file from in a PS script

Make it non user interactive.

Have it answer 'Y' to any prompts that may be issued

rename all duplicate filename's automatically just as in a manual extraction.

It would seem that if the functionality exists in the OS, .NET 4.5 would expose it to PS 3.

The closest hint to how to do this is using vOption as referenced in this page:

http://www.howtogeek.com/tips/how-to-extract-zip-files-using-powershell/

When I tried that it did some really amazing things, just not 'good' amazing things. (That example showed for java I believe)

Thanks for any ideas, especially links to better documentation that allows me to see how this is done.

-= Bruce D. Meyer

Powershell Script to back up sql server db and disable/enable sql agent jobs

$
0
0

Hello,

I am new to powershell and I am looking for a script that would connect remote sql server instaces and backup sql server databases and disable specific jobs. I am basically wanting to use it for a deployment. So predeployment I would backup and disable the jobs and post deployment I would like to enable those jobs that were disabled.

These sqlagent jobs are 3 different instances and the database that needs to be backed up is one among those.

Is this possible with powershell scripting?

Thanks a bunch

Re-map existing network drives with alternate credentials

$
0
0

Hi

I am looking for a way to list a users network drives, delete them and then remap them using the same drive letters but with alternate credentials

I am ok listing the drives  (using get-wmiobject win32_network connection) and sending this to a file but I don't know how to manipulate and then reference the file to remap the drives using the alternate credentials.

I have had a good trawl around the internet but can find anything that suits my situation.

Any help would be greatly appreciated



Single Quotes in XML Attribute Value

$
0
0

Hi,

Please I need help regarding writing xml from PowerShell.

The problem is that I want to do as below;

<output test="sometext" test2="sometext2" name='test3' location='test4' />

notice that the first 2 attributes with double quotation and the rest with single quotation, how do I do that?

Also I was using Writer.WriteAttributeString("name", 'test3') whenever I write this single quotes, the WriteAttributeString change it to double quotes.

Please advise.


Mai Omar Desouki | Software Consultant | Infusion | MCP, MCTS, MCPD, MCITP, MCT Microsoft Certified Trainer & MCC Microsoft Community Contributor | Email: mai_omar_86@live.com | Blog: http://moresharepoint.wordpress.com


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

Viewing all 21975 articles
Browse latest View live


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