Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

msexchextensioncustomattribute 4

$
0
0
Hey Guys, Anyone know how to populate msexchextensioncustomattribute 4 with each users primary email address for everyone in the address book. Thanks in advance. Graham

nike air max Chaussure Air Max

$
0
0

Added directly in a very manufacturing technique of deodorization ability strongest activated carbon, so can guarantee these comfortable shoes don't smelly, and efficient for quite some time. 3, the durability of POLIYOU make inoculants POLIYOU product of antibacterial agent took the kind of chemical combination in POLIYOU sponge and fiber surface, the antibacterial effect of insoluble in water and general dry cleaning solvent, wet resistance of heat-resistant, durable antibacterial effect. By applying our country textile department issued FJ - 54 p - 85 standard polyester detection method, bacteriostatic rate after washing ten times remain extremely high water ??. 4, POLIYOU compressibility and high elastic resistance of materials. POLIYOU materials for the primary elements for flexibility and strength are fantastic polyurethane, and compression resistance and abrasion resistance have grown to be good, tricky to balanced with other materials. POLIYOU high elasticity from itself open modified PU material, flexible than closed or half open material, as well as maintain its original shape, elastic never tired, permit your feet while walking, running or meaning many to become more properly protected. [Upper - shoe] role: to choose from support, protection, air permeability, and make sure the feet they fit around the right place. Leather, Leather is comfortable, comfortable, by consumers often known as valuable. It's stretching deliver an easy deformation. Leather (Leather) - Leather will probably flexibility belonging to the characteristics of comfort, fit, surface tension, bioactive, permeability is best; It's true it will a great deal of materials used leather shoe money it's very classic and collection value. Excellent material for long periods, appears to with their leather played with making shoes, having said that the characteristic of leather also cause its inherent defects of your shoe, good crease flexible extension generates it simple to deformation, fracture; In the mean time leather uppers easy worn and nike air max scratched; Leather good aeration biological characteristics of deep breathing damp and water environment facing the severe test, flexible leather uppers alone while in the high strength limited ankle, foot side key vulnerable parts for example , strong support of protection and form. Then again, in relation to technology, especially more NIKE materials, leather materials in these aspects as processing molding often demanding and complex, to be sure the process costs rise, or, use cortex is will not be completely take out the suture, in high-tech developed now, it looks like, suture is growing is the defect of history. Simple said, cortex from inside the nature of your hard and soft aspects for shoe is contradictory. Choose good leather, among the characteristics of leather material design shoes structure happens to be the premise and key while using whole shoe body design, beginners, giving full play on the way to the advantages of leather that good, concurrently , ?? scale improvement, strengthen the leather uppers supportive and reliable. Quite a lot of this past classic shoe into the wide variety of cortical is searching for a rigorous testing and many additional actual to square high quality of that extreme, do sports and luxury

request for Script for enable-mailbox with conditional SMTP

$
0
0

Hi Tech gurus,

I have scenario, wherein if I have a user Firstname.Lastname@company.com in org and another same Firstname.Lastname comes in.. instead of Firstname.Lastname2@company.com. I would like to use middle name initial, and make it Firstname.FirstletterInitial.Lastname@company.com. In case no middle name is mentioned it should pick Firstname.Lastname@company.com

Also, rest of the EmailAddressPolicyEnabled should be true and applicable.

I would like to enable it for existing AD object under enable-mailbox.

Can you please guide me for the same.

So far I built :

$sam = $_.samAccount

$givenName = $_.GivenName

$Initial = $_.Initials

$LastName = $_.LastName

$EmailAddress = ($givenName+$Initial+$LastName+"@company.com")

Enable-Mailbox -Identity $sam -PrimarySmtpAddress $EmailAddress -Database DB2 | Set-Mailbox -IgnoreDefaultScope -EmailAddressPolicyEnabled $true -Identity $sam

Exchange Auto check

$
0
0

$Header = "<style>table {font-size: 10pt; font-family: calibri;}

  body {background-color:black;}

  table {align: cernter; border-width: 1px;border-style: solid; border-color: black; border-collapse: collapse;}

  th {font-size:1em; border-width: 1px;padding: 2px; border-style: solid; border-color: white; background-color: #FFCCCC}

  td {font-size:0.8em; border-width: 1px;padding: 2px; border-style: solid; border-color: white; background-color: PaleGoldenRod}

</style>"

$Getdate = Get-date

 

$TotalGB = @{Name="Capacity(GB)";expression={[math]::round(($_.Capacity/ 1073741824),2)}}

$FreeGB = @{Name="FreeSpace(GB)";expression={[math]::round(($_.FreeSpace / 1073741824),2)}}

$FreePerc = @{Name="Free(%)";expression={[math]::round(((($_.FreeSpace / 1073741824)/($_.Capacity / 1073741824)) * 100),0)}}

 

function get-mountpoints {

$volumes = Get-WmiObject -computer $server win32_volume | Where-object {$_.DriveLetter -eq $null}

$volumes | Select SystemName, Label, $TotalGB, $FreeGB, $FreePerc

}

 

$servers = (Get-Content .\servers.txt)

$target = @()

foreach ($server in $servers){

$target += get-mountpoints

$file = $target |Export-csv -NoTypeInformation -Force -Path 'C:\folder\MountPointSpace-Report.csv'

 

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010

Get-MailboxDatabase | Get-MailboxDatabaseCopyStatus |select Name,Status,CopyQueueLength,ReplayQueueLength,LastInspectedLogTime| Export-csv "C:\folder\DatabasesIndexStatus.csv"

 

 

Get-Queue -server <server name>|select Identity,DeliveryType,Status,MessageCount,NextHopDOmain| Export-csv "C:\folder\Queue_status_servername1.csv"

 

Get-queue -server <Server name>|select Identity,DeliveryType,Status,MessageCount,NextHopDOmain| Export-csv "C:\folder\Queue_status_Servername2.csv"

 

Get-queue -server <server name>|select Identity,DeliveryType,Status,MessageCount,NextHopDOmain| Export-csv "C:\folder\Queue_status_servername3.csv"

 

 

$ExchangeInfo = Import-Csv -Path C:\folder\MountPointSpace-Report.csv| ConvertTo-Html -Head $Header

$ExchangeInfo2 = Import-Csv -Path C:\folder\DatabasesIndexStatus.csv| ConvertTo-Html -Head $Header

$ExchangeInfo3 = Import-Csv -Path C:\folder\Queue_status_servername1.csv| ConvertTo-Html -Head $Header

$ExchangeInfo4 = Import-Csv -Path C:\folder\Queue_status_servername2.csv| ConvertTo-Html -Head $Header

$ExchangeInfo5 = Import-Csv -Path C:\folder\Queue_status_servername3.csv| ConvertTo-Html -Head $Header

 

$mailBody = 

@"

Hello Messaging Admins,</br>

</br>

<p>Here are the <b>Exchange Auto Check</b> info. Please have a look.</p></br>

</br>

$ExchangeInfo

</br>

$ExchangeInfo2

</br>

$ExchangeInfo3

</br>

$ExchangeInfo4

</br>

$ExchangeInfo5

</br>

 

Best</br>

Gautam Verma

"@

 

Send-MailMessage -Body $mailBody -BodyAsHtml `

-From "Gautam.Verma@domain.com" -To "admin@domain.com" `

-Subject "Test Exchange $Getdate"`

-SmtpServer "smtp.domain.com"

Copy MemberOf from one user and mirror all other users to existing users

$
0
0

$CopyFromUser = Get-ADUser gver359 -prop MemberOf

$CopyToUser = get-content C:\folder\users.txt

$date = Get-date

 

 

"Processing started (on " + $date + ") : " |Out-File C:\folder\logs.txt -append

"-----------------------------------------------" |Out-File C:\folder\logs.txt -append

Get-ADPrincipalGroupMembership $CopyFromUser | select name |Out-File C:\folder\logs.txt -append

 

$CopyFromUser.MemberOf | Where{$CopyToUser.MemberOf -notcontains $_} |  Add-ADGroupMember -Member $CopyToUser

request to review the script and guidance further

$
0
0

I would like to find if firstname and last name exist in org, in case yes, it should use middle name in SMTP policy and in case no, then use simple SMTP policy :

Import-Module ActiveDirectory -ErrorAction Stop
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
#Create Mailbox

$OU = "OU=Sync,OU=Users,OU=Corp,DC=domain,DC=com"
$sam = Get-aduser -filter * -Properties * | select CN
$FirstName = Get-aduser -filter * -Properties * | select GivenName
$LastName = Get-user -filter * -Properties *| select SN
$Middle = Get-Aduser -filter * -Properties * | select Initials
$EmailAddWithMiddle = ($FirstName+"."+$Middle+"."+$LastName+"@domain.com")
$EmailAddWithoutMiddle = ($FirstName+"."+$LastName+"@domain.com")
If ($Middle -eq "")
{
Get-User -ResultSize "Unlimited" -OrganizationalUnit $OU | Where-Object {$_.RecipientType -eq "User"} | Enable-Mailbox -Database DB2 | Set-Mailbox -EmailAddressPolicyEnabled $true
}
Else
{
Get-User -ResultSize "Unlimited" -OrganizationalUnit $OU | Where-Object {$_.RecipientType -eq "User"} | Enable-Mailbox -PrimarySmtpAddress $EmailAddWithMiddle -Database DB2
}

How to copy files based on list of array?

$
0
0

Hi Guys,

I need to copy files from sourceA to either destA or destB based on if the filename matches the array of string in an external file or not.

For example:

I have 3 files in SourceA:

CATisNice.txt
DogisPretty.txt
HorseisFast.txt

I have following list of strings in a text file, lets say listA.txt:

Nice
Pretty

Now I need script to check each file and see if its name matches  any string in the  listA.txt

If matches, copy the file to both destA and destB

If not copy only to destB

In the above example, I should see CATisNice.txt, DogisPretty.txt in destA and CATisNice.txt,DogisPretty.txt, HorseisFast.txt in destB

I know only very very basic of powershell and not sure how to loop through the array of value for each object.

Thank you very much for your time and help

Let me know if smething is no clear

 

 

 

 

Need assistance on Start-process

$
0
0

I'm using start-process to add appv package. Normal procedure would be using add-appvclientpackage that returns packageid, versionid etc but if add application using start-process i am not getting return code of add-appvclientpackage.

Direct code: $a = add-appvclientpackage C:\applicationname.appv

write-host $a

Result for above command:

PackageId            : 

VersionId            : 

Name                 : 

Version              : 0.0.0.1

Path                 : 

IsPublishedToUser    : False

UserPending          : False

IsPublishedGlobally  : False

GlobalPending        : False

InUse                : False

InUseByCurrentUser   : False

PackageSize          : 

PercentLoaded        : 100

IsLoading            : False

HasAssetIntelligence : False

 But when i add package using below code, i am not getting above return code of appv client.

$a = Start-Process powershell -Credential DOmain\username -ArgumentList '-noprofile -command &{$result = Add-AppvClientPackage C:\applicationname.appv;$result}' `

 -WorkingDirectory C:\windows\System32\WindowsPowerShell\v1.0 -PassThru

 

Can someone help me how can i get return code of add-appvclientpackage using start-process.

 


Creating a PSUserAgent for Microsoft Office Outlook

$
0
0

So, I am currently trying to retrieve information via "Invoke-WebRequest" from Office 365's autodiscover (https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml). My code currently returns the "600: Invalid Request" error code, which for usual sys administration you'd just go, yep, that means Office 365 autodiscover is working, however I want to retrieve the XML information, and use it to create a .prf file, to then create a mail profile. There seems to be useful bits and pieces across the web for doing this kind of thing via C#, but PowerShell is my choice of tool!

My Current code is:

$uri ="https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml"[xml]$AutodiscoverReq =Invoke-WebRequest $uri -Method post -ContentType"text/xml"-Credential $cred 
$AutodiscoverReq.InnerXML

By monitoring traffic, I have found that I also need to use the User Agent for Microsoft Office Outlook, which looks something like this:

MicrosoftOffice/15.0(Windows NT 6.2;MicrosoftOutlook15.0.4693;Pro)

From my research, I have found that PowerShell current has in-built User Agents, I have included the commands I have run and the results below:

Command:

[Microsoft.PowerShell.Commands.PSUserAgent].GetProperties()|Select-ObjectName,@{n='UserAgent';e={[Microsoft.PowerShell.Commands.PSUserAgent]::$($_.Name)}}

Result:

NameUserAgent-------------InternetExplorerMozilla/5.0(compatible; MSIE 9.0;Windows NT;Windows NT 10.0; en-GB)FireFoxMozilla/5.0(Windows NT;Windows NT 10.0; en-GB)Gecko/20100401Firefox/4.0ChromeMozilla/5.0(Windows NT;Windows NT 10.0; en-GB)AppleWebKit/534.6(KHTML, like Gecko)Chrome/7.0.500.0Safari/534.6OperaOpera/9.70(Windows NT;Windows NT 10.0; en-GB)Presto/2.2.1SafariMozilla/5.0(Windows NT;Windows NT 10.0; en-GB)AppleWebKit/533.16(KHTML, like Gecko)Version/5.0Safari/533.16

Command:

[Microsoft.PowerShell.Commands.PSUserAgent].GetProperties()

Result:

MemberType:PropertyName:InternetExplorerDeclaringType:Microsoft.PowerShell.Commands.PSUserAgentReflectedType:Microsoft.PowerShell.Commands.PSUserAgentMetadataToken:385876515Module:Microsoft.PowerShell.Commands.Utility.dllPropertyType:System.StringAttributes:NoneCanRead:TrueCanWrite:FalseGetMethod:System.String get_InternetExplorer()SetMethod:IsSpecialName:FalseCustomAttributes:{}MemberType:PropertyName:FireFoxDeclaringType:Microsoft.PowerShell.Commands.PSUserAgentReflectedType:Microsoft.PowerShell.Commands.PSUserAgentMetadataToken:385876516Module:Microsoft.PowerShell.Commands.Utility.dllPropertyType:System.StringAttributes:NoneCanRead:TrueCanWrite:FalseGetMethod:System.String get_FireFox()SetMethod:IsSpecialName:FalseCustomAttributes:{}MemberType:PropertyName:ChromeDeclaringType:Microsoft.PowerShell.Commands.PSUserAgentReflectedType:Microsoft.PowerShell.Commands.PSUserAgentMetadataToken:385876517Module:Microsoft.PowerShell.Commands.Utility.dllPropertyType:System.StringAttributes:NoneCanRead:TrueCanWrite:FalseGetMethod:System.String get_Chrome()SetMethod:IsSpecialName:FalseCustomAttributes:{}MemberType:PropertyName:OperaDeclaringType:Microsoft.PowerShell.Commands.PSUserAgentReflectedType:Microsoft.PowerShell.Commands.PSUserAgentMetadataToken:385876518Module:Microsoft.PowerShell.Commands.Utility.dllPropertyType:System.StringAttributes:NoneCanRead:TrueCanWrite:FalseGetMethod:System.String get_Opera()SetMethod:IsSpecialName:FalseCustomAttributes:{}MemberType:PropertyName:SafariDeclaringType:Microsoft.PowerShell.Commands.PSUserAgentReflectedType:Microsoft.PowerShell.Commands.PSUserAgentMetadataToken:385876519Module:Microsoft.PowerShell.Commands.Utility.dllPropertyType:System.StringAttributes:NoneCanRead:TrueCanWrite:FalseGetMethod:System.String get_Safari()SetMethod:IsSpecialName:FalseCustomAttributes:{}

My Question is, how can I create a PSUserAgent object myself for outlook? And use it to retrieve the information I need?

If anyone can see any issues with what I'm attempting or has any advice, that would be greatly appreciated.

wait for a windows to appear ?

$
0
0

A small vendor gave us some software to install and they did not provide any silent way to install it.  -s, -q, /q, -q, -silent etc... none of those are available.   So I need to automate the installation.  I did this using PowerShell but I need to make my code smarter.   How do I "wait" for a window title to appear?

$wshell = New-Object -ComObject wscript.shell;

$wshell.AppActivate('My Window Title Here')

I use Start-Process to call the .EXE in question and yes I can use sleep 'x' but that is crude.  I want to have my code loop until this window title appears.

 

 

 

 

force window to be active and on top?

$
0
0

I call an .EXE, I then disable the mouse and keyboard.   The .EXE that is called throws up a dialog window that I try to activate.    This is running from the RUN key in the registry.

$wshell=New-Object-ComObjectwscript.shell;
$wshell.AppActivate('Alaris® desktop configuration tool')

The issue I'm seeing is although the dialog window does appear my script never clicks the "Next" button since for some reason the window does not have focus.    But, if I run this manually it all works.  Being called from the RUN key seems to be the issue that causes the focus problem.

Is there another command that will force a window to be on top and the active window?

 

test-connection fails because multiple IP's registered in DNS for computer

$
0
0

Hi

Just started to learn PowerShell, created my first practical script which pings a list of desktops and laptops and if they are reachable exports out the remaining c: drive free space into a .csv file.

All is well until I realised a lot of laptops are failing to return any data because they are not reachable using test-connection even though I know the laptops are plugged into the network.

This seems to be because there is more than one IP address registered in DNS for some laptops. The second IP is from the a recent VPN connection the user initiated when they were working from home which remains registered in DNS for 7 days. If I do a NSLOOKUP on the hostname I can see both IP addresses, the live LAN IP as well as the previous VPN IP. It seems when test-connection pings the machine it sometimes returns the VPN IP which times out resulting in a failed ping.

Question is, is there a way if test-connection fails to check for a secondary IP registered in DNS and then ping that giving me a reachable device and a more complete disk space report?

 

Many Thanks Big Smile

Print list of (mostly) empty folders - script optimization, elegance

$
0
0

I pieced the following together to "scan" a folder structure and output line-terminated paths of folders that contain no files, directly or indirectly. The script expects an argument of the top-level or root folder to check. It took a few minutes to run with a network share as target (contains 1,982 folders and 13,970 files). If you have tips for optimizing or a more elegant / different approach to suggest, I'm interested!

param([string]$PathRoot="");
[System.Collections.ArrayList]$emptyDirs=Get-ChildItem$PathRoot-Recurse|Where-Object {$_.PSIsContainer};
$emptyDirs.Insert(0, (Get-Item$PathRoot));
$dirsWithFiles=Get-ChildItem$PathRoot-Recurse|Where-Object {$_.PSIsContainer -and$_.GetFiles().Count}

for ($i=0; $i-lt$dirsWithFiles.length; $i++) {
    for ($j=0; $j-lt$emptyDirs.Count; $j++) {
        if ($dirsWithFiles[$i].FullName -like ("{0}*"-f$emptyDirs[$j].FullName)){
            $emptyDirs.RemoveAt($j);
            $j--;
        }
    }
}

$emptyDirs|ForEach-Object {$_.FullName};

 

 

 

using the -AsHashTable and -AsString parameters with Group-Object cmdlet

$
0
0

Hello 

I have seen a few examples (cannot lay my hands on one now unfortunately) where people has used -AsHashTable and -AsString with the Group-Object cmdlet

can someone place explain a bit more about these two parameters e.g. do they always need to be used together or can they be used separately

can anyone give me some examples of when and where these two parameters would come in handy e.g. when and why to use

 

Thanks

AAnotherUser__ 

 

Compressing&Decompressing Sites Using Powershell Command/Script.

$
0
0

What powershell command/script would be needed to tell a browser to send a note on the fly to compress a requested site by eliminating unnecessary bits in order to reduce the site's size to one third and decompress the site after reaching the browser that called it?


How to best handle "No matches found"

$
0
0

Hi All,
Am new to PowerShell and still learning my way about.

I am running the following snippet of code ...

$event= Get-EventLog -LogName Security -ComputerName [DCServer] -InstanceId 4740 -Newest 1 |
   Select TimeGenerated,ReplacementStrings,"Account name","Account Domain","Caller Computer Name" |
   % {
     New-Object PSObject -Property @{
      "Account name" = $_.ReplacementStrings[-7]
      "Account Domain" = $_.ReplacementStrings[5]
      "Caller Computer Name" = $_.ReplacementStrings[1]
      Date = $_.TimeGenerated
    }
   }

My question is how should I best handle this when it returns nothing?

Example:

Get-EventLog : No matches found
At line:1 char:1
+ Get-EventLog -LogName Security -ComputerName [DCServer] -InstanceId 4740  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [Get-EventLog], ArgumentException
    + FullyQualifiedErrorId : GetEventLogNoEntriesFound,Microsoft.PowerShell.Commands.GetEventLogCommand

Thanks in advance.

Cheers, Cameron

VB message boxes and outputs?

$
0
0

Normal 0 false false false EN-AU X-NONE X-NONEHow do I write a powershell script which brings up a VB Script message box, with Yes, No and Cancel buttons.  Executing a different action for each button press?

Show message box (form) while script is running

$
0
0

Hello,

I´m working on a installtion script which should install a .msi package and while the installation is running the user should see a message box (form) "installation running".

My problem is to get the message box (form). If I use "$Form.ShowDialog()" the script will stop as long as the form is open. And if I use "$form.Show()" I cann´t see the label text because the label is transparent.

Here is my script:

    Add-Type -AssemblyName System.Windows.Forms

    $Form = New-Object system.Windows.Forms.Form
    $Form.Text = "Installation"
    $Form.AutoSize = $True
    $Form.AutoSizeMode = "GrowAndShrink"
    $Font = New-Object System.Drawing.Font("Times New Roman",18 [System.Drawing.FontStyle]::Italic)
   
    $Form.Font = $Font
    $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle

    $handler_form_Load = { $form.Location = New-Object System.Drawing.Point(600, 200) }
    $form.add_Load($handler_form_Load)
 
    $Label = New-Object System.Windows.Forms.Label
    $Label.Text = "Installation running...."
    $Label.AutoSize = $True

    $Form.Controls.Add($Label)

    # $Form.ShowDialog() | out-null
    $form.Show() | out-null

    #give the form focus
    $form.Focus() | out-null

    # Here the installation should start

    $form.Close()

 

Regards, Martin Fischer

 

Report of members of local Administrators group

$
0
0

I found this here: (http://powershell.com/cs/media/p/376.aspx)

  1. cls 
  2. $ErrorActionPreference="SilentlyContinue" 
  3. Get-Content (ENTER PATH TO YOUR INPUT FILE HERE) | foreach
  4.     [ADSI]"WinNT://$_/administrator" | select ` 
  5.     $(Name="Account";Expression={($_.PSBase).Path}}, ` 
  6.     $(Name="Password Set";Expression={(Get-Date).AddSeconds(-($_.PasswordAge)[0])}}; ` 
  7.     $(Name="PasswordAge (Days)";Expression={[int]((4-.PasswordAge)[0]/86400) }}, ` 
  8.     $(Name="Last Logon";Expression={$_.LastLogin}}, ` 
  9.     $(Name="Days Since Last Logn";Expression={ ` 
  10.     (New-TimeSpan-start ($_.LastLogin[0]) -end (Get-Date)).days}}} ` 
  11. | Export-csv (ENTER PATH TO YOUR OUTPUT FILE HERE) -notypeinformation 

The $'s in the SELECT statement need to be @'s... That corrected, I'm trying to get to run so I can report on the local administor account - by SID.  Our local admin accounts are renamed depending on department.   Also to run against all (local account) members of the builtin administrators group.

I've been able to dump the members, but am having trouble putting the two halves together.  

 

Workstation Componet Validation

$
0
0

Hi all

I am writing a script to check a few things on a Virtual machine to ensure that it meets a certain baseline(Services running, Hotfixes ...etc).   I am running into a problem with getting the display adapter in the report.  I can pull the information and display it separately, however I would like it in the same report to make it a bit easier for our deployment team.  Below is the script,  I am sure that there are a few things that can be written a little better as well.   Any and all input is appreciated

 

#################


$recipients = "me@you.com"
$fromEmail = "Validcheck@you.com"
$SMTPserver = "Mailserver"
$currentTime = Get-Date -Format "yyyy-MM-dd | hh:mm:ss tt"
$logTime = Get-Date -Format "yyyy-MM-dd_hh-mm"
$LogFile = "C:\Support\scripts\US-VDICheck-Report-$logTime.csv"
$Bodymsg = $Bodymsg = gc -Path c:\support\scripts\vdimigrationmsg.txt | Out-string


add-pssnapin Citrix*
add-pssnapin Admin*
#$vm=$()
#$Status=$()
#$collection = $()

# Set variable for computername
$vm = "MyMachine"

 

foreach ($vm in $vms)
{
# ping the machine to see if it is up
 if (Test-Connection $vm -Count 1 -ea 0 -Quiet)   
   { $Pingstatus = "Up"     


# Get the video adapters on the system
$displayAdapters = get-wmiobject win32_videocontroller –comp $vm | Select Description, DriverVersion


# Check services
  $icasvc = get-service -Name "Porticaservice" -computername $vm
  $icaDesktopsvc = get-service -name "Brokeragent" -computername $vm
  $DskWindowMgrsvc = get-service -name "UxSms" -computername $vm
  $vmviewagent = get-service -name "WSNM" -computername $vm
  $rgsAgent = get-service -name "rgsender" -computername $vm
  $GoToMYPC = get-service -name GoToMyPC -computernam $vm

# Checks to see if the Citrix Hotfixes are installed
 # ICAWS760WX64010
  $Registry_Location010 = 'Software\Wow6432node\Citrix\XenDesktop\Hotfixes\{516E229D-D5EE-AE8A-F3AF-9EB09D0A6B46}'   
  $Remote_Registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $VM)   
  $hotfix10 = $Remote_Registry010.OpenSubKey($Registry_Location010)
  $ctxhfx010 = $hotfix10.GetValue('HotfixName')
 # ICAWS760WX64014
  $Registry_Location014 = 'Software\Wow6432node\Citrix\XenDesktop\Hotfixes\{54200A3F-5C4F-EF2B-FA7C-0B06BD5E5815}'   
  $Remote_Registry014 = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $VM)   
  $hotfix014 = $Remote_Registry014.OpenSubKey($Registry_Location014)
  $ctxhfx014 = $hotfix014.GetValue('HotfixName')
 #ICAWS760WX64024
  $Registry_Location024 = 'Software\Wow6432node\Citrix\XenDesktop\Hotfixes\{62B4CE3B-687D-0D8B-0B4F-18FF3F5CE90E}'   
  $Remote_Registry024 = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $VM)   
  $hotfix024 = $Remote_Registry024.OpenSubKey($Registry_Location024)
  $ctxhfx024 = $hotfix024.GetValue('HotfixName')
 #ICAWS760WX64011
  $Registry_Location011 = 'Software\Wow6432node\Citrix\XenDesktop\Hotfixes\{835CAFEE-2BD5-5189-991F-A2F50E57B9AD}'   
  $Remote_Registry011 = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $VM)   
  $hotfix011 = $Remote_Registry011.OpenSubKey($Registry_Location011)
  $ctxhfx011 = $hotfix011.GetValue('HotfixName')
 #ICAWS760WX64022
  $Registry_Location022 = 'Software\Wow6432node\Citrix\XenDesktop\Hotfixes\{8F87C292-5616-82C8-44DC-28651D014337}'   
  $Remote_Registry022 = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $VM)   
  $hotfix022 = $Remote_Registry022.OpenSubKey($Registry_Location022)
  $ctxhfx022 = $hotfix022.GetValue('HotfixName')
 #ICAWS760WX64002
  $Registry_Location002 = 'Software\Wow6432node\Citrix\XenDesktop\Hotfixes\{AB36927A-FEFA-2176-BE81-E0AFCBE71AE7}'   
  $Remote_Registry002 = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $VM)   
  $hotfix002 = $Remote_Registry002.OpenSubKey($Registry_Location002)
  $ctxhfx002 = $hotfix002.GetValue('HotfixName')
 #ICAWS760WX64005
  $Registry_Location005 = 'Software\Wow6432node\Citrix\XenDesktop\Hotfixes\{BB9345DB-52F0-76AD-0364-EB598913C8BC}'   
  $Remote_Registry005 = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $VM)   
  $hotfix005 = $Remote_Registry005.OpenSubKey($Registry_Location005)
  $ctxhfx005 = $hotfix005.GetValue('HotfixName')

# if Desktop Mger services is stopped, Set to automatic and enable it
  if ($DskWindowMgrsvc.status -eq "Running")
   { set-service -name "UxSms" -computername $vm -startupType Automatic -Status Running}
   $DskWindowMgrsvc = get-service -name "UxSms" -computername $vm 
   }
 else    { $Pingstatus = "Down"} 
 
# Gets the broker info
 $XDstatus = Get-BrokerDesktop -adminaddress pwvrfpcxd002 -MachineName ad\$vm |Select MachineName,DesktopGroupName,RegistrationState,InMaintenanceMode,AgentVersion
 
 #compiles status
 $Status= @{
  "MachineName" = $vm;
  "pingStatus" = $Pingstatus;
  "XD_DesktopGroup" = $XDStatus.DesktopGroupName;
  "XD_RegistrationState" = $XDStatus.RegistrationState;
  "XD_AgentVersion" = $XDStatus.AgentVersion
  "MaintenanceMode" = $XDStatus.InMaintenanceMode
  "Citrix ICA Service" = $icasvc.Status
  "Citrix Desktop Service"  = $icaDesktopsvc.status
  "Desktop Window Manager Session Manager" = $DskWindowMgrsvc.Status
  "ICAWS760WX64010" = $ctxhfx010
  "ICAWS760WX64014" = $ctxhfx014
  "ICAWS760WX64024" = $ctxhfx024
  "ICAWS760WX64011" = $ctxhfx011
  "ICAWS760WX64022" = $ctxhfx022
  "ICAWS760WX64002" = $ctxhfx002
  "ICAWS760WX64005" = $ctxhfx005
  "VMView Agent" = $vmviewagent.Status
  "RGS Agent" = $rgsAgent.status
  "GoToMyPC" = $GoToMYPC.status
   }
 New-Object -TypeName PSObject -Property $status -OutVariable MachineStatus | out-Null
 $collection += $machinestatus
}

#Spit out display Adapter info
$displayAdapters

# Dump the results in to csv
$collection | Select MachineName, pingStatus, XD_RegistrationState, XD_Agentversion, MaintenanceMode, "Citrix ICA Service", "Citrix Desktop Service", "Desktop Window Manager Session Manager","ICAWS760WX64002","ICAWS760WX64005","ICAWS760WX64010","ICAWS760WX64011","ICAWS760WX64014","ICAWS760WX64022","ICAWS760WX64024", "VMView Agent", "RGS Agent", "GoToMyPC", XD_DesktopGroup | Export-csv $LogFile  -NoTypeInformation
$logfile
$displayadapters | out-gridview

# mail CSV with message
send-mailmessage -from $fromEmail -to $recipients -subject "VDI Post Migration Check | $currentTime | $DDC " -Body $Bodymsg -Attachments $LogFile -SmtpServer $SMTPserver -Priority High

#####################################

Viewing all 10624 articles
Browse latest View live