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

How to override powershell memory limit in remote session

$
0
0

Hi,

I am trying to run a memory allocation tool (testlimit64 from sysinternals suite) on multiple windows VMs remotely. The VMs run windows server 2012, patched up to date.

The machine i'm running the code from also runs windows server 2012.

The code I use to run the testlimit commands is this:

#run memory load routine
foreach ($vm in $testvmsview) {    $vm.IP    
   $s = new-pssession  -ComputerName $vm.IP -credential $cred    Invoke-Command -Session $s -FilePath "C:\Scripts\LoadMem.ps1" -ArgumentList '80'    Read-Host "Enter to continue"    }


The "C:\Scripts\LoadMem.ps1" file that gets executed on the other side is this:

param( [Parameter(Mandatory=$false)][System.String]$PercentAvailRAM=50)

$OBjectCount = [math]::Round(($PercentAvailRAM/100) * (((Get-WMIObject Win32_OperatingSystem).FreePhysicalMemory)/1KB))

#$OBjectCount

$loadmemcmd = "c:\temp\testlimit64.exe -d -c $OBjectCount"

Invoke-Expression $loadmemcmd

The code runs fine, but testlimit returns this error:

Testlimit v5.22 - test Windows limits
Copyright (C) 2012 Mark Russinovich 
Sysinternals - www.sysinternals.com

Process ID: 3152

Leaking private bytes with touch (MB)...

99
199
299
399
499
599
699
799
The paging file is too small for this operation to complete.
    + CategoryInfo          : NotSpecified: (The paging file...on to complete.:String) [], RemoteException+ FullyQualifiedErrorId : NativeCommandError+ PSComputerName        : pc.contoso.com

The issue I am seeing is that, when i run the script remotely, the testlimit64 process is limited to almost 1GB of RAM. I also ran the piece of code in a powershell window, while connected via RDP, and the testlimit64 command works fine, i get the correct amount of ram assigned to the process.

I have tried to change the MaxMemoryPerShellMB value to other values (i suspected it was because of this). i change to 5000MB, 192000MB, no diference in the way my code runs. INvoke-command remotely limits to 1GB, local console runs up to whatever memory allocation I need

Does anyone know why this is happening?

Thank you,
Ionut



new-partition but supress the dialog

$
0
0

hi, I want to initialize, partition, and format using PowerShell on windows Server 2012.

The following 3 lines  works, BUT the new-partition step opens a dialog "You need to format the disk in drive G: before you can use it" .

 I ran it from the PowerShell window and tried from PowerShell ISE, both opened with admin privilages.

How can I suppress that dialog?
maybe the issue is not my PowerShell but rather the Windows Server 2012 environment?

>>>>>>>>>>>>>>>>>>>

Initialize-Disk -Number 2 -PartitionStyle MBR -confirm:$false

New-Partition -DiskNumber 2 -UseMaximumSize -IsActive -DriveLetter z

Get-Partition -DiskNumber 2 -PartitionNumber 1 | Format-Volume -FileSystem NTFS -force -confirm:$false


-Craig (SQL Server User Education Team) // This posting is provided AS IS with no warranties, and confers no rights.


Copy and rename files using a CSV with Powershell

$
0
0

Completely new to this and I am trying to run this simple script to take my source file and copy\rename to a new location.

SAMPLE CSV:

ORGINALFILENAME,NEWFILENAME
G:\Academy\Client Images\374.jpg,E:\Images_Renamed\T00002US01_374.jpg
G:\Academy\Client Images\374-1.JPG,E:\Images_Renamed\T00002US02_374-1.JPG

Script:

Import-Csv e:\scripts\copyimg.csv -Delimter "," | % { Copy-Item -Path $_.ORGINALFILENAME -Destination "E:\Images_Renamed\$($_.NEWFILENAME)

Error:

Copy-Item : The given path's format is not supported.
At line:1 char:54

Any help to point me in the correct direction will help. Thanks!

Pull All User Attributes with PowerShell

$
0
0

Okay, when I go into ADUC and open up the Attribute Editor for a User I see something like 300 attributes. Many are blank or unused, that's fine. I need to pull that full list with Powershell. I don't care whether they are blank or null or whatever, I want a list of every attribute available in my directory. I've tried several different queries with different tools. Get-ADUser is the most comprehensive at 100 attributes returned.

Get-ADUser username -Properties * | Select *
This isn't all of them. For example the "Audio" Attribute doesn't show up. But as soon as I put a value in Audio it does show up. So I know that the CMDLET has access to the attributes it just isn't showing them to me. Is there a flag/switch I'm missing that will show everything? Is there a different CMDLET I should be using?

Thanks much for the help in advance.

Task schedular not run a ftp application

$
0
0

Hi all.

    I Created a Windows Application through vb.net .When i run the exe manually its working.and upload the excel file to ftp link.When i run the application through  task schedular its not working .it showing the status as Running..

Thanks.

office365 new-msoluser

$
0
0

Hi I've got a script which creates new office365 users/mailboxes from csv using the new-msoluser commandlet. I was wondering if it were possible to include the add-distributiongroupmember command into the routine for creating new-msolusers ? So basically complete the account creation for 'John Doe' and then pipe that user into the same foreach routing into the chosen distribution group ?

List empty OU's

$
0
0
i’m using below query to list empty OU’s fom AD. but its not working :(

could some one help me ?

Get-ADObject -Filter {objectclass -eq “OrganizationalUnit”} | Where-Object {@(get-adobject -Filter * -SearchBase $_.DistinguishedName).count -eq 1} | Out-File d:\ou.txt

Regards, Nidhin.CK

PowerShell to Get Duration of Network Connection

$
0
0

Hi,

Is it possible to get the an idea on how to get the Duration of the network Adapter?

I have tried couple of commands in PowerShell but none on them gives me the Duration.

Any help?

Thanks,


Enable-PSRemoting Error

$
0
0

Hi...I am trying to run the Enable-PSRemoting in Windows Server 2012 domain controller. Ifollowed the linkto open the port using group policy....but I am getting the error mentioned below...Also tried WinRM QuickConfig...got error "Error: One or more update steps could not be completed. Unable to enable the firewall for WinRM. 

PS C:\Users\Administrator> Enable-PSRemoting
WinRM is already set up to receive requests on this computer.
Set-WSManQuickConfig : Error:One or more update steps could not be completed.
At line:69 char:17
+                 Set-WSManQuickConfig -force
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Set-WSManQuickConfig], InvalidOperationE
   xception
    + FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.SetWSManQuickConfigCommand

Any help...please let me know.


VT

How to get a parmeter name and type for any command/Script

$
0
0

Hi,

we have a requirement to fetch all the parameters for any powershell command/script using c#. Can you please help me to find the soultion for the same.

Thanks,
Srikanth

remove item command

$
0
0

I want to delete some files on multiple servers.How can i execute this commands on multiple server.

Remove-Item D:\vpm\* -include *sys.txt,error.txt,log.txt
get-childitem D:\vpm\*.* -include *.txt

If i use

PsExec  Remove-Item D:\vpm\* -include *sys.txt,error.txt,log.txt

i get an error saying "PsExec not a valid cmdlet.

I have also tried this code but this also doesn;t work.

Invoke-Command -computername "localhost" -Scriptblock {
Remove-Item D:\vpm\* -include *sys.txt,error.txt,log.txt
get-childitem D:\vpm\*.* -include *.txt
}

Adding color to a RichTextBox

$
0
0

So I have a RichTextBox and I want to colorize individual lines.  The 3 lines I have now are

Red

Green

Blue

So, I want Red to be in Red text, Green in green text, and Blue to be in Blue text.  I have written a basic script.  However when I run it I still get Red, Green, and Blue on seperate lines however they are all still in Black text with an error stating "the term 'color.red' is not recognized as the name of a cmdlet, function..........." <-- I'm sure you all know the rest of the error

If anyone could help, I would really appreciate it.  So here is the code I have...

#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
# Generated On: 7/23/2013 2:38 PM
# Generated By: 
########################################################################

#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
#endregion


#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$richTextBox1 = New-Object System.Windows.Forms.RichTextBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects

#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 262
$System_Drawing_Size.Width = 284
$form1.ClientSize = $System_Drawing_Size
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.Name = "form1"
$form1.Text = "Primal Form"

$richTextBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 19
$System_Drawing_Point.Y = 19
$richTextBox1.Location = $System_Drawing_Point
$richTextBox1.Name = "richTextBox1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 225
$System_Drawing_Size.Width = 245
$richTextBox1.Size = $System_Drawing_Size
$richTextBox1.TabIndex = 0
$winuprem = "Red"
$richTextbox1.selectedtext = $winuprem
$richtextbox1.selectionbackcolor = color.red 
$richTextBox1.text = "$winuprem" + "`n"
$richTextBox1.text += "White" + "`n"
$richTextBox1.text += "Blue" + "`n"
$form1.Controls.Add($richTextBox1)

#endregion Generated Form Code

#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null

} #End Function

#Call the Function
GenerateForm

PowerShell remoting: Results not returned using Enter-PSSession vs Invoke-Command???

$
0
0

So my code generates output when using Enter-PSSession but the same code does not return data using invoke-command (using CredSSP) as a script.

Here is the relevant excerpt from my script:

So I am able to use the Get-SPWeb.Recylce() method when I am using Enter-PSSession but as soon as I turn this code into a script with invoke-command I do not get access to that method.  What gives?  I am still logged in as the same user.  I suppose it would be a permissions issue but my login never changed

if ((Get-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null) {
      Add-PSSnapin Microsoft.SharePoint.PowerShell
    }

    $webapps = (Get-SPWebApplication | % {$_.url})
    $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
    foreach ($webapp in $webapps) {
      $appdetails = Get-SPWebapplication $webapp
      $appdetails.GrantAccessToprocessIdentity("$env:userdomain"+"\$env:username")
      $spWeb = Get-SPWeb -Identity $webapp
      $DocLibName = "MSOTest$($appdetails.displayname)".split(".")[0]
      $DocLibName += "_DocumentLibrary"
      try { 
        $library = $null
        $library = $spWeb.lists["$DocLibName"]
      }
      catch {out-null}
      if ($library) {
        #If document library does exist, delete it
        $spFolder = $spWeb.GetFolder("$DocLibName") 
        $spFolder.recylce() | out-null
      } 



-Filter parameter

$
0
0

Hello!

Having read this: http://www.computerperformance.co.uk/powershell/powershell_wmi_filter.htm

"

PowerShell -Filter Parameter

PowerShell's -filter is an alternative solution to the | Where-Object {$_.clause} when sieving data.  Using -filter instead of 'Where' is a classic case of when you find a good technique, look for an even better modus operandi.

"

...I assume that I can use -Filter instead of  Where-Object in any cmdlets. But, for example, runningGet-process -Filter ... produces the error stating there's no such parameter, whereasGet-WmiObject ... -Filter works as expected. Why?

Thank you in advance,

Michael

run an exe without prompt to run or not from powershell

$
0
0

Hello Team,

I am developing an automation to install few application on PC remotely, script run on windows 7.

I need to run set of .exe files from shared drive. I have map the drive where installation files are stored. When I invoke the exe from PowerShell windows security prompts ask to run or not for each exe.

I do like to run exe one after other without prompting for user input, how can I achieve this with PowerShell.

Thanks


sridhar v


Eventviewer Log to Text File

$
0
0
In Eventviewer -> Application and Services -> Microsoft -> Windows -> Backup -> Operational there are various events, In case Event ID 4 or 5 occurs need to send all the contents in details tab to a text file. Need Help...

Bala


WinRM cannot complete the operation

$
0
0

I have been trying to deploy Microsoft Dynamics NAV on Windows Azure. Microsoft has gives few scripts which helps us deploy. While running the script I get the error :

"Get-WSManInstance : <f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault" Code="2150859046" 
Machine="MyCompName"><f:Message>WinRM cannot complete the operation. Verify that the specified computer name is valid, 
that the computer is accessible over the network, and that a firewall exception for the WinRM service is enabled and allows access from this 
computer. By default, the WinRM firewall exception for public profiles limits access to remote computers within the same local subnet. 
</f:Message></f:WSManFault>"

WinRM Service is running and WinRM is also setup for Remote Management using the Enable-PSRemoting -force.

It would be helpful if anyone can suggest a solution.


Looking to modify this script to pull user highitem count and exclude a specific OU

$
0
0

I have found the below powershell script that pulls highitems from exchange 2010. I would like to modify the script to exclude users who are part of a specific OU. I am also looking to include archive mailbox sizes, if possible. I know this script was written t work with several versions of exchange, I am open to creating a new script that can get the necessary info (folder path, item count, and database), but I dont know how to do it for a specific ou. Any help is greatly appreciated. Thank you so much.

################################################################################# 
#  
# The sample scripts are not supported under any Microsoft standard support  
# program or service. The sample scripts are provided AS IS without warranty  
# of any kind. Microsoft further disclaims all implied warranties including, without  
# limitation, any implied warranties of merchantability or of fitness for a particular  
# purpose. The entire risk arising out of the use or performance of the sample scripts  
# and documentation remains with you. In no event shall Microsoft, its authors, or  
# anyone else involved in the creation, production, or delivery of the scripts be liable  
# for any damages whatsoever (including, without limitation, damages for loss of business  
# profits, business interruption, loss of business information, or other pecuniary loss)  
# arising out of the use of or inability to use the sample scripts or documentation,  
# even if Microsoft has been advised of the possibility of such damages 
# 
################################################################################# 
param( 
[bool] $CriticalFoldersOnly = $true, 
[string] $Database = "", 
[string] $DomainController = "", 
[bool] $FormatList = $false, 
[int32] $ItemCount = -1, 
[string] $OutputFile = "", 
[string] $ResultSize = "unlimited", 
[string] $Server = "") 
#Script Parameters: 
#-CriticalFoldersOnly: Only checks Calendar, Contacts, Inbox, and Sent Items. The default value is $true. 
#-Database: Specifies the target Database. Overrides the -Server option if set. 
#-DomainController: Specifies the default Domain Controller to use for mailbox and folder tests. 
#-FormatList: Outputs to the screen in list format. The default is table format. 
#-ItemCount: Ignores the max limits, and finds folders with the specified item count. 
#-OutputFile: Specifies the output file. Should be in .CSV format. 
#-ResultSize: Specifies the maximum number of mailboxes to check. The default value is unlimited. 
#-Server: Specifies the target Exchange server. 
# Function used to check the individual item count of folders within a given mailbox 
function checkFolderItems 
{ 
    param( 
    $mbx, 
    [ref]$fldrArray, 
    [ref]$mbxFailed) 
    #Set item limit to search for 
    [int32] $maxItems = 5000 
    if ($mbx.ExchangeVersion -eq "2000") 
    { 
        $maxItems = $2kmax 
    } 
    elseif ($mbx.ExchangeVersion -eq "2003") 
    { 
        $maxItems = $2k3max 
    } 
    elseif ($mbx.ExchangeVersion -eq "2007") 
    { 
        $maxItems = $2k7max 
    } 
    elseif ($mbx.ExchangeVersion -eq "2010") 
    { 
        $maxItems = $2k10max 
    } 
    #Create the base of our Get-MailboxFolderStatistics command 
    $getFoldersString = "Get-MailboxFolderStatistics -Identity `"$($mbx.Identity)`""
    #-ErrorAction SilentlyContinue" 
    #Add the domain controller if specified 
    if ($DomainController -ne "") 
    { 
        $getFoldersString += " -DomainController $DomainController" 
    } 
    #Add the filter portion of the command 
    if ($CriticalFoldersOnly -eq $true) 
    { 
        $getFoldersString += " | Where {(`$_.Name -like 'Calendar' -or `$_.Name -like 'Contacts' -or `$_.Name -like 'Inbox' -or `$_.Name -like 'Sent Items') -and `$_.ItemsInFolder -ge $maxItems}" 
    } 
    else 
    { 
        $getFoldersString += " | Where {`$_.ItemsInFolder -ge $maxItems}" 
    } 
    #Get the current error count so we can report errors after checking folders 
    $errorCountBefore = $error.Count 
    #Actually run our command and process all folders over the item limit 
    Invoke-Expression -Command $getFoldersString | ForEach-Object{ 
        $folder = New-Object PSObject 
        $folder | Add-Member NoteProperty User $mbx.Alias -Force 
        $folder | Add-Member NoteProperty Folder $_.FolderPath -Force 
        $folder | Add-Member NoteProperty ItemCount $_.ItemsInFolder -Force 
        $folder | Add-Member NoteProperty Database $mbx.Database -Force 
        $folder | Add-Member NoteProperty Version $mbx.ExchangeVersion -Force
        if ($fldrArray.Value[0] -ne "") 
        { 
            $fldrArray.Value += @($folder) 
        } 
        else 
        { 
            $fldrArray.Value = @($folder) 
        } 
    } 
    #Now check the current error count. Report an error if it is larger than when we started 
    if ($error.Count -gt $errorCountBefore) 
    { 
        Write-Host -ForeGroundColor red "ERROR: Unable to process mailbox '$($mbx.Alias)'." 
        $mbxFailed.Value++ 
    } 
} 
# Function that checks whether the target server or database is inaccessible. 
# This prevents us from timing out on each inaccessible mailbox. 
# Note, this does not work against 2000-2003 mailboxes. 
# Returns $true if accessible, and $false is not. 
function checkAccessibility 
{ 
    param( 
    [ref]$badServers, 
    [ref]$badDBs, 
    [ref]$goodServers, 
    [ref]$goodDBs, 
    [ref]$mbxFailed, 
    $mbx) 
    #Check database and server accessibility. If mailbox is not on Exchange 2007+, or the server or database are already bad, fail. 
    if ($mbx.ExchangeVersion -ge 2007 -and !($badDBs.Value -Contains $mbx.Database) -and !($badServers.Value -Contains $mbx.ServerName)) 
    { 
        #Check if mailbox is on a higher version of Exchange than this shell 
        if ($mbx.ExchangeVersion -ge 2010 -and (Get-Command "Microsoft.Exchange.PowerShell.Configuration.dll").FileVersionInfo.FileVersion -lt "14") 
        { 
            Write-Host -ForeGroundColor red "ERROR: Server '$($mbx.ServerName)' is running a higher version of Exchange than this machine. Skipping all mailboxes on this server." 
            $badServers.Value += $mbx.ServerName 
            $mbxFailed.Value++ 
            return $false         
        } 
        #Check if database or server is already marked as good. 
        $serverGood = $false 
        $dbGood = $false 
        if ($goodServers.Value -Contains $mbx.ServerName) 
        { 
            $serverGood = $true 
        } 
        if ($goodDBs.Value -Contains $mbx.Database) 
        { 
            $dbGood = $true 
        } 
        #Either the server or database have not been marked as good. Proceed with connectivity test. 
        if (!$serverGood -or !$dbGood) 
        { 
            $failed = $false 
            $testMAPIString = "Test-MAPIConnectivity -Database '$($mbx.Database)' -PerConnectionTimeout 10 -ErrorAction SilentlyContinue" 
            if ($DomainController -ne "") 
            { 
                $testMAPIString += " -DomainController $DomainController" 
            } 
            $testMAPI = Invoke-Expression -Command $testMAPIString 
            #Check if the server is accessible 
            if (!$serverGood -and $testMAPI.Error -like "Microsoft Exchange Information Store service is not running.") 
            { 
                Write-Host -ForeGroundColor red "ERROR: Server '$($mbx.ServerName)' is inaccessible. Skipping all mailboxes on this server." 
                $badServers.Value += $mbx.ServerName 
                $failed = $true                     
            } 
            else 
            { 
                $goodServers.Value += $mbx.ServerName 
            } 
            #Check if the database is accessible 
            if (!$dbGood -and $testMAPI.Result -like "*Failure*" -and $testMAPI.Error -notlike "Microsoft Exchange Information Store service is not running.") 
            { 
                Write-Host -ForeGroundColor red "ERROR: Database '$($mbx.Database)' is inaccessible. Skipping all mailboxes on this database."              
                $badDBs.Value += $mbx.Database 
                $failed = $true 
            } 
            else 
            { 
                $goodDBs.Value += $mbx.Database 
            } 
            #Check if we failed 
            if ($failed) 
            { 
                $mbxFailed.Value++ 
                return $false 
            } 
            else 
            { 
                return $true 
            } 
        } 
        else 
        { 
            #The server and database are both in the good list. Proceed with checking mailbox 
            return $true 
        } 
    } 
    elseif ($mbx.ExchangeVersion -lt 2007) 
    { 
        #Do nothing and proceed to checking mailbox 
        return $true 
    } 
    else 
    { 
        #The server or database is in the bad list. Skip this mailbox 
        $mbxFailed.Value++ 
        return $false 
    } 
} 
# Function that writes output to the screen, and writes to the output file if specified 
function writeOutput 
{ 
    param( 
    [ref]$fldrArray) 
    [int32] $maxItems = 5000 
    if ($fldrArray.Value[0].Version -eq "2000") 
    { 
        $maxItems = $2kmax 
    } 
    elseif ($fldrArray.Value[0].Version -eq "2003") 
    { 
        $maxItems = $2k3max 
    } 
    elseif ($fldrArray.Value[0].Version -eq "2007") 
    { 
        $maxItems = $2k7max 
    } 
    elseif ($fldrArray.Value[0].Version -eq "2010") 
    { 
        $maxItems = $2k10max 
    } 
    #Write output to screen 
    $screenOutput = @() 
    Write-Host "" 
    Write-Host -ForeGroundColor green "Exchange $($fldrArray.Value[0].Version) Folders With $($maxItems) or More Items:"         
    for ($i = 0; $i -lt $fldrArray.Value.Length; $i++) 
    { 
        $screenOutput += $($fldrArray.Value[$i]) 
        #Write output to file 
        if ($usingOutput -eq $true) 
        { 
            $currentLine = "$($fldrArray.Value[$i].User)`t$($fldrArray.Value[$i].Folder)`t$($fldrArray.Value[$i].ItemCount)`t$($fldrArray.Value[$i].Database)`t$($fldrArray.Value[$i].Version)" 
            $currentLine | Out-File -Append -NoClobber $OutputFile     
        } 
    } 
    #Check whether we should output in list or table format 
    if ($FormatList) 
    { 
        Write-Output $screenOutput | fl User, Folder, ItemCount, Database 
    } 
    else 
    { 
        Write-Output $screenOutput | ft User, Folder, ItemCount, Database -Autosize 
    } 
    #Add the folders from this pass to the master output array 
    $outputArray += $screenOutput 
    $screenOutput = $null 
} 
#Function that parses the ExchangeVersion property on a mailbox 
function getExchangeVersion 
{ 
    param( 
    [ref]$mbx) 
    [double] $mbxVer = 0 
    #Check whether ExchangeVersion is set properly on the mailbox 
    if ($mbx.Value.ExchangeVersion.ExchangeBuild.Major -lt 6 -or $mbx.Value.ExchangeVersion.ExchangeBuild.Major -gt 20) 
    { 
        #ExchangeVersion is not set properly. Defaulting to Exchange 2010 
        $mbxVer = 14 
    } 
    else 
    { 
        $mbxVer = $mbx.Value.ExchangeVersion.ExchangeBuild.Major + ($mbx.Value.ExchangeVersion.ExchangeBuild.Minor/10) 
    } 
    #Convert the version to a string 
    #The mailbox is 2010 
    if ($mbxVer -ge 14) 
    { 
        $mbxVer = "2010" 
    } 
    #The mailbox is 2007 
    elseif ($mbxVer -ge 8 -and $mbxVer -le 8.5) 
    { 
        $mbxVer = "2007" 
    } 
    #The mailbox is 2003 
    elseif ($mbxVer -eq 6.5) 
    { 
        $mbxVer = "2003" 
    } 
    #The mailbox is 2000 
    elseif ($mbxVer -ge 6 -and $mbxVer -lt 6.5) 
    { 
        $mbxVer = "2000" 
    } 
    #We didn't find the version. Default to 2010 
    else 
    { 
        $mbxVer = "2010" 
    } 
    return $mbxVer 
} 
# Function that returns true if the incoming argument is a help request 
function IsHelpRequest 
{ 
    param($argument) 
    return ($argument -eq "-?" -or $argument -eq "-help"); 
} 
# Function that displays the help related to this script following 
# the same format provided by get-help or <cmdletcall> -? 
function Usage 
{ 
@" 
NAME: 
`tHighItemFolders.ps1 
SYNOPSIS: 
`tFinds users who have folders with more than the recommended 
`titem count. The item count that is searched for is different for 
`teach Exchange version: 
`t`tExchange 2000: 5000 Items 
`t`tExchange 2003: 5000 Items 
`t`tExchange 2007: 20,000 Items 
`t`tExchange 2010: 100,000 Items 
SYNTAX: 
`tHighItemFolders.ps1 
`t`t[-CriticalFoldersOnly <BooleanValue>] 
`t`t[-Database <DatabaseIdParameter>] 
`t`t[-DomainController <StringValue>] 
`t`t[-FormatList <BooleanValue>] 
`t`t[-ItemCount <IntegerValue>] 
`t`t[-OutputFile <OutputFileName>] 
`t`t[-ResultSize <StringValue>] 
`t`t[-Server <ServerIdParameter>] 
PARAMETERS: 
`t-CriticalFoldersOnly 
`t`tSpecifies whether to check only Critical Folders, which 
`t`tare Calendar, Contacts, Inbox, and Sent Items. Should be 
`t`tinput as either `$true or `$false. If omitted, the default 
`t`tvalue is $true. 
`t-Database 
`t`tSpecifies the target database. 
`t`tOverrides the -Server switch if used. 
`t-DomainController 
`t`tSpecifies the Domain Controller to use for all mailbox 
`t`tand folder tests. If omitted, the default value is `$null. 
`t-FormatList 
`t`tWrites output to the screen in list format instead of 
`t`ttable format. Should be input as either `$true or `$false. 
`t`tIf omitted, the default value is `$false. 
`t-ItemCount 
`t`tIgnores the max limits, and finds folders with the 
`t`tspecified item count. 
`t-OutputFile 
`t`tSpecifies the output file. Should be in .CSV format. 
`t-ResultSize 
`t`tSpecifies the maximum number of mailboxes to be checked. 
`t`tCan be specified either as a number, or 'Unlimited'. 
`t`tIf omitted, the default value is unlimited. 
`t-Server 
`t`tSpecifies the target Exchange server. 
`t-------------------------- EXAMPLES ---------------------------- 
C:\PS> .\HighItemsUsers.ps1 -Server "MyEx2007Server" -OutputFile output.csv -CriticalFoldersOnly `$false 
C:\PS> .\HighItemsUsers.ps1 -Database "MyEx2007Server\My Storage Group\My Database" 
C:\PS> .\HighItemsUsers.ps1 
REMARKS: 
`tIf -Database and -Server are omitted, the entire Organization 
`twill be checked. "@ 
} 
#################################################################################################### 
# Script starts here 
#################################################################################################### 
# Check for Usage Statement Request 
$args | foreach { if (IsHelpRequest $_) { Usage; exit; } } 
#Declare the arrays for holding problem folders. 
#The arrays are initialized to "" so that they can be passed by 
#reference, even if they contain no objects. 
[Array] $2kFolders = "" 
[Array] $2k3Folders = "" 
[Array] $2k7Folders = "" 
[Array] $2k10Folders = "" 
#Declare the arrays for keeping track of inaccessible servers and databases. 
[Array] $badServers = @() 
[Array] $badDBs = @() 
[Array] $goodServers = @() 
[Array] $goodDBs = @() 
#Declare the item count limits we are looking for 
if ($ItemCount -gt -1) 
{ 
    $2kmax = $ItemCount 
    $2k3max = $ItemCount 
    $2k7max = $ItemCount 
    $2k10max = $ItemCount 
} 
else 
{ 
    $2kmax = 5000 
    $2k3max = 5000 
    $2k7max = 20000 
    $2k10max = 100000 
} 
#Declare variables for keeping track of progress 
[int32]$mbxSucceeded = 0 
[int32]$mbxCount = $mbxCmd.Count 
[int32]$mbxFailed = 0 
#Determine which Get-Mailbox command to run 
$getMbxString = "Get-Mailbox -ResultSize $ResultSize" 
if ($Server -ne "") 
{ 
    $getMbxString += " -Server $Server" 
} 
elseif ($Database -ne "") 
{ 
    $getMbxString += " -Database '$Database'" 
} 
else 
{ 
    #Do nothing. Use the default command 
} 
if ($DomainController -ne "") 
{ 
    $getMbxString += " -DomainController $DomainController" 
} 
#This array will hold just the properties we need for each mailbox. This helps to conserve memory 
$mailboxes = @() 
#Start our progress bar 
Write-Progress -Activity "Getting All Mailboxes in the Specified Scope" -Status "Command: $getMbxString" 
#Actually run the command and store the output in $mailboxes 
Invoke-Expression -Command $getMbxString | ForEach-Object{ 
    $ver = getExchangeVersion -mbx ([ref]$_) 
    $mbx = New-Object PSObject 
    $mbx | Add-Member NoteProperty Identity $_.Identity.ToString() 
    $mbx | Add-Member NoteProperty Alias $_.Alias.ToString() 
    $mbx | Add-Member NoteProperty ServerName $_.ServerName.ToString() 
    $mbx | Add-Member NoteProperty Database $_.Database.ToString() 
    $mbx | Add-Member NoteProperty ExchangeVersion $ver 
    $mailboxes += $mbx 
} 
#Close progress bar 
Write-Progress -Activity "Getting All Mailboxes in the Specified Scope" -Completed -Status "Completed" 
#Get total mailbox count 
$mbxCount = $mailboxes.Count 
#Begin processing of mailboxes 
foreach ($mailbox in $mailboxes) 
{ 
    #Update Progress Bar 
    $failCountBefore = $mbxFailed 
    Write-Progress -Activity "Checking $mbxCount Mailboxes for High Item Counts" -Status "Mailboxes Successfully Processed: $mbxSucceeded   Inaccessible Mailboxes: $mbxFailed" 
    #Check whether the server and database of this mailbox are accessible (only works on 2007 and higher) 
    if (!(checkAccessibility -badServers ([ref]$badServers) -badDBs ([ref]$badDBs) -goodServers ([ref]$goodServers) -goodDBs ([ref]$goodDBs) -mbxFailed ([ref]$mbxFailed) -mbx $mailbox)) 
    { 
        #We failed the accessibility check. Skip this mailbox. 
        Continue 
    } 
    #Now on to the actual item checking 
    #Mailbox version is Exchange 2000 
    if ($mailbox.ExchangeVersion -eq "2000") 
    { 
        checkFolderItems -mbx $mailbox -fldrArray ([ref]$2kFolders) -mbxFailed ([ref]$mbxFailed) 
    } 
    #Mailbox version is Exchange 2003 
    elseif ($mailbox.ExchangeVersion -eq "2003") 
    { 
        checkFolderItems -mbx $mailbox -fldrArray ([ref]$2k3Folders) -mbxFailed ([ref]$mbxFailed) 
    } 
    #Mailbox version is Exchange 2007 
    elseif ($mailbox.ExchangeVersion -eq "2007") 
    { 
        checkFolderItems -mbx $mailbox -fldrArray ([ref]$2k7Folders) -mbxFailed ([ref]$mbxFailed) 
    }     
    #Mailbox version is Exchange 2010 
    elseif ($mailbox.ExchangeVersion -eq "2010") 
    { 
        checkFolderItems -mbx $mailbox -fldrArray ([ref]$2k10Folders) -mbxFailed ([ref]$mbxFailed) 
    } 
    if ($failCountBefore -eq $mbxFailed) 
    { 
        $mbxSucceeded++ 
    } 
} 
#Done processing mailboxes. Stop the progress bar 
Write-Progress -Activity "Checking $mbxCount Mailboxes for High Item Counts" -Completed -Status "Completed" 
#Initialize the Output File 
$usingOutput = $false 
if ($OutputFile -ne "") 
{ 
    $usingOutput = $true "Alias`tFolderPath`tItemsInFolder`tDatabase`tExchangeVersion" | Out-File $OutputFile 
} 
#Sort all the folders based on item count 
Write-Progress -Activity "Sorting Folders by Item Count" -Status " " 
$2kFolders = $2kFolders | Sort-Object -Property ItemCount -Descending 
$2k3Folders = $2k3Folders | Sort-Object -Property ItemCount -Descending 
$2k7Folders = $2k7Folders | Sort-Object -Property ItemCount -Descending 
$2k10Folders = $2k10Folders | Sort-Object -Property ItemCount -Descending 
Write-Progress -Activity "Sorting Folders by Alias" -Completed -Status "Completed" 
#Start writing folder output 
$totalFolders = 0 
#Write Exchange 2000 Folders to Screen and Output File 
if ($2kFolders[0] -ne "") 
{ 
    writeOutput ([ref]$2kFolders) 
    $totalFolders += $2kFolders.Length 
} 
#Write Exchange 2003 Folders to Screen and Output File 
if ($2k3Folders[0] -ne "") 
{ 
    writeOutput ([ref]$2k3Folders) 
    $totalFolders += $2k3Folders.Length 
} 
#Write Exchange 2007 Folders to Screen and Output File 
if ($2k7Folders[0] -ne "") 
{ 
    writeOutput ([ref]$2k7Folders) 
    $totalFolders += $2k7Folders.Length 
} 
#Write Exchange 2010 Folders to Screen and Output File 
if ($2k10Folders[0] -ne "") 
{ 
    writeOutput ([ref]$2k10Folders) 
    $totalFolders += $2k10Folders.Length 
} 
#Write final statistics to screen 
Write-Host "" 
Write-Host -ForeGroundColor Green "Finished Processing Mailboxes" 
Write-Host -ForeGroundColor yellow "Total Mailboxes Found: " -NoNewLine 
Write-Host "$mbxCount" 
Write-Host -ForeGroundColor yellow "Mailboxes Successfully Processed: " -NoNewLine 
Write-Host "$mbxSucceeded" 
Write-Host -ForeGroundColor yellow "Mailboxes Skipped: " -NoNewLine 
Write-Host "$mbxFailed" 
Write-Host -ForeGroundColor yellow "High Item Folders Found: " -NoNewLine 
Write-Host "$totalFolders"

get timings for ssas full cube process keep a log

$
0
0

  Are there any scripts where you can get start end time of a cube rebuild. I know you can get the LOG of
the process, but would be nice to see start stop for each dim and Measure group.


 Like

 dim_items -- started 09:01:00
                    ended 09:02:15

  This way you could monitor individual run times to monitor any spikes that maybe happening and be
proactive.

 Thanks.

script to RDP multiple servers

$
0
0

Hi,

Please help me in my below query...

First Question

              I needs to check if i can RDP to multiple(34) windows servers.

               I am using the below script to find out if RDP is open on multiple servers by giving servers in txt file

               $Servers = get-content C:\serverlist1.txt

               foreach($server in $servers)
       {
                New-Object System.Net.Sockets.TCPClient -ArgumentList "$server",3389
       }

           I get below result

        Client              : System.Net.Sockets.Socket
        Available           : 0
        Connected           : True
        ExclusiveAddressUse : False
        ReceiveBufferSize   : 8192
        SendBufferSize      : 8192
        ReceiveTimeout      : 0
        SendTimeout         : 0
        LingerState         : System.Net.Sockets.LingerOption
        NoDelay             : False

on the third line of result there is TRUE value

Does this mean the server is up and running ? if not please suggest which is best way.

Second Question.

is there a way to check if profiles are loading on windows server using powershell script ?

Thanks in advance

Alex

      


Alex

Viewing all 21975 articles
Browse latest View live


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