Archive

Posts Tagged ‘PowerShell’

Viewing open files on a file server from powershell.

December 5, 2012 2 comments

http://andymorgan.files.wordpress.com/2011/03/windows_powershell_icon.png?w=58&h=58&h=58So this is a situation you should all be aware of in an SBC / VDI environment, despite all warnings, you’ve redirected folders to your network drive and your file servers are screaming in agony?

Having been in this situation recently, I needed to audit and report on the types of files open on the file server, my hunch was a certain select number of users were running applications (like *gulp* lotus notes) from the network share.

Disappointed with the powershell scripts on the interwebs, I decided to write my own function to perform this task:

function get-openfiles{
param(
    $computername=@($env:computername),
    $verbose=$false)
    $collection = @()
foreach ($computer in $computername){
    $netfile = [ADSI]"WinNT://$computer/LanmanServer"

        $netfile.Invoke("Resources") | foreach {
            try{
                $collection += New-Object PsObject -Property @{
        		  Id = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
        		  itemPath = $_.GetType().InvokeMember("Path", 'GetProperty', $null, $_, $null)
        		  UserName = $_.GetType().InvokeMember("User", 'GetProperty', $null, $_, $null)
        		  LockCount = $_.GetType().InvokeMember("LockCount", 'GetProperty', $null, $_, $null)
        		  Server = $computer
        		}
            }
            catch{
                if ($verbose){write-warning $error[0]}
            }
        }
    }
    Return $collection
}

The function above (get-openfiles) has been written to accept an array of servers to the command line and it will return the following items:

  • The ID of the open file.
  • The server it’s open from.
  • The username who has the file open.
  • The amount of locks the file has.

A couple of quick examples for using this command are below:


Retrieving open files from server1:


full

get-openfiles -computername server1 | select server,itempath,lockcount



Retrieve a count of open files that end with the nsf file type (Lotus Notes):


count

(get-open files -computername server1,server2 | ? {$_.itempath -like "*.nsf*"}).count()



Retrieve a report of total open files on a number of file servers:


report

 

get-openfiles -computername server1,server2,server3,server4,server5 | group -property server

 

Monitoring Storage disk queue’s and IO with PowerShell

November 30, 2012 3 comments

http://andymorgan.files.wordpress.com/2011/03/windows_powershell_icon.png?w=58&h=58&h=58Here’s one that used to bother me alot. The problem usually went as follows:

“Your XenApp servers have very high disk queue’s and IO”

“What’s causing it?”

“dunno…”

With Server 2008, the task manager’s resource monitor feature will help you find these items. But in server 2003 this was a perilous task. The specific details for disk io per process are stored in performance monitor under each specific process running. Trying to analyse each process was a massive pain, but powershell can do some very clever work to help alleviate this!

I wrote two quick functions which act similar to “top” in linux for giving an on screen view, updating at interval of what exactly is creating IO activity. These two functions are:

get-IODataBytes:

storageio

Get-IODataOperations

storageioops

The code for these functions are below:

function get-iodatabytes{
    $result=(get-counter -counter "\Process(*)\IO Data Bytes/sec" -ea 0).countersamples | ? {$_.cookedvalue -gt 0} | select instancename,@{Name="SessionID";Expression={if ($_.path.contains("#")){($_.path.split("#)"))[1]}else{"0"}}},@{Name="IO Data Bytes/sec";Expression={[math]::Round($_.cookedvalue,0)}},@{Name="IO Data KBytes/sec";Expression={[math]::Round($_.cookedvalue / 1024,0)}} | sort -Descending "IO Data Bytes/sec" | ft
    $currentqueue=(((get-counter -counter "\PhysicalDisk(0 C:)\Current Disk Queue Length" -ea 0).countersamples) | select cookedvalue).cookedvalue
    clear
    write-warning "Hit [CTRL] + [C] to exit live capture"
    write-host "Current Disk queue: $currentqueue"
    return $Result
}

FUnction get-IODataOperations {
    $result=(get-counter -counter "\Process(*)\IO Data Operations/sec" -ea 0).countersamples | ? {$_.cookedvalue -gt 0} | select instancename,@{Name="SessionID";Expression={if ($_.path.contains("#")){($_.path.split("#)"))[1]}else{"0"}}},@{Name="IO Data Operations/sec";Expression={[math]::Round($_.cookedvalue,0)}} | sort -Descending "IO Data Operations/sec" | ft
    $currentqueue=(((get-counter -counter "\PhysicalDisk(0 C:)\Current Disk Queue Length" -ea 0).countersamples) | select cookedvalue).cookedvalue
    clear
    write-warning "Hit [CTRL] + [C] to exit live capture"
    write-host "Current Disk queue: $currentqueue"
    return $Result
}

if you wish to loop one of these functions, simply use the following code:

while ($true){
get-iodataoperations
start-sleep 1
}

Silently installing the Citrix Edgesight ActiveX plugin

September 5, 2012 3 comments

Just a really quick blog post on how to silently install the reporting agent inside your environment.

Log into a server / client without the EdgeSight plugin installed, and browse to the edgesight website. Once logged in, you will receive the usual prompt to install the software:

Install the software and ensure it works, then fire up a command prompt and browse down to “c:\windows\downloaded program files”. Once in this folder, a DIR will reveal the ActiveX plugin “csmdbprov.dll”.

Now simply copy this file out to shared storage:

Once done, now its scripting time!

Below are two examples in batch (.bat , .cmd) or PowerShell (.ps1) for achieving this:

(please amend h:\csmdbprov.dll to the path you use)

Batch:

copy h:\csmdbprov.dll "c:\windows\downloaded program files"
regsvr32 /s "c:\windows\downloaded program files"

Powershell:

if (test-path h:\csmdbprov.dll){
	copy-item H:\csmdbprov.dll 'C:\Windows\Downloaded Program Files' -Force
	start-process regsvr32 -ArgumentList "/s ""C:\Windows\Downloaded Program Files\csmdbprov.dll""" -wait
}

Disable the Windows Firewall in Server 8 Beta, with Powershell

March 17, 2012 8 comments

(Note: this will also work with Windows 8 Consumer Preview)

While troubleshooting an issue in windows server 8’s new Powershell Web Access, I had the need to disable the windows firewall. Normally I would use a “netsh firewall” command, but when running this in windows server 8 we receive the notification:

“In future versions of Windows, Microsoft might remove the Netsh Functionality for windows firewall with Advanced Security”

“If you currently use Netsh firewall to configure and manage Windows Firewall with advanced Security, Microsoft recommends that you transition to Windows Powershell.”

This message continues in the screenshot below:





So with the warning in mind, I decided it was time to learn the new thing for the day and off I went to find out how to quickly disable the firewall using powershell!

As above the first clue is in the message, a new module seems to be available on both Windows 8 and Server 8. So with a quick get-module -listavailable I can see netsecurity listed:





“So what commands can I use with the netsecurity module” I asked myself. I ran a quick “Get-Command -module NetSecurity” and was overwhelmed with a large list of potential candidates as below:





So I used the trusted “Import-Module NetSecurity” command and set about reading the help files. Or so I thought…





As with PowerShell 3.0, the helpfiles for Powershell are not completely installed by default, we need to run update-help to download the powershell help files. This is causing quite a debate in the powershell community, so I’m not going to get into this, personally I think its a good idea.

Anyway, so off I went to update the help, or so I thought:





Bugger…

I’ll admit, this list had me scratching my head for some time, but I soon enough stumbled across the important command on this list for my objective. “Get-NetFirewallProfile”.

Get-NetFirewallProfile lists out the firewall profiles for your machine. The profiles are separated out into Domain, Public and Private as you can see in the screen-shot below:





Now that we’re aware of where the profiles live, its just a simple task of piping the current profiles, into a “Set-NetFirewallProfile” command to turn the profiles off.

Below is a quick on-liner to disable the windows firewall in Server 8 or Windows 8 completely:

Import-Module NetSecurity -ea Stop ; Get-NetFirewallProfile | Set-NetfirewallProfile -Enabled False



And that’s it!





And once finished troubleshooting, you can turn it back on as below:

Import-Module NetSecurity -ea Stop ; Get-NetFirewallProfile | Set-NetfirewallProfile -Enabled True

Friday Fun: Powershell with Citrix PNAgent.

February 24, 2012 4 comments

This is something I was playing with for a while. I couldn’t quite get the conversions right without over complicating the script. But as with everything I do, Remko Weijnen, the legend that he is read my mind from afar and published the following fantastic article: Scripting Citrix Online Plugin Settings which basically made my script look like it was written by a two year old!

So with his much improved code I set about writing a script to query the Program Neighbourhood Agent’s applications and launching them too with powershell.

By default, when Program Neighbourhood Agent launches, it populates the Application Model key(s) in HKEY_CURRENT_USER\Software\Citrix\PNAgent.

After the launch, we can use powershell to convert these binary keys into useable data, stick them all together then pull the application details.

With the below script, you can:

Query applications published:


Filter query published applications:



Launch Published applications:



And if you’re crazy, auto launch all applications:

 

The script can be found after the jump below:

Read more…

Removing users access to “Devices and Printers” in a Server 2008 R2 / Win 7 Environment.

January 27, 2012 1 comment

I love a good challenge. Recently I read the following article from Microsoft about how to tackle the title of this blog. This hack didn’t actually stop the users from accessing the cpl as clever users will just use rundll32 to get around the limitation. This also knocked other “show the following control panel items” policies out.

This really inst a huge issue to most environments, as users will probably want to enumerate their printers at one stage or another. But in a RES Workspace manager environment, RES provide a much better interface for printer management which really defunct’s and eliminates the need for the windows method.

The culprit can be seen below:

This problem for me, all stems from the “NoSetFolders” chestnut, anyone who’s tried to lock down a Terminal services environment from Windows Server 2000 onwards will be aware that this “handy” group policy removes the users ability to use [Windows Key] and [E] to open explorer. This issue still isn’t fixed in 2008 R2 and I’m beginning to think Microsoft just wont fix it. Hey no big deal right? Yes, quite a big deal if you ask pedantic users.

Anyway, I digress. Once you remove the NoSetFolders key, the user has the ability to see the devices and printers as below on the start menu, hence my situation.

To remove this folder view for all users, its time to hack the registry!

The Class ID belonging to this start menu item can be found here:

HKEY_CLASSES_ROOT\CLSID\{A8A91A66-3A7D-4424-8D24-04E180695C7A}

This dastardly key also has a 32bit relation that can be found here:

HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{A8A91A66-3A7D-4424-8D24-04E180695C7A}

As with my previous post about removing screen resolution and personalise, its just a matter of removing the users ability to see this registry key.

So below you will find the steps to take to remove this item:

  1. Take a backup of this key, you’ll thank me if you get it wrong!
  2. Browse down to HKEY_CLASSES_ROOT\CLSID\{A8A91A66-3A7D-4424-8D24-04E180695C7A}
  3. right click this key, choose permissions, click advanced then owner
  4. Select administrators from the list, then choose “Apply”.
  5. browse to the permissions tab and remove the “users” group. (you may need to remove inheritance)
  6. Click “apply”, then “ok”.
  7. Repeat step 2 to 6 on HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{A8A91A66-3A7D-4424-8D24-04E180695C7A}
  8. Tada! go grab a coffee to celebrate your domination over the windows operating system.

And that’s it, even if the user tries to view the option theres a blank place on the start menu where devices and printers should be. Check back next week and I’ll show you how to replace this shell icon with PowerPrint from RES software.

PS: You can also quite easily script this, Remko provided me with a great script that I’ve modified below to suit this purpose.

Read more…

Using my Citrix Edgesight Powershell module with Active directory OU’s.

January 27, 2012 Leave a comment

I received a request on twitter late last night and it was an interesting one. The person in question wanted to use my current edgesight module to import users from active directory into the static Citrix Edgesight groups, but instead of group membership in Active Directory, they wanted to use Active Directory Organisational Units.

All the information on how to use the module is included in the previous post, so I wont re-invent the wheel. Have a read of the previous post for any caveats or pre-emptive misunderstandings.

Below are two code snippets to use OU membership with either the Quest or Microsoft cmdlets for active directory, just modify the OU Path below, I’ve tried to include a long example to ensure there’s no confusion.

 Quest Active directory Snap-in:

#Quest Active directory module
import-module "C:\citrix.edgesight.cmdlets.psm1"
add-pssnapin Quest.ActiveRoles.ADManagement
$ADOU='domain.domain.com/Country/Users/advanced/Helpdesk'
$esgroupid=20

#clear the group before import
clear-esgroupmembers -groupid $esgroupid

#get users from group, then import them into edgesight
foreach ($user in get-QADUser -SearchRoot $ADOU -SizeLimit 0){
    $prid = get-ESUserPrid $user.logonname
    if ($prid -NE $null){
    Add-ESGroupMember -groupid $ESgroupid -prid $prid
    }
}#end For

Microsoft Active directory module:

 

#Microsoft active directory module
import-module "C:\citrix.edgesight.cmdlets.psm1"
import-module activedirectory
$ADOU="OU=helpdesk,OU=advanced,OU=Users,OU=Country,DC=domain,DC=domain,DC=com"
$esgroupid=20

#clear the group before import
clear-esgroupmembers -groupid $esgroupid

#get users from group, then import them into edgesight
foreach ($user in get-ADUser -filter * -searchbase $ADOU){
    $prid = get-ESUserPrid $user.samaccountname
    if ($prid -NE $null){
        Add-ESGroupMember -groupid $ESgroupid -prid $prid
    }
}#end For
Follow

Get every new post delivered to your Inbox.

Join 2,587 other followers