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

PowerShell Issues for user count per group all groups in an OU

$
0
0

So here is the major problem. I was recently tasked with creation of a script to get a user count for every group, and list that count, per group, all groups in a specific OU in AD.

I have created two solutions so far, but can't seem to combine the two. My knowledge of PowerShell is rather lacking.

Script 1 Lists number of active, disabled, and total users in a specific OU path:

Import-Module activeDirectory
Get-ADOrganizationalUnit -filter * -SearchBase 'OU=ENDOU,OU=MIDOU,OU=SOURCEOU,DC=DOMAIN,DC=local' |

foreach {

  $users=Get-ADUser -filter * -searchbase $_.distinguishedname -ResultPageSize 2000 -resultSetSize 500 -searchscope Onelevel 

  $total=($users | measure-object).count

  New-Object psobject -Property @{

OU=$_.Name;
TotalUsers=$Total;
Enabled=$Enabled;
Disabled=$Disabled

    }

} | Export-Csv C:\temp\Users1.csv

Script two lists every group in that OU path:

Import-Module activeDirectory
Get-ADOrganizationalUnit -filter * -SearchBase 'OU=ENDOU,OU=MIDOU,OU=SOURCEOU,DC=DOMAIN,DC=local' |

foreach {
get-adobject -Filter 'ObjectClass -eq "group"'
}

Does anyone know if it is possible to do what is requested, as in, script to list ever group in an OU path, and also display number of enabled users per group for every OU?

Thanks in advance for any help you guys can suggest, thanks.


Run ps1 file in a batch file

$
0
0

I use the following in bat file to run ps1 files ok. I have a form ps1 file and the form popup when running it in Powershell ISE but when run it using the following, it does not work. any suggestion?

Powershell.exe -ExecutionPolicy Unrestricted -File C:\Scripts\Form.ps1

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!

Checking for a specific shared printer

$
0
0

I have a script that adds shared printers to a print server by passing arguments into it via a CSV file.  This normally works fine, but I need to validate that the printers actually got created afterwards, so I'm attempting via powershell to check for the existence of a printer on a specific print server.

I've read another thread that has partway lead me down the path I think I need. What that has given me thus far is the following:

gwmi win32_printer -filter "name='PrinterName'"

2 issues with this.  When I run this from the prompt it shows information for the printer in question then seems to hang rather than return to the prompt.  The data returned is: Location, Name, PrinterState, PrinterStatus, Sharename, & SystemName, then this is where it hangs.  When I cancel via <CTRL+C> I get the following:

Get-WmiObject : Out of memory
At line:1 char:5+ gwmi <<<<  win32_printer -filter "name='PrinterName'"+ CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], ManagementException+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

So I'm not certain how to deal with the 'hang' & subsequent error.  Also I really want to reach a Boolean type of value where I can have the scripts take action on whether its there or not.  So that the code would follow the following logic:

Check for Printer1 on ServerA

If Printer1 exists on ServerA - do This

If Printer1 does NOT exist on ServerA - do something else

Any assistance appreciated!


# When I wrote this script only God & I knew what I was doing.

# Now, only God Knows!

don't retire technet http://social.technet.microsoft.com/Forums/en-US/e5d501af-d4ea-4c0f-97c0-dfcef0192888/dont-retire-technet?forum=tnfeedback


Execute bat file remotely without enabling PowerShell Remoting - Like psexec

$
0
0

Hi All,

I want to execute a bat file on a remote machine. I know this has been like thousand times already, my scenario is quite different. kindly Assist.

Source machine - From where PS script will be run 
Target Machine - Machine on which "bat" file needs to executed on.

Bat file is already saved on "Target Machine"

I don't want to enable PowerShell Remoting (there are 30000+ machines , enabling it will be pain and out of my pay grade)
I tried inovoke-command and figured out that PS remoting needs to be enabled (if there is a way to do with out PS remoting please advice)
Certain machines dont have PowerShell installed (XP machines and Server 2003).

It should pretty much act like PSexec but something that is already integrated in OS. 


Tried []Process.create WMI method. For some reason its not working.. may be i'm doing it all wrong.. 

Thank you all in advance. 


$Bug

get share permissions

Powershell to tell which servers a service is running on?

$
0
0

Hi,

I have a text file with a list of server names called 'server_names.txt'

Im trying to write a powershell script to check if the SQL browser service is running on any of the instances:

So far ive got:

Clear-Host
$a = Get-Content "d:\server_names.txt"
foreach ($server in $a)
{ 
Write-Host $server
Get-Service -ComputerName $server | Where-Object {$_.name -eq "SQLBrowser" -and $_.status -eq "running" }
}

This list all the servernames and then if the Browser is running it says 'Running SQLBrowser   SQL Server Browser.

i.e.

Server A
Running  SQLBrowser         SQL Server Browser                    
Server B
Server C
Running  SQLBrowser         SQL Server Browser                    

The browser runs on Server A & C but not Server B. 

I want to supress the servernames that it is not running on (Server B).

Any idea what im doing wrong?

Thanks,

Zoe


Modify Registry values on multiple workstations

$
0
0

Hope someone can help me out with my PowerShell code.

I have a list of Workstations that I need to update with two registry keys for each machine. Each key is unique (the value is different) per workstation. I have input csv input file with the following: ComputerName , AcctName, AcctPwd.

My code below will update the only one workstation and will not move to the next and the values for  $newPwd = $autoComp.AcctPwd and $compName = $autoComp.compName are not being passed.

Thanks,

$cred = Get-Credential 'Domain\UserID'

$autoComps = Import-Csv -Path c:\Scripts\AutoLogon\autoLogon.csv | select CompName, AcctName, AcctPwd
 ForEach ($autoComp in @($autoComps))
 {
 $newName = $autoComp.AcctName
 $newPwd = $autoComp.AcctPwd
 $compName = $autoComp.compName
Invoke-Command -ComputerName $compName -cred $cred -ScriptBlock {
$Comps = Import-Csv -Path c:\temp\autologon.csv | select AcctName, AcctPwd
ForEach ($Comp in @($Comps))
 {
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" -Name "DefaultUsername" -Value $newName
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" -Name "DefaultPassword" -Value $newPwd
Write-Output $newName
}}

}





Isaac Oben MCITP:EA, MCSE,MCC <a href="https://www.mcpvirtualbusinesscard.com/VBCServer/4a046848-4b33-4a28-b254-e5b01e29693e/interactivecard"> View my MCP Certifications</a>


How to create a user account by mirroring another account in PowerShell (Trying to learn to use Powshell for some daily AD tasks intead of the GUI)

$
0
0

Hi,

I am trying to create user accounts via PowerShell instead of the Gui in server 2008 R2 (PowerShell 2.0).

I know how to create a user account with the following Power Shell command below is one from a dummy domain I created to practice.

"

PS C:\Users\Administrator> New-ADUser -SamAccountName "TestOut" -UserPrincipalNa
me "TestOut@Bwcat.net.int" -GivenName "Test" -Surname "out" -DisplayName "Testou
t" -Name "Testout" -Enabled $true -Path "CN=users,DC=bwcat,DC=net,DC=int" -Accou
ntPassword (Read-Host -AsSecureString "Enter Account Password") 

"

However when doing day to day tasks where I work normally we have a new hire, they contact IT and ask that a user account is created.   I will ask who they would like to mirror.

I then would go into the gui pull up the user that they want to mirror right click him and choose copy.  This would create a new user account that I would then fill out.

I am wondering if its possible to do this same thing via PowerShell, or  if its not an option because it takes more work type up everything than it does to go into the gui and do it.

Anyway thanks for the help.

Code to add to server pool

$
0
0

I just added a server to RDS via the Add-RDSServer it worked like i intended but now when i try to browse to RDS via the server manager i get the following

The following servers in this deployment are not part of the server pool:

1.ABC.forst.org

The servers must be added to the server pool.

I would love to fix this via powershell.

Looked around and couldn't find a solution.


The Unicode format that PowerShell uses for file output redirection - instead of ASCII

$
0
0

There must be some benefit to using the UNICODE format for a text file. 

I don't know what that benefit is or what made the PowerShell team chose UNICODE as the file encoding for the file redirection operator.  As far as I know, > always writes file content as UNICODE.

This thread is intended to be a discussion of whether the UNICODE format is preferable to ASCII for Windows system administration purposes using PowerShell.

Check account properties - DES

$
0
0

Hi,

I need to look up all our AD accounts and check if account property: Use Kerberos DES encryption types is enabled.

Is that possible with PowerShell, how?

Thank you.

Powershell Loop

$
0
0

Guys,

I would like to create a script which does the following.

Search a file in d:\folder\test\

If it finds it, send-email and finish.

If it doesn't find the file, retry again every 10 minutes for an hour or retry for a fixed number of times before finishing.

I understand how to do the initial stuff ( search file send email etc), but i require some help with setting up the loop to keep retrying until it is successful or finishes.

Thanks in advance

Write console output to file

$
0
0

Hi!

I am trying to get powershell to write the results of a query to a txt file. It creates the text file, but its blank everytime

heres my code:

Clear-Host
$a = Get-Content "d:\server_names2.txt"
foreach ($server in $a)
{ 
foreach ($Service in (Get-Service -ComputerName $server -name "SQLBrowser"))
{

 Get-WmiObject Win32_Service -ComputerName $server | where     {($_.name  -like "*SQLBrowser*")
	$mode = select StartMode} 
Write-host $server  $Service.startmode $mode | Out-File c:\test.txt
}
}

any ideas what im fdoing wrong?

Thanks,

Zoe


Adding an exception to removing empty folders

$
0
0

I am having a problem with removing empty folders when there is an exception. The code below has this effect... The "_DoNotDelete" folder is not removed unless the parent folder only contains the "_DoNotDelete" folder, then parent folder is removed as though it was empty- and its not. The "_DoNotDelete" folder is empty by default. Is there a way to code this so the parent folder recognizes the child folder and does not delete?


Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and $_.Name -ne "_TrendForMac" -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse



C# style "yield return" in PowerShell

$
0
0

Is it possible to have a function in powershell which returns values like the "yield return" of C#?

I am parsing a very large excel workbook in powershell and currently my function does nothing when the excel workbook is being loaded into an array.

this is wasting time. 

I wish if the function could start returning records immediately like the yield return approach.

Powershell form randomly hangs - Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

$
0
0

I have a PowerShell script using forms that will randomly crash with the error below.  I have a function that creates the form and buttons on the form that call other functions.  I call the form declaring a variable equal to the create form function; $FORM = DrawForm

In my testing all the buttons function properly, that's why I say random crashes.  For example, in one session I might click button A 5 times, and the first 4 times it does what it's supposed to do, but the 5th time it hangs and eventually crashes.  Then I will start the script again, click button A 8 times; first 7 work, 8th locks up.  I can't find any pattern other than it usually takes at least a handful of tries before it breaks and sometimes it can go for 10s of tries before it does.

The function button A calls has a for loop going through 60 items, but very light work, completing normally in fractions of a second.  And advice on how I can further troubleshoot?

************** Exception Text **************

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.RichTextBox.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Detect Single Path failure in HBA card using powershell for windows server 2003 and 2008

$
0
0

Hi All,

I would like to write a basic script for showing the SAN path health status for my physical servers.

I just able to find WMI classes MSFC_FCAdapterHBAAttributtes and MSFC_FibrePortHBAAttributes, however this two classes not able to show me the path failure and only showing the HBA status as 0 even though single path is failed.

Please advise further as i need to run it for 700+ servers to identified the failure.

Chun

===========

#Get server name
$strComputer = get-content -path C:\Users\xootzecadm\Desktop\test\server.txt

#Get Details
function GetDetails{

ForEach ($computer in $strComputer){
        
$Driveinfo = gwmi win32_volume -computername $computer      
        $HBAinfo = gwmi -namespace root\wmi -class msfc_fcadapterHBAattributes -computer $computer
        
        
        Foreach($Drive in $Driveinfo){
            $Size = $Drive.freespace/1024/1024
            $Sheet1.Cells.Item($intDrive, 1) = $computer
            $Sheet1.Cells.Item($intDrive, 2) = $Drive.driveletter
            $Sheet1.Cells.Item($intDrive, 3) = $Size
            $intDrive = $intDrive + 1
        }
        
        Foreach($HBA in $HBAinfo){
            if($HBA.HBAstatus -eq 0){ $status = "OK"}
            else { $status = "Failed"}
            $Sheet2.Cells.Item($intHBA, 1) = $computer
            $Sheet2.Cells.Item($intHBA, 2) = (($HBA.NodeWWN) | ForEach-Object {"{0:x}" -f $_}) -join ":"
            $Sheet2.Cells.Item($intHBA, 3) = $status
            $intHBA = $intHBA + 1
        }
        
        $intRow = $intRow + 1
}
}

$CurrentPath = $pwd.path
$file = $CurrentPath + "\Drive_HBA.xls"

#Create Excel Application
$Excel = New-Object -com Excel.application
$Excel.visible = $false
$Excel.displayalerts = $false

#Create Excel workbook and worksheet
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Add()
$Sheet = $Excel.Worksheets.Add()

#Assign each worksheet to variable and Name the worksheet
$Sheet1 = $Excel.Worksheets.Item(1)
$Sheet2 = $Excel.Worksheets.Item(2)
$Sheet1.Name = "Drive"
$Sheet2.Name = "SAN"

#create heading
$Sheet1.Cells.Item(1,1) = "Server Name"
$Sheet1.Cells.Item(1,2) = "Drive Letter"
$Sheet1.Cells.Item(1,3) = "Size(MB)"

$Sheet2.Cells.Item(1,1) = "Server Name"
$Sheet2.Cells.Item(1,2) = "WWN"
$Sheet2.Cells.Item(1,3) = "Status"

$intRow = 2
$intDrive = 2
$intHBA = 2

getdetails

$Excel.SaveAs($file)
$Excel.Close()

===========

Post xml on a webservice

$
0
0

Hi,

I'm trying to do an xml post on a webservice. But i think i'm doing something wrong with the XML string. It seems to expect an integer. Does anybody have a tip to get this post working? Please explain me what i'm doing wrong.

function sendXML{
 $url = "http://gateway/gateway.ashx"
 $parameters = 		'<?xml version="1.0" encoding="utf-8"?>' + "'n" + '<MESSAGES>' + "'n"  + '<CUSTOMER ID="test" />' + "'n"  + '<USER LOGIN="test" PASSWORD="test" />' + "'n"  + '<REFERENCE>"Standby"</REFERENCE>' + "'n"  + '<MSG>' + "'n" + '<FROM>"System Center Operations Manager R2"</FROM>' + "'n" + '<DCS>8</DCS>' + "'n" + '<TO>"Standby"</TO>' + "'n" + '<BODY TYPE="String" HEADER="Test_ID">Test</BODY>' + "'n" + '<TO OPERATOR="Standby">"telephone"</TO>' + "'n" + '</MSG>' + "`n"+ '</MESSAGES>'
 $http_request = New-Object -ComObject Msxml2.XMLHTTP
 $http_request.open('POST', $url, $false)
 $http_request.setRequestHeader("Content-type", "text/html")
 $http_request.setRequestHeader("Content-length", $parameters.length)
 $http_request.setRequestHeader("Connection", "close")
 $http_request.send($parameters)
 $http_request.statusText
 $http_request.responseText
 }
 sendXML

Kind regards,

André


Trying to find empty AD groups

$
0
0

Hi,

I'm trying to find empty AD groups using this query:

Get-ADGroup -Filter * -properties members | where {-not $_.members} | ft -property name, GroupScope, GroupCategory -autosize

It works for groups that do not contain any user accounts, but it keeps returning groups that contain only computer accounts ("Domain controllers" for example).

Viewing all 21975 articles
Browse latest View live


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