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

Finding odd and even numbers

$
0
0

I have created a script that will put a collection into a html table and send it in an eamil. I would like to add an alternating color for each table row in the html table. I am building the table and each row by looping through a collection and have added $LoopCount++ count each time the loop is started. I want to use the $LoopCount++ to generate a number and based on the number being odd or even i will update the <tr "bgcolor='7FA96F'"> tag. I am not married to this method but it was the only way i could think of to get alternating colors. I am missing the logic to find out if the loopcount is an odd or even number. Any ideas would help...

FOREACH($Item in $SortedMBXProps)
 { 
  $LoopCount ++
  ## Change to color 1
  IF($LoopCount -eq "True")
   {
   $list += "<tr bgcolor='7FA96F'>"
   }
   ## Change to color 2
    ELSE
    {
    $list += "<tr bgcolor='FFFFFF'>"
    }
  $list += "<td>" + $Item.DisplayName + "</td>"
  $list += "<td>" + $Item."IssueWarningQuota(MB)" + "</td>"
  $list += "<td>" + $Item."TotalItemSize(MB)" + "</td>"
  $list += "<td>" + $Item."ProhibitSendQuota(MB)" + "</td>"
  $list += "<td>" + $Item.StorageLimitStatus + "</td>"
  $list += "<td>" + $Item.ServerName + "</td>"
  $list += "</tr>"
 }
$list += "</table></font>"

Powershell and XML protocol

$
0
0

Hello,

I'm trying to communicate with our telephone exchange with powershell via XML Slican Protocol

Interface:

  • Medium: Ethernet
  • Protocol: TCP/IP
  • Port: 5529

XML frame structure:

<?xml version="1.0" encoding="UTF-8"?><XCTIP><Module><Command><Data>...</Data></Command></Module></XCTIP>

Answer is also in XML.

I already build a working XML frame structure, which I tested with dedicated Slican tool.

Sending a packet requires also IP, login and pass.

Should I use Invoke-WebRequest or Invoke-RestMethod? Which method? How the request should look like?

Any help will be appreciated.


follow out-gridview with out-printer

$
0
0

Hi,

I have a script which pulls Active Directory user information. When I finish the script I am using "out-gridview" which presents the information perfectly on screen. What I don't understand, is how I can print that view. I want to pass the output to a named printer using...Out-Printer "namedprinter"

My code therefore ends...

$GridHTML = $Data.Values | Sort $SortBy | Select $($Fields.Split(",")) | out-gridview | out-printer "NamedPrinter"

But it still only shows on the screen and doesn't print. I naively thought piping the output again to out-printer would work.

If I leave out the "out-gridview" altogether, then I get the output but the column spacing is not correct. Any help greatly appreciated.


Inconsistent getType() behavior?

$
0
0

Hi

I'm pretty happy with the newer versions of Powershell that let you return values without assigning them to a variable beforehand, but I'm having an issue regarding returning the proper object types.

According to GetProcess | gm, ProcessName is a string

TypeName: System.Diagnostics.Process
Name                       MemberType     Definition
----                       ----------     ----------

ProcessName                Property       string ProcessName {get;}

The following command, however, returns it as Object[] instead of an expected String[].

(Get-Process).ProcessName.getType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

Trying to forecfully cast it as a String[] using the following method doesn't work either

[string[]](Get-Process).ProcessName.GetType()
System.Object[]
This only way to make it function properly is to do the following script...

$c=[string[]](Get-Process).ProcessName $c.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String[]                                 System.Array

... Which properly returns the result as String[]

I find this to be pretty inconsistent. From where I'm standing, in this latest Powershell 5, all of these should return String[], or at least the second example should, since the third one does. Why is that?

I am using PowerShell Major 5 Build 10240 Revision 16384

Website Automation (Error with: Document.documentElement.getElementsByClassName)

$
0
0

I am at the last phase of my automation with creating accounts in a file storage system online. 

I am trying to grab the class and not the type. I can call the type 'input' but it takes forever. I would like to call the 'control' class. Then input the value for firstName. 

Here is a snippet I am using to find it, it is returning NULL. I am guessing due to it finding the first control class. Any advice would be helpful!

$CUserFirst = $ie.Document.Document.documentElement.getElementsByClassName('controls') | Where-Object {$_.name -eq "firstName"}
$CUserFirst.value = $UsersFirstName


Read text file and send email with some extras

$
0
0

Hi,

I have a scenario where an application writes a nightly log to a file with a non desired date and time format.

It will always write to the log file the following line: "10/15/15 13:40:11 Log processing ended normally."

Is there any way I can create a powershell to read the text file that has a date and time entry in this format: 10/15/15 13:40:11 and convert it to October 15, 2015 1:40:11 PM? But also adding a fixed text to it [Log has completed successfully at]? The end result should send an email out with the body of the email say : "Log has completed successfully atOctober 15, 2015 1:40:11 PM"  


Z

Setup Wallpaper for all user in ps

$
0
0

I setup it manually on local machine, not on domain by using gpedit.msc, and it works ok

Can I use Set-GPRegistryValue to do it? I tried it but not working.

Set-GPRegistryValue -Key "HKCU\Control Panel\Desktop\" -ValueName "Wallpaper" -Type String -Value "C:\Windows\Web\Wallpaper\Windows\Wallpaper.jpg"

CSV file

$
0
0

Trying to write a script that reads a CSV file that only has 2 columns.  The Columns are Alias and AID.

I read the csv file with this line... $Template = import-csv c:\ReportProject\test.csv

There are 20 lines under each column.  Some lines are blank under 1 column but have data in another.

I then cycle through the CSV file like this

foreach ($Compaire in $Template.AID){write-host $Compaire}

however when $Compaire has nothing in it I want it to then = $Template.Alias So this is what I wrote

$Template = import-csv C:\ReportProject\test.csv
foreach ($compaire in $Template.AID)
    {
     if ($compaire -eq ""){write-host $template.Alias}
     else {write-host $Compaire}
     }

Any help would be appreciated.

Understanding $()

$
0
0

Hi,
I have a cmd like this:

a - Write-Host "Return $myVar.count Objects" - The output of this cmd returns:

Return System.__ComObject System.__ComObject System.__ComObject System.__ComObject System.__ComObject System.__ComObject System.__ComObject System.__ComObject System.__ComObject
ystem.__ComObject System.__ComObject System.__ComObject ... Objects

Now, the gm for "$myVar.count | gm" returns an int32 object type... To test this further I assigned it to a new var like this

$myint=$myVar.count

Then ran:

b - write-host "Return $myint Objects" - This cmd returns: "Return 60 Objects""

Not sure why this happens, $myint variable gm still returns Int32 object type, but is able to display the number correctly inside "", why $myVar.count doesn`t?

Did a little more digging and found out some possible solutions to this behavior, for example:

c - write-host "Return"$myVar.count"Objects" - returns: "Return 60 Objects"
d - write-host "Return $($myVar.count) Objects" - returns: "Return 60 Objects"


Questions:

1 - Why, when using $myVar.count, it returns what appears to be the COM objects associated with the count property (example "a"), but in example "b" it doesn`t?
2 - Why in the example (c), PS adds spaces between the 2 strings ("Return" and "Objects") in the output although I didin`t add those spaces when doing - "Return"$myVar.count"Objects"?
3 - What is the meaning of the $(somecode) in example d?

Thank you.


Join remote computer on a DIFFERENT NETWORK to my Domain

$
0
0
My company is in the process of acquiring a bunch of other businesses, and in doing so will need to add each of their existing computers to our domain and remove them from their current domain. My question is, can we do this remotely using Powershell's psession or psexec in some way without having to physically walk over to each of these workstations(they are in different states all around the US)? They are not on the same network or domain, so i'm not sure what options we have for accessing them remotely. Any possible suggestions would be greatly appreciated, thanks.

The WinRM service is not listening for WS-Management requests. Event ID 10149

$
0
0

Dears,

One -domain joined- server has Windows Remote Management not working even after running the command WINRM QUICKCONFIG and Enable-PSRemoting many times successfully.. I still can't connect to this server using WMI commands.

I checked the event log and found Event ID 10149 The WinRM service is not listening for WS-Management requests.

  - Windows Firewall is turned off and network traffic is opened between my client and all servers.

  - Other servers has WMI working fine and I can manage them.

  - The server is batched with last updates.

  - OS : Windows Server 2012 R2 Datacenter

  - Server role is Hyper-V host

Please help what can we do to fix this issue..

Thanks,

A Seyam

Check for O365 distribution group existance and replacing members...

$
0
0

Hi,

I'm in the process of learning PS and I have tried with some help to put together a script which copies selected O365 security groups to mail-enabled security groups with the same members.  However I have two problems.

1. Check if group exists:

 $TargetGroup = Get-DistributionGroup -Identity $TargetCommonName -ea 0

This is supposed to check if this mail-enabled security group exists or not.  However it does not work.  What is the correct and bulletproof way to check the existance of a group and in that case, fetch the group object?

2.  Ensure that the target group's members are exactly the same as those of the source group. 

        $TargetGroupMembers = Get-DistributionGroupMember -Identity $TargetGroup
        $TargetGroupMembers | % { Remove-DistributionGroupMember -Identity $TargetGroup -Member $_.EmailAddress }
        $SourceGroupMembers | foreach { Add-DistributionGroupMember -Identity $TargetGroup -Member $_.EmailAddress }

I try to fetch all existing target group members, delete them and then add all members from the source group.  However I getb the following error message:

PS C:\Users\dev\Desktop> E:\ListGroups.ps1
DistributionGroup Servicepersonalet already exists!  Now deleting and re-adding members...
Cannot process argument transformation on parameter 'Identity'. Cannot convert value "ServicepersonalPers" to type "Microsoft.Exchange.Configuration.Tasks.DistributionGroupMemberIdParameter". Error: "Cannot convert hashtable to an object of the following type: Microsoft.Exchange.Configuration.Tasks.DistributionGroupMemberIdParameter. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section."  + CategoryInfo          : InvalidData: (:) [Get-DistributionGroupMember],   ParameterBindin...mationException    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-DistributionGroupMember  + PSComputerName        : outlook.office365.com

Here is a portion of the script:

  if ($SourceNameData -ne "") {
    $SourceGroupMembers = Get-MsolGroupMember -GroupObjectId $SourceObjectID
    $AtPos = $SourceNameData.indexof("@")
    $TargetAliasName = $SourceNameData.substring(0,$AtPos)
    $TargetCommonName = $TargetAliasName.substring(0,1).ToUpper()+$TargetAliasName.substring(1).ToLower()
    $TargetDispName = "EMailGroup $TargetCommonName"
    #Write-Host $SourceDescr $SourceDispName $SourceCommonName $SourceNameData
    $TargetGroup = Get-DistributionGroup -Identity $TargetCommonName -ea 0
    if ($TargetGroup) {
      Write-Host "DistributionGroup $TargetCommonName already exists!  Now deleting and re-adding members..."
      if ($DoCreate -eq $TRUE) {
        $TargetGroupMembers = Get-DistributionGroupMember -Identity $TargetGroup
        $TargetGroupMembers | % { Remove-DistributionGroupMember -Identity $TargetGroup -Member $_.EmailAddress }
        $SourceGroupMembers | foreach { Add-DistributionGroupMember -Identity $TargetGroup -Member $_.EmailAddress }
      }
    }
    else
    {
      Write-Host "DistributionGroup $TargetCommonName does not exist, now creating and populating it...."
      if ($DoCreate -eq $TRUE) {
        New-DistributionGroup -Name $TargetCommonName -DisplayName $TargetDispName -Alias $TargetAliasName -Notes $SourceDescr -Type "Security" -PrimarySmtpAddress $SourceNameData
        $SourceGroupMembers | foreach { Add-DistributionGroupMember -Identity $TargetCommonName -Member $_.EmailAddress }
      }
    }
  }
  if ($ListMembers -eq $TRUE) {
    foreach ($Member in $SourceGroupMembers) {
      Write-Host $Member.DisplayName
    }
  } 

Thanks a lot for help on these two issues

regards Tor

powershell windows forms ctrl break

$
0
0

Hi

I have a powershell winforms code to get the installed applications from remote computers.
Like if I say ...I executed it on 100 boxes and it sometimes hangs. I want to use ctrl c or ctrl break

to break that operation.

Is there any event handler I can use...if the form hangs or takes long time and I want to use ctrl c or break to stop that operation.

Any hint would be appreciated.

Thanks

neo

Exchange Script to empty an online archive (drop office 365 archive)

$
0
0

Dear community,

I imported a PST into my Exchange Online Archive (Office365) but the issue is the items imported (more than 3 Go) are not displayed in the UI. So my archive quota displays 3 Go but I only can see 2 folders with few items.

Before to try another import, I would to delete/clean my archive.
I can't do that with the UI (the items are not displayed).

So my question is, can I use a PS Script to do a recursive delete into all my archive?

I didn't find scripts to do that and never seen a PS Script to empty an online archive :(

Regards.

Powershell script to get Computer Description + OU details

$
0
0

Hello,

I need help in finding Computer Description and OU details of 100 machines from ADs.

any simple command to get this ?



Comparing 2 Csv files.

$
0
0

Hello Experts,

Below is the code and the question. 

I am comparing 2 csv files and addding a flag to the output csv file which value does not match and $result.Model  and $result.computer contains 2 times repeat data .

#==============================================

$BaseCSV = import-csv -Path "D:\Compare Files\OS1.csv"

$NewCSV = import-csv -Path "D:\Compare Files\OS2.csv" 

  

$output = @() 

   forEach ($Column in $BaseCsv) {  

 

$result = $NewCSV | Where-Object {$Column.COMPUTER -eq $_.COMPUTER}

 

$OldModelValue = $result.Model

$ModelFlagValue = [string]::Compare([string]$Column.Model, [string]$result.Model, $True)

If ($ModelFlagValue = '0') {$Model = [string]$column.Model} else {  $Model = $result.Model -join "-Flag"} 
$result.Model

 

write-host $Model

$output += New-object PSObject -property @{

 

COMPUTER = $Column.COMPUTER

Model = $model

 

}

 }

$output | Select-object COMPUTER,MODEL |Export-Csv  -Path "D:\Compare Files\Change.csv" -NoTypeInformation -Force

 

Sample CSV file1.

Computer,Model

abc,sdfhskdfhs

xyz,fdkssdfh

paris,dfdsfkh

 

Sample CSV file2.

Computer,Model

abc,sdfhskdfhssad

xyz,fdkssdfhsad

paris,dfdsfkhsad

  

Any help or pointers pls. 


Priyabrata


Weird issue with moving folder with Move-Item

$
0
0

This is my scriptpart

$hsource = "\\fileserver\data\foldername"

$hdestination = ("\\fileserver\data\archive\foldername-archived-" + (get-date -format "d-MMMM-yyyy-HH-mm"))

Move-Item $hsource $hdestination

Now i have a service account that should execute the script which is a domain admin like i am.

When executing this script with the service account i get the following error:

Invalid Path: '\\fileserver\data\foldername'.

At line:95 char:2

+  Move-Item $hsource $hdestination

+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (:) [], ArgumentException

    + FullyQualifiedErrorId : MoveItemDynamicParametersProviderException

If i execute it with my own account on this server it's working flawles.
Both accounts are getting their permissions via the same group.

I tried disabling the quota manager but that doesn't make any difference.

Folder security does not prohibit the account access in any way.

Moving the folder manually is going without problems.

 

Can anyone point me in the right direction ? 

 

Many thanks

Getting a csv list of users and their AD group membership

$
0
0

Hi,

My situation is as follows, I have a starting CSV file which contains only the username, without @domain.smth suffix. For example, a file USERS.CSV has the following:

derek.trotter
rodney.trotter
uncle.albert


and nothing else (in reality it will be a long list of users). For example, let's say I have two AD groups:
Accounting
Management

Also, for the example, let's say that derek.trotter and uncle.albert are members of the Accounting group, and rodney.trotter is a member of the Management group.

What i would like to know is how to use a single powershell script to get two new CSV files that would look like this:

1st file:
derek.trotter,Accounting
uncle.albert,Accounting


2nd file:
rodney.trotter,Management

Thanks!


finding missing record on load

$
0
0

 Is there any way that after loading a csv file to MSSql that you could check to make sure all records loaded?
Example:
 You are loading a csv(3 fields) that has customer data.. The key is custnbr in Csv and Sql table. 

custnbr.csv

  custnbr,pcode,mod-date

 0043853,4ggp,11-14-2015
 0043663,3ggp,11-14-2015

SQL
cust_mstr - table  
Keyfield:custnbr

LineCount(exclude header) from csv 35 SQL table count 34  .. how to find missing record?

  Thanks.

SCCM Client cmdlet Win32Reg_AddRemovePrograms

$
0
0
I am trying to write a powershell script to get a list of all application install on the local compouter, using the the SCCM Client cmdlet Win32Reg_AddRemovePrograms, the computers do have the SCCM 2012 R2 client installed, but I am running into an issue. The command will only collect the programs base on the bit level of powershell.  So if I open Powershell (x86) and run Get-WmiObject -Class Win32Reg_AddRemovePrograms, I get the 32 bit applications on a 64 bit computer.  I need to run that same command in Powershell (x64) to get the 64 bit applications.  I tried using Win32Reg_AddRemovePrograms64, but I get the same list as the other cmdlet.  Am I missing something with this cmdlet?
Viewing all 21975 articles
Browse latest View live


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