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

[ADSI] Question

$
0
0

We have recently added VDI to our arsenal.  I need to modify our build scripts to modify these.  I swore this was working, and now it is not, but here is what is happening.  I sure could use some assistance.  

VDI are created and automatically put on the Domain in the ComputersOU, where physical PC's and laptops are not.  I used 

Get-WMIObject win32_computersystem.pcsystemtype and Get-WMIObject win32_computersystem.model to determine if the equipment being built is a physical laptop or VDI.  If it is a CDI, I have it run this command with the goal to move it from the ComputersOU to the ComputersWB- VDI OU:

## Determine if PC is a VDI based on Model
If ($model -like "VMware Virtual Platform")
    { 
     ## Move PC from ComputersOU to ComputersWB\VDI OU based on Model
     $AD = [ADSI]''   
     # Setup the search criteria
     $ADSearch = New-Object System.DirectoryServices.DirectorySearcher    
     $ADSearch.SearchRoot = $AD    
     $ADSearch.Filter = "(objectclass=computer)"
     $Results = $ADSearch.FindAll() | Where-Object {$_.properties.item("cn") -like $CN}
     # Get the DN of the object
     $ComputerDN = $Results.Properties.Item("DistinguishedName")
     # Connect to the computer object
     $Object = [ADSI]"LDAP://$ComputerDN"
     # Specify the target OU
     $TargetOU = "OU=VDI,OU=ComputersWB,DC=BLAIRNET,DC=NET"
     $TargetOU="LDAP://$targetOU"
     # Move the object to the target OU
     $Object.psbase.MoveTo($TargetOU)
    }  


I swore this was working.  I really did, but when I ran it again on a new VDI, it fails miserably.  Doing some troubleshooting, it fails almost immediately and i don't know why.  

When I run the line $AD = [ADSI]'', I get the following error:

format-default : The following exception occurred while retrieving member "distinguishedName": "The specified domain either does not exist or could not be 
contacted.
"
    + CategoryInfo          : NotSpecified: (:) [format-default], ExtendedTypeSystemException
    + FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand

Looking for some guidance on how to move this VDI automatically to another OU using ADSI commands or to figure out why I am getting this error.  Maybe I was logged in as myself when it worked, but I swore it worked as it was supposed to logging in a a local user - not a domain user.  

Any help or thoughts appreciated.  

Matt


Matt Dillon


Getting the top left value in a csv file

$
0
0

Does anybody know how to get the top left value from a csv file? I use Import-CSV to get the file content. I need this for a kind of header validation where only this value is constant. Many thanks


Writing to MSSQL database error Incorrect Syntax near '('

$
0
0

I have the following code below,  I am trying to write the data to a table, but it keeps throwing up the following error.  As you can see, I've tried several ways.  I just can't find the issue..  Thank you for your help


Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near '('."
At C:\Scripts\Sharepoint\LastUserLogon\ParseFile.ps1:111 char:1
+ $Cmd.ExecuteNonQuery();
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException


Foreach ($item in $tbl_2)
{
$OU = $item.OU
$Type = $item.type -replace " ", ""

If ($OU -like "*$OU")
{
Write-Host $sam $OU $itemType $Date $OU
$csv = @"
"$sam",$Type","$LastLogon","$Enabled","$DN","$OU"
"@
$csv >>$ParseOutcsv


#$Cmd.CommandText = "INSERT INTO $tbl_3 (sam,Type,Enabled,Date,DN,OU) VALUES ('$sam','$Type','$lastLogon','$Enabled','$DN','$OU')"
#$cmd.ExecuteNonQuery()



$Cmd.Parameters.Add("@sam", $sam);
$Cmd.Parameters.Add("@Type", $Type);
$Cmd.Parameters.Add("@lastLogon", $lastLogon);
$Cmd.Parameters.Add("@Enabled", $Enabled);
$Cmd.Parameters.Add("@DN", $DN);
$Cmd.Parameters.Add("@OU", $OU);


$Cmd.CommandText = "INSERT INTO $tbl_3 (Sam,Type,Enabled,Date,DN,OU) VALUES (@sam,@Type,@lastLogon,@Enabled,@DN,@OU)";
$Cmd.ExecuteNonQuery();

}

Parent Folder path

$
0
0

I need to reference a number of resources with paths relative to the script folder, and I am using 

$ScriptPath = Split-Path $script:MyInvocation.MyCommand.Path to establish the script path. I had tried just using relative patching, but I had some failures since the path "origin" isn't the script folder, but rather the current folder, and some environments where setting that to user folders. Thus $ScriptPath. Also, these values are stored in some XML that I read into some variables to make maintenance easier down the road, and I then use $ExecutionContext.InvokeCommand.ExpandString($Var) to get an actual path. 

I can use "$ScriptPath\Resources\Resources.xml" to get to a file that is in a subfolder of the current script's folder, but getting to a parent folder I am having trouble with. If I didn't need to use the $ScriptPath variable then "..\Locations.xml" would work, but I do need the variable, and things like "$ScriptPath\..\Locations.xml" don't work.

Anyone point me in the right direction on this? Or should I abandon the approach?

Thanks!
Gordon

Changing the Remote Desktop Profile Path with Powershell

$
0
0

I am making a PowerShell script for automating user creation in the company I work in, but I have a problem.

 

How can I set the "Remote Desktop Services Profile Path" through Powershell? I can set all the other attributes I needed through SET-ADUser, but I couldn't find any -command to change the Remote Profile Path.

 

Is this even possible?

Why does some data show up as blank or zero?

$
0
0

I have the script below which seems to work fine except that a couple of variables show zero or blank on output, but the editor's data browswer shows non-zero non-blank data. The properties areWin32_PhysicalMemory_Capacity andWin32_PhysicalMemory_Capacity_GB. When I print$Computer.Win32_PhysicalMemory_Capacity at the command prompt I get the correct output.

# http://ss64.com/ps/get-wmiobject-win32.html
# http://social.technet.microsoft.com/Forums/windowsserver/en-US/8443fcfd-5a0b-4c3d-bda7-26df83d2ee92/how-to-output-a-bunch-of-variables-into-a-table?forum=winserverpowershell

Param( 
	[string]$ComputerName = $env:COMPUTERNAME 
)

$Win32_PingStatus        = $null
$Win32_PingStatus_Result = $null
$Win32_OperatingSystem   = $null
$Win32_Processor         = $null
$Win32_PhysicalMemory    = $null
$Win32_ComputerSystem    = $null
$Win32_BIOS              = $null
$Computer                = $null

$Win32_PingStatus = "select * from Win32_PingStatus where address = '$ComputerName'"
$Win32_PingStatus_Result = Get-WmiObject -query $Win32_PingStatus

If ( $Win32_PingStatus_Result.protocoladdress )
{
	$Win32_OperatingSystem =             Get-WmiObject Win32_OperatingSystem -computer $ComputerName
	$Win32_Processor       = [object[]]$(Get-WmiObject Win32_Processor       -computer $ComputerName)
	$Win32_PhysicalMemory  =             Get-WmiObject Win32_PhysicalMemory  -computer $ComputerName
	$Win32_ComputerSystem  =             Get-WmiObject Win32_ComputerSystem  -computer $ComputerName
	$Win32_BIOS            =             Get-WmiObject Win32_BIOS            -computer $ComputerName

	$Computer = New-Object -Type PSObject -Property @{
		Name                                           = $Win32_OperatingSystem.CSName
	    Win32_BIOS_SerialNumber			               = [string]$Win32_BIOS.SerialNumber
	    Win32_ComputerSystem_Manufacturer              = [string]$Win32_ComputerSystem.Manufacturer
	    Win32_ComputerSystem_Model                     = [string]$Win32_ComputerSystem.Model
	    #Win32_ComputerSystem_NumberOfLogicalProcessors = [int32]$Win32_ComputerSystem.NumberOfLogicalProcessors
	    #Win32_ComputerSystem_NumberOfProcessors        = [int32]$Win32_ComputerSystem.NumberOfProcessors
	    #Win32_ComputerSystem_TotalPhysicalMemory       = [long]$Win32_ComputerSystem.TotalPhysicalMemory
	    #Win32_ComputerSystem_TotalPhysicalMemory_GB    = [float]($Win32_ComputerSystem.TotalPhysicalMemory / (1024*1024*1024))
	    Win32_OperatingSystem_Caption                  = [string]$Win32_OperatingSystem.Caption
		Win32_OperatingSystem_CSName                   = [string]$Win32_OperatingSystem.CSName
	    #Win32_OperatingSystem_OSArchitecture           = [string]$Win32_OperatingSystem.OSArchitecture
	    #Win32_OperatingSystem_SerialNumber             = [string]$Win32_OperatingSystem.SerialNumber
	    Win32_OperatingSystem_ServicePackVersion       = [string]$Win32_OperatingSystem.ServicePackMajorVersion + "." + [string]$Win32_OperatingSystem.ServicePackMinorVersion
	    Win32_PhysicalMemory_Capacity                  = $Win32_PhysicalMemory.Capacity
	    Win32_PhysicalMemory_Capacity_GB               = ($Win32_PhysicalMemory.Capacity / (1024*1024*1024) )
	    Win32_Processor_Count                          = [int]$Win32_Processor.Count
	    Win32_Processor_NumberOfCores                  = [string]$Win32_Processor[0].NumberOfCores
	    Win32_Processor_NumberOfLogicalProcessors      = [string]$Win32_Processor[0].NumberOfLogicalProcessors
	    #Win32_Processor_Description                    = [string]$Win32_Processor[0].Description
	    Win32_Processor_Manufacturer                   = [string]$Win32_Processor[0].Manufacturer
	    Win32_Processor_Name                           = [string]$Win32_Processor[0].Name
	} ## end new-object
	$Computer
} Else {"$ComputerName Not Responding" 
}""
Write-Host "$(Get-Date -Format o) Ending script $($MyInvocation.MyCommand.Name)"

declare webservice variable types

$
0
0

Hi,

How can I load the object types from a web service in Powershell?

$url = http://wserver/v1.asmx?WSDL

$ws = New-WebServiceProxy -uri $url -Namespace myWS

$wsObj = New-Object -TypeName "myWS.AddObjectData"

When I now do a $wsObj.GetType() the BaseType is "System.Object" and not "AddObjectData".

Trying to declare a variable like [myWS.StringVal]$Test ("StringVal" is valid and found in the WSDL), I get an error that the assembly is not loaded.

How can I load this into PowerShell?

Note: This works fine in C#.

Thanks

VMM - add recources to user group

$
0
0

Hello,

Is it possible to add recources (ie. virtual machine) to a VMM user group via powershell?

Thanks


PowerShell ISE doesn't flush stdout

$
0
0

Hello everyone,

I'm having a little problem when running a console program in PowerShell ISE: when the program writes out a line in portions using flush, PowerShell won't show the line until the program writes a line ending. For example the program is doing something like this (C++):

std::cout << "Doing something time-consuming..." << std::flush;
// Do something for some time
std::cout << " done in " << x << " seconds" << std::endl;

And PowerShell ISE will only show the whole line when this section of code completes. With non-ISE PowerShell this doesn't happen, the line is printed in portions as expected.
So the question is: can I somehow make PowerShell ISE disable its internal buffer and print the program's stdout directly?

Thank you.

GPO Folder redirection using Powershell

$
0
0

Dear,

how can i configure a gpo for Folder Redirection using powershell.

I would like to create gpo's with all kinds of folder redirection configurations using a script.

Davy

PSRemotingTransportException when invoking command on a distant server

$
0
0

Hello,

I'm having some trouble when I try to call Invoke-Command in powershell on a distant server.

I'm receiving a PSRemotingTransportException. It tells me that the user is either unknown or associated with a wrong password.

I've run the following commands on the distant server :

Set-ExecutionPolicy RemoteSigned

winrm quickconfig

Enable-PSRemoting


and the user is in the administrator group of the distant server.

When I try with another user, it works.

What I am missing ? Can anyone help me ?

Thanks in advance !

Removing user in DomainB from a group in DomainA

$
0
0

I am trying to remove a user in DomainB from a group in DomainA.

So far, I have not been able to do so using powershell.

$Tusr = Get-ADUser TestUser -server DomainB.company.com
$grp = Get-ADGroup TestGroup -server DomainA.company.com
Remove-ADPrincipalGroupMembership -server DomainA.company.com TestUser -MemberOf $grp

This gives me this error:

WARNING: Could not remove member(s) from ADGroup: 'CN=TestGroup,OU=JD,OU=Temp,DC=uk,DC=Comp,DC=com'. Error is:
'The specified account name is not a member of the group'.
Remove-ADPrincipalGroupMembership : Could not remove member(s) to one or more ADGroup.
At line:1 char:1+ Remove-ADPrincipalGroupMembership -server DomainA TestUser -MemberOf $grp ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : OperationStopped: (Microsoft.Activ...ement.ADGroup[]:ADGroup[]) [Remove-ADPrincipalGroup
   Membership], ADException+ FullyQualifiedErrorId : 1,Microsoft.ActiveDirectory.Management.Commands.RemoveADPrincipalGroupMembership

If I try to be clever and user Remove-ADGroupMember, I do this:

$usr = Get-ADUser TestUser -server DomainB
Remove-ADGroupMember TestGroup -Members $usr -server DomainA

Followed by this error:

Remove-ADGroupMember : The specified account name is not a member of the group
At line:1 char:1+ Remove-ADGroupMember TestGroup -Members $usr -server DomainA+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (TestGroup:ADGroup) [Remove-ADGroupMember], ADException+ FullyQualifiedErrorId : The specified account name is not a member of the group,Microsoft.ActiveDirectory.Management.Commands.RemoveADGro
   upMember

I get the same error when running:

Remove-ADGroupMember $grp -Members $usr -server DomainA

So, basically, I'm wondering if PowerShell is bugged out when trying to do cross-domain stuff like this...

I have looked at this post:

Adding/removing members from another forest or domain to groups in Active Directory

But unfortunately, I get the first error I posted.

I will not be able to use Quest, or other thrid party, commandlets.

Any ideas?

Server2012: Set-ClusterScheduledTask + "Run with highest Priviledges" - ???

$
0
0

Hey there,

I'm trying to fix a script we have to trim VSS copies on our Fileserver which is a Serve 2012 Failover Cluster. 

This has worked in the past, however I think it got messed up when I changed the schedule from a Win8.1 workstation. Anyway, I've lost the "Run with highest priviledges" flag on the task and I can't quite seem to find a way to set it back. Judging by the documentation, if I were able to set a scheduled task principal I could use the -RunLevel switch, but apparently that's not supported with the ClusteredScheduledTasks. Also, it appears that if the settings of the task are set to volatile=true, that enables highest privs, but I can't find a way to do that via the Powershell cmdlets. 

Anyone have any ideas? 

Define site CSS

$
0
0

Hi, is it possible to define the CSS to be used by a site? thanks

add-pssnapin Microsoft.Exchange.Management.PowerShell.Admin

$
0
0

I have a script (below) that was designed to be used by people who do not have access to Exchange. The idea is to check if ActiveSync is enabled for the user, it gives the ability to enable or disable ActiveSync, look for connected devices and remove any stale partnerships.

It works great, in ISE, but run it in Powershell and it says:

"add-pssnapin : The Windows PowerShell snap-in Microsoft.Exchange.Management.PowerShell.Admin' is not installed on this computer."

This is obviously not true as it loads the snap-in and runs the script fine in ISE (both 32 and 64 bit).

Can anyone tell me why it does not work in Powershell but does work in ISE? Every time I've encountered issues like this before it has been the other way around, fails in ISE but works in Powershell.

I am running Windows 8.1, Powershell 4. The domain is Windows server 2008 R2, Exchange is 2007 SP3.

Code:

add-pssnapin Microsoft.Exchange.Management.PowerShell.Admin
load-module activedirectory
$prompt = @"

************************************************************************************************************************
**                                      Please select from the options below                                          **
**                                                                                                                    **
**                                      s = Search ActiveSync Status                                                  **
**                                      e = Enable ActiveSync for User                                                **
**                                      d = Disable ActiveSync for User                                               **
**                                      c = Search For Device Connections                                             **
**                                      r = Remove Device Connection                                                  **
**                                      x = exit                                                                      **
**                                                                                                                    **
************************************************************************************************************************


"@
Clear-host
Do{
	$originalcolor = $host.UI.RawUI.ForegroundColor
	$host.UI.RawUI.ForegroundColor = "Yellow"
	$choice = Read-Host -Prompt $prompt
	$host.UI.RawUI.ForegroundColor = "Yellow"
	Switch($choice){
        s {$user = Read-Host 'Enter the email address to search for (email.address@bellevue.edu)' ; Get-CASMailbox $user | Select-Object ActiveSyncEnabled}
        c {$user = Read-Host 'Enter the mailbox to search for (Firstname.Lastname)' ; Get-ActiveSyncDeviceStatistics -Mailbox $user | 
    ft DeviceType, DeviceUserAgent, LastSuccessSync}
        r {$user = Read-Host 'Enter the email address (email.address@bellevue.edu) you wish to remove inactive (no sync in last 7 days) partnership(s) from' ; Get-ActiveSyncDeviceStatistics -Mailbox $user | Where-Object {$_.LastSuccessSync -le (Get-Date).AddDays("-7")} | Remove-ActiveSyncDevice -confirm:$false}
        e {$user = Read-Host 'Enter the email address to enable ActiveSync for (email.address@bellevue.edu)' ; get-mailbox $user | set-Casmailbox -ActiveSyncEnabled:$true}
        d {$user = Read-Host 'Enter the email address to disable ActiveSync for (email.address@bellevue.edu)' ; get-mailbox "$user" | set-Casmailbox -ActiveSyncEnabled:$false}
        x {break}

		default {write-host "Invalid selection, please try again." -ForegroundColor Red}
	}
}Until($choice -eq "x")


PowerShell Exchange Command

$
0
0

Try to build a GUI for some mailbox administration stuff..... 

The command below produces syntax errors.

Get-Mailbox $dlist.alias -Resultsize Unlimited | Search-Mailbox -SearchQuery "Received:`$DateFromvar..`$DateTovar Subject:$Sub" -DeleteContent -Force >\\Server\Share\file.txt

Error: Please adjust the date time. Make sure it is in the correct format.

When I output $DateFromvar and $DateTovar is appears to be correct. Running the command natively in PowerShell runs successful as well. 

What am I missing? 

Thanks


Djoe


Active Directory/Powershell Name Formatting - Proper Title Case & processing

$
0
0

I'm getting a nightly feed from our HR system with user information.  I'm trying to use this feed to create and maintain Active Directory.  The folks that enter the data are a little less than consistent.  I've seen ALL CAPS, all lowercase, and occasionally AmiXed BaG.

I can't fix the database because I don't own the data.  I'm a lowly windows/linux guy trying to make the best of a bad situation.  

I'm loading everything in from a CSV file, and removing parenthesis and escaping the apostrophes for the O'Malley twins.

$LAST = "'" + ($entry.last_name -replace "'","''" -replace "\(","" -replace "\)","") + "'"

I'm actually doing that replace command for everything I read in since some departments and titles have apostrophes in the names...but that's another thread.

I'm using (Get-Culture).TextInfo.ToTitleCase to fix the easy stuff and capitalize the first letter of each name:

$FIRST = (Get-Culture).TextInfo.ToTitleCase($FIRST)
$LAST = (Get-Culture).TextInfo.ToTitleCase($LAST)
$MIDDLE = (Get-Culture).TextInfo.ToTitleCase($MIDDLE)

I've written the code to fix names like MacGruber and McClung, but I'm having trouble finding where I've done it and how I've done it (I'm assuming I used regex).  I'm curious if there are other problem names that (Get-Culture).TextInfo.ToTitleCase won't totally fix. 

I have another concern.  My script is going to run from the HR data....meaning, it could be triggered any time they make any change to the record.  Once they make a change, they'll show up in the feed and my script will repush all fields from HR... I may try to build in a *manual override* flag somewhere, but don't know what attribute in AD I can use to store it or if it's worth spending time on coding it...

I'd like to see what other people do that are faced with this problem.

Thanks.

Results to table powershell

$
0
0

in our monitoring system we havent installed windows excel hence we are unble to run the below script. i am new to powershell can any one help me to change the scrit to update the results to sql server database table ?

<#=================================
# Generated On: 02/04/2014
# Generated By: Prashanth Jayaram
# Version     : 1.1
# Desc        : SQL Inventory Generation
# Change    : Added Named Instance column
# EXAMPLE :
PS:\>.\SQLServerInventory.ps1 -InputFileName c:\server.txt -DirectoryToSaveTo C:\  -Topram@app.com -From pram@app.com
-SMTP mail.app.com
#=================================
#>
[CmdletBinding()]
Param(
  [Parameter(Mandatory=$True,Position=1)]
   [string]$InputFileName,
 
   [Parameter(Mandatory=$True,Position=2)]
   [string]$DirectoryToSaveTo,

   [Parameter(Mandatory=$True,Position=3)]
   [string]$To,

   [Parameter(Mandatory=$True,Position=4)]
   [string]$From,

   [Parameter(Mandatory=$True,Position=5)]
   [string]$SMTP

)

$Filename='SQLInventory'

# before we do anything else, are we likely to be able to save the file?
# if the directory doesn't exist, then create it
if (!(Test-Path -path "$DirectoryToSaveTo")) #create it if not existing
  {
  New-Item "$DirectoryToSaveTo" -type directory | out-null
  }

#Create a new Excel object using COM
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)

#Counter variable for rows
$intRow = 1
$xlOpenXMLWorkbook=[int]51

#Read thru the contents of the SQL_Servers.txt file
$Sheet.Cells.Item($intRow,1)  ="InstanceName"
$Sheet.Cells.Item($intRow,2)  ="ComputerNamePhysicalNetBIOS"
$Sheet.Cells.Item($intRow,3)  ="NetName"
$Sheet.Cells.Item($intRow,4)  ="OS"
$Sheet.Cells.Item($intRow,5)  ="OSVersion"
$Sheet.Cells.Item($intRow,6)  ="Platform"
$Sheet.Cells.Item($intRow,7)  ="Product"
$Sheet.Cells.Item($intRow,8)  ="edition"
$Sheet.Cells.Item($intRow,9)  ="Version"
$Sheet.Cells.Item($intRow,10)  ="VersionString"
$Sheet.Cells.Item($intRow,11) ="ProductLevel"
$Sheet.Cells.Item($intRow,12) ="DatabaseCount"
$Sheet.Cells.Item($intRow,13) ="HasNullSaPassword"
$Sheet.Cells.Item($intRow,14) ="IsCaseSensitive"
$Sheet.Cells.Item($intRow,15) ="IsFullTextInstalled"
$Sheet.Cells.Item($intRow,16) ="Language"
$Sheet.Cells.Item($intRow,17) ="LoginMode"
$Sheet.Cells.Item($intRow,18) ="Processors"
$Sheet.Cells.Item($intRow,19) ="PhysicalMemory"
$Sheet.Cells.Item($intRow,10) ="MaxMemory"
$Sheet.Cells.Item($intRow,21) ="MinMemory"
$Sheet.Cells.Item($intRow,22) ="IsSingleUser"
$Sheet.Cells.Item($intRow,23) ="IsClustered"
$Sheet.Cells.Item($intRow,24) ="Collation"
$Sheet.Cells.Item($intRow,25) ="MasterDBLogPath"
$Sheet.Cells.Item($intRow,26) ="MasterDBPath"
$Sheet.Cells.Item($intRow,27) ="ErrorLogPath"
$Sheet.Cells.Item($intRow,28) ="BackupDirectory"
$Sheet.Cells.Item($intRow,29) ="DefaultLog"
$Sheet.Cells.Item($intRow,20) ="ResourceLastUpdatetime"
$Sheet.Cells.Item($intRow,31) ="AuditLevel"
$Sheet.Cells.Item($intRow,32) ="DefaultFile"
$Sheet.Cells.Item($intRow,33) ="xp_cmdshell"
$Sheet.Cells.Item($intRow,34) ="Domain"
$Sheet.Cells.Item($intRow,35) ="IPAddress"

  for ($col = 1; $col –le 34; $col++)
     {
          $Sheet.Cells.Item($intRow,$col).Font.Bold = $True
          $Sheet.Cells.Item($intRow,$col).Interior.ColorIndex = 48
          $Sheet.Cells.Item($intRow,$col).Font.ColorIndex = 34
     }

$intRow++

foreach ($instanceName in Get-Content $InputFileName)
{
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$server1 = New-Object -Type Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
$s=$server1.Information.Properties |Select Name, Value
$st=$server1.Settings.Properties |Select Name, Value
$CP=$server1.Configuration.Properties |Select DisplayName, Description, RunValue, ConfigValue
$dbs=$server1.Databases.count
$BuildNumber=$s | where {$_.name -eq "BuildNumber"}|select value
$edition=$s | where {$_.name -eq "edition"}|select value
$ErrorLogPath =$s | where {$_.name -eq "ErrorLogPath"}|select value
$HasNullSaPassword =$s | where {$_.name -eq "HasNullSaPassword"}|select value
$IsCaseSensitive =$s | where {$_.name -eq "IsCaseSensitive"}|select value
$Platform =$s | where {$_.name -eq "Platform"}|select value
$IsFullTextInstalled =$s | where {$_.name -eq "IsFullTextInstalled"}|select value
$Language =$s | where {$_.name -eq "Language"}|select value
$MasterDBLogPath =$s | where {$_.name -eq "MasterDBLogPath"}|select value
$MasterDBPath =$s | where {$_.name -eq "MasterDBPath"}|select value
$NetName =$s | where {$_.name -eq "NetName"}|select value
$OSVersion =$s | where {$_.name -eq "OSVersion"}|select value
$PhysicalMemory =$s | where {$_.name -eq "PhysicalMemory"}|select value
$Processors =$s | where {$_.name -eq "Processors"}|select value
$IsSingleUser =$s | where {$_.name -eq "IsSingleUser"}|select value
$Product =$s | where {$_.name -eq "Product"}|select value
$VersionString =$s | where {$_.name -eq "VersionString"}|select value
$Collation =$s | where {$_.name -eq "Collation"}|select value
$IsClustered =$s | where {$_.name -eq "IsClustered"}|select value
$ProductLevel =$s | where {$_.name -eq "ProductLevel"}|select value
$ComputerNamePhysicalNetBIOS =$s | where {$_.name -eq "ComputerNamePhysicalNetBIOS"}|select value
$ResourceLastUpdateDateTime =$s | where {$_.name -eq "ResourceLastUpdateDateTime"}|select value
$AuditLevel =$st | where {$_.name -eq "AuditLevel"}|select value
$BackupDirectory =$st | where {$_.name -eq "BackupDirectory"}|select value
$DefaultFile =$st | where {$_.name -eq "DefaultFile"}|select value
$DefaultLog =$st | where {$_.name -eq "DefaultLog"}|select value
$LoginMode =$st | where {$_.name -eq "LoginMode"}|select value
$min=$CP | where {$_.Displayname -like "*min server memory*"}|select configValue
$max=$CP | where {$_.Displayname -like "*max server memory*"}|select configValue
$xp_cmdshell=$CP | where {$_.Displayname -like "*xp_cmdshell*"}|select configValue
$FQDN=[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
$IPAddress=(Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $instanceName | ? {$_.IPEnabled}).ipaddress

if ($HasNullSaPassword.value -eq $NULL)
{
 $HasNullSaPassword.value='No'
}
if($DefaultFile.value -eq '')
{
 $DefaultFile.value='NA'
}
if ($VersionString.value -like '8*')
{
 $SQLServer='SQL SERVER 2000'
}
elseif ($VersionString.value -like '9*')
{
 $SQLServer='SQL SERVER 2005'
}
elseif ($VersionString.value -like '10.0*')
{
 $SQLServer='SQL SERVER 2008'
}
elseif ($VersionString.value -like '10.5*')
{
 $SQLServer='SQL SERVER 2008 R2'
}
elseif ($VersionString.value -like '11*')
{
 $SQLServer='SQL SERVER 2012'
}
else
{
 $SQLServer='Invalid'
}


if ($OSVersion.value -like '5.0*')
{
 $OSVer='Windows 2000'
}
elseif ($OSVersion.value -like '5.1*')
{
 $OSVer='Windows XP'
}
elseif ($OSVersion.value -like '5.2*')
{
 $OSVer='Windows Server 2003'
}
elseif ($OSVersion.value -like '6.0*')
{
 $OSVer='Windows Server 2008'
}
elseif ($OSVersion.value -like '6.1*')
{
 $OSVer='Windows Server 2008 R2'
}
elseif ($OSVersion.value -like '6.2*')
{
 $OSVer='Windows Server 2012'
}
else
{
 $OSVer='NA'
}
 $Sheet.Cells.Item($intRow,1)   =$instanceName
        $Sheet.Cells.Item($intRow,2)   =$ComputerNamePhysicalNetBIOS.value
        $Sheet.Cells.Item($intRow,3)   =$NetName.value
        $Sheet.Cells.Item($intRow,4)   =$OSVer
        $Sheet.Cells.Item($intRow,5)   =$OSVersion.value
        $Sheet.Cells.Item($intRow,6)   = $Platform.value
        $Sheet.Cells.Item($intRow,7)   = $Product.value
        $Sheet.Cells.Item($intRow,8)   = $edition.value
        $Sheet.Cells.Item($intRow,9)   = $SQLServer
        $Sheet.Cells.Item($intRow,10)  = $VersionString.value
        $Sheet.Cells.Item($intRow,11)  = $ProductLevel.value
        $Sheet.Cells.Item($intRow,12)  = $Dbs
        $Sheet.Cells.Item($intRow,13)  = $HasNullSaPassword.value
        $Sheet.Cells.Item($intRow,14)  = $IsCaseSensitive.value
        $Sheet.Cells.Item($intRow,15)  = $IsFullTextInstalled.value
        $Sheet.Cells.Item($intRow,16)  = $Language.value
        $Sheet.Cells.Item($intRow,17)  = $LoginMode.value
        $Sheet.Cells.Item($intRow,18)  = $Processors.value
        $Sheet.Cells.Item($intRow,19)  = $PhysicalMemory.value
        $Sheet.Cells.Item($intRow,10)  = $Max.Configvalue
        $Sheet.Cells.Item($intRow,21)  = $Min.Configvalue
        $Sheet.Cells.Item($intRow,22)  = $IsSingleUser.value
        $Sheet.Cells.Item($intRow,23)  = $IsClustered.value
        $Sheet.Cells.Item($intRow,24)  = $Collation.value
        $Sheet.Cells.Item($intRow,25)  = $MasterDBLogPath.value
        $Sheet.Cells.Item($intRow,26)  = $MasterDBPath.value
        $Sheet.Cells.Item($intRow,27)  = $ErrorLogPath.value
        $Sheet.Cells.Item($intRow,28)  = $BackupDirectory.value
        $Sheet.Cells.Item($intRow,29)  = $DefaultLog.value
        $Sheet.Cells.Item($intRow,20)  = $ResourceLastUpdateDateTime.value
        $Sheet.Cells.Item($intRow,31)  = $AuditLevel.value
        $Sheet.Cells.Item($intRow,32) = $DefaultFile.value
        $Sheet.Cells.Item($intRow,33) = $xp_cmdshell.Configvalue
        $Sheet.Cells.Item($intRow,34) = $FQDN
        $Sheet.Cells.Item($intRow,35) = $IPAddress

  
$intRow ++

}
 
$filename = "$DirectoryToSaveTo$filename.xlsx"
if (test-path $filename ) { rm $filename } #delete the file if it already exists
$Sheet.UsedRange.EntireColumn.AutoFit()
cls
$Excel.SaveAs($filename, $xlOpenXMLWorkbook) #save as an XML Workbook (xslx)
$Excel.Saved = $True
$Excel.Close()

 

 

Function sendEmail([string]$emailFrom, [string]$emailTo, [string]$subject,[string]$body,[string]$smtpServer,[string]$filePath)
{
#initate message
$email = New-Object System.Net.Mail.MailMessage
$email.From = $emailFrom
$email.To.Add($emailTo)
$email.Subject = $subject
$email.Body = $body
# initiate email attachment
$emailAttach = New-Object System.Net.Mail.Attachment $filePath
$email.Attachments.Add($emailAttach)
#initiate sending email
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($email)
}

#Call Function
sendEmail -emailFrom $from -emailTo $to "SQL INVENTORY" "SQL INVENTORY DETAILS - COMPLETE DETAILS" -smtpServer $SMTP -filePath $filename

Move Computer to a different OU without AD cmdlets using PowerShell

$
0
0

Hello.  Struggling with understanding [ADSI] yet again.  Just when I think I get it, I don't.  

So I wrote this PowerShell code yesterday which moves a Computer from the ComputersOU to the OU I specify. 

$CN = $env:COMPUTERNAME

$root = [ADSI]'' $searcher = New-Object System.DirectoryServices.DirectorySearcher($root) $searcher.filter = "(&(objectclass=computer)(cn= $CN))" $name = $searcher.findall() # Get the DN of the object $computerDN = $name.Properties.Item("DistinguishedName") # Connect to the computer object $Object = [ADSI]"LDAP://$ComputerDN" # Specify the target OU $TargetOU = "OU=VDI,OU=ComputersWB,DC=BLAIRNET,DC=NET" $TargetOU="LDAP://$TargetOU" # Move the object to the target OU $Object.psbase.MoveTo($TargetOU)

It works when I am logged in.  However I have rights everywhere.  I need this to work using credentials as i keep getting the Access is Denied error.  

I tried this code when logged in as the no rights user:

$CN = $env:COMPUTERNAME
$domain = "BLAIRNET"
$un = (Get-Content '\\secret2\LIBRARY\Powershell\PSScripts\Private\id.txt')
$username = ($domain + "\" +$un)
$password = (Get-Content '\\secret2\LIBRARY\Powershell\PSScripts\Private\pw.txt')

$root = [ADSI]''
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
$searcher.filter = "(&(objectclass=computer)(cn= $CN))"
$name = $searcher.findall() 


# Get the DN of the object
$computerDN = $name.Properties.Item("DistinguishedName")

# Connect to the computer object
##$Object = [ADSI]"LDAP://$ComputerDN",$username,$password
$Object = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$computerDN", $username, $password)

# Specify the target OU
$TargetOU = "OU=VDI,OU=ComputersWB,DC=BLAIRNET,DC=NET"
$TargetOU="LDAP://$TargetOU"

# Move the object to the target OU
$Object.psbase.MoveTo($TargetOU)

The error I continue to get is Exception calling MoveTo" with 1 argument(s): "Access is denied".  

Can anyone out there assist me in getting this written with credentials somehow?  


Matt Dillon

Exporting Mailbox Attributes

$
0
0

i need to export mailbox attributes for all the mailboxes . This attributes includes; first name, last name, display name, alias, primary smtp name, department, last accesed /active status. Please advise.

Thanks.


Viewing all 21975 articles
Browse latest View live


Latest Images

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