Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

How would I convert this to a CSV

$
0
0

Hi All,

I was wondering how I would convert the below to output to CSV and NOT call excel, as I dont have it on the server and keep the same format, so it outputs into two columns, with just the IP and Name.  Thanks in advance.  Script works just need it to interface with notepad rather than excel.

Kind Regards,

Sean,

$Printserver = "Printserver"


$Excel = new-Object -comobject Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)
$Sheet.Cells.Item(1,2) = "Printer Name"
$Sheet.Cells.Item(1,1) = "IP Address"
$intRow = 2
$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True


$Printers = Get-WMIObject Win32_Printer -computername $Printserver
foreach ($Printer in $Printers)
{
    $Sheet.Cells.Item($intRow, 2) = $Printer.Name
    $Ports = Get-WmiObject Win32_TcpIpPrinterPort -computername $Printserver
        foreach ($Port in $Ports)
        {
            if ($Port.Name -eq $Printer.PortName)
            {
            $Sheet.Cells.Item($intRow, 1) = $Port.HostAddress | %{"{0:000}.{1:000}.{2:000}.{3:000}" -f @([int[]]$_.split('.'))}
            }
        }
    }

$WorkBook.EntireColumn.AutoFit()
$intRow = $intRow + 1
$Sheet.Cells.Item($intRow,1).Font.Bold = $True
$Sheet.Cells.Item($intRow,1) = ""


Cannot Substring in Script - Error You cannot call a method on a null-valued expression

$
0
0

Hi All,

I have a script for gathering User Info and I wanted to Substring one of the properties.

Script:

$ADUser = get-aduser -filter * -properties *
###Create an empty array:
$myCol = @()
foreach ($user in $ADUser)
{
$myUsers = New-Object System.Object
$myUsers | Add-Member -memberType Noteproperty -name sAMAccountName -value $user.sAMAccountName
$myUsers | Add-Member -memberType Noteproperty -name LastName -value $user.sn
$myUsers | Add-Member -memberType Noteproperty -name FirstName -value $user.givenName
$myUsers | Add-Member -memberType Noteproperty -name DisplayName -value $user.DisplayName
$myUsers | Add-Member -memberType Noteproperty -name PhoneNumber -value $user.telephoneNumber
$myUsers | Add-Member -memberType Noteproperty -name EmployeeStatus -value $user.comment
$myUsers | Add-Member -memberType Noteproperty -name Extension -value $user.telephoneNumber.ToString().Substring($user.telephoneNumber.Length -4,4)
###Add values to an Array(add everything from $myUsers to $myCol):
$myCol += $myUsers
}
$myCol | export-csv c:\adminscripts\UserExport.csv -NoTypeInformation

The script chokes on my attempt to Substring the telephoneNumber.  It works just fine if you test the Substring...

This is the error I receive:

At C:\adminscripts\Last_4_characters_GetUserInfo.ps1:14 char:101
+ $myUsers | Add-Member -memberType Noteproperty -name Extension -value $user.telephoneNumber.ToString <<<< ().Substrin
g($user.telephoneNumber.Length -4,4)
    + CategoryInfo          : InvalidOperation: (ToString:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

I don't know what I'm doing wrong.  Like Princess Leia to Obi-Wan, "you're my only hope."

Mr Mister

Reading large binary files

$
0
0

Hi, I’m a beginner in PowerShell scripting. I want to read a binary file, I can skip to a position and read one byte, but I can’t read two bytes, I don’t know how to give the buffer for the read operation, I don’t want to use C#. Can somebody show a little snippet how to skip to, e.g., 603761 and read 1024 bytes? Preferably to show where it is documented and where I can find similar sample scripts. I’ve looked a few dozen threads on this forum, no luck.
Thanks, Vilmos

Parse MAC address from "getmac"?

$
0
0

When I use $a = getmac it returns

Physical Address     Transport Name

==========      ==========

xx-xx-xx-xx-xx-xx   \Device\Tcpip_......

I want to extract only the "Physical Address" portion using something like this:

         $b = $a | select "physical address"

but there is no such property. How can I parse this string ($a) in PS?

TIA,

edm2

using copy-item and retaining security permissions

$
0
0

I am trying to copy files and folders from one (network) location to another while keeping permissions intact. Copy-Item doesn't seem to do that Maybe I am just using it wrong? No need to go all crazy with accessing permissions directly if I can just copy my files from source to target and keep permissions intact right?

copy-item -Pathc:\test2-Destinationc:\test3-Recurse

Create a distribution Group based on extensionAttribute6

$
0
0

Hello,

I need to create a Distribution group  based on extensionAttribute7 and extensionAttribute6, how can i do this ??

e.g. i need all users that having the the extensionAttribute6 7 equal p_*** and extensionAttribute6 6 equal 'M'


Script to Scan Specific OU and copy the Security Groups names and members then created a DG with these info

$
0
0

Hello,

I need script to scan a specific OU and get all security group names and their members, then take this names and members and created a distribution group for each security Group.

e.g.  Students Security Groups and it has 300 Student

the script will create a Distribution group with the exact security Group name and all members in the Student security group will be members in the Student Distribution Group.

on my windows xp I cannot find the command for the 'at' sign

$
0
0
I cannot find the command for the @ on my other pc which uses windows xp

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>"

get top 10 installed programs on all machines in domain

$
0
0

hi

is there a way in powershell to:

connect to all machines in domain

check what programs are installed on each machine

list by number of instances in total

return list in nice txt document


Kindest regards, Martin

Codesigning cert in a workstation computer

$
0
0

Hi!

Is there a way to create a self signed codesigning cert on a non-domain computer?

I want to use it on my home computer to sign powershell script that i will run on startup. Any ideas how i could accomplish this?

Need to rename file replacing digit by letter

$
0
0

hi

I am renaming files by

get-childItem *.enx | rename-item -newname { $_.name -replace "^.*\.aiz_(.*) \((.*)\)_\d(\d{2})\.enx$", '$1-P$3-$2!$2.enx' }

where $2!$2 must be 01!A if "01", 02!B if "02", 03!C if "03"... etc.

please help me.

thanx.

Remove duplicates from text file that matches a given string

$
0
0

Hi, total newbie here.

I have a text file which contains the following data

Generic Playlist File - Version 1.01
00:00:00H0024    000:000024            Top of Hour (Multi Station)            
00:xx:xxC0000    000:408011            PYB - STARTS MON - 1                   
00:xx:xxM0000    000:000000            Traffic Merge01                        
00:xx:xxM0000    000:000000            Traffic Merge01                        
00:xx:xxC0000    000:00J8206           DRY 5" tell u that                     
00:xx:xxC0000    003:08E1230           GOOD THING                             
00:xx:xxC0000    000:03J8223           DRY 3" welcome to      

I need to remove any duplicate lines containing the string "Traffic Merge" only. Any other strings that may be duplicated must not be touched.

The end results need to look like this.   

Generic Playlist File - Version 1.01
00:00:00H0024    000:000024            Top of Hour (Multi Station)            
00:xx:xxC0000    000:408011            PYB - STARTS MON - 1                   
00:xx:xxM0000    000:000000            Traffic Merge01                                               
00:xx:xxC0000    000:00J8206           DRY 5" tell u that                     
00:xx:xxC0000    003:08E1230           GOOD THING                             
00:xx:xxC0000    000:03J8223           DRY 3" welcome to     

I'm guessing this can be done using powershell but I'm about a month away from learning how to do it myself. Any help would be fantastic.

Thank you!

Greg

             

Uninstall PS V3

$
0
0

Hi,

I would like to uninstall Powershell V3, deployed too fast on my computers ...
I know how to remove it from one PC.
But I have to uninstall from many.

Do you know a command line to uninstall Windows Management Framework (WMF) 3.0, (currently distributed as KB2506146 for Windows Server 2008 SP2 and KB2506143, for Windows 7 SP1 and Windows Server 2008 R2 SP1) ?

Thank you for your help.

Ludovic

PS : http://blogs.msdn.com/b/powershell/archive/2012/12/20/windows-management-framework-3-0-compatibility-update.aspx
PPS : I found another problem with this upgrade : my Altiris deployments failed when session is not open and task is a script powershell.

Write aggregates to the pipeline

$
0
0

Hi,

When writing an cmdlet in C#, is there a way to write aggregates to the pipeline? When I use:

        protected override void ProcessRecord()
        {
            // is it possible to return an object that contains a list of objects in the pipeline?
            ErrRecord error = new ErrRecord() { RecordNumber = 1 };
            error.Columns.Add(new ErrColumn() { ColumnName = "col1", Type = ErrType.Warning, Value = "xyz" });
            error.Columns.Add(new ErrColumn() { ColumnName = "col2", Type = ErrType.Breaking, Value = "ABC" });

            WriteObject(error);
        }

I get the following error:

Get-StatTdsErrorlist : Object reference not set to an instance of an object.
At line:1 char:21
+ Get-StatTdsErrorlist <<<<
    + CategoryInfo          : NotSpecified: (:) [Get-StatTdsErrorlist], NullReferenceException
    + FullyQualifiedErrorId : System.NullReferenceException,IphPSModules.GetStatTdsErrorlist

thanks,

Jan


Basic File Operations

$
0
0

Hello everybody!

This is my very first query on this forum. I have fair knowledge of programming, but I am an ultimate beginner to the WindowsPowerShell.  I just want to take a start of using the PowerShell by transforming a very simpleBatch files, of mine, into psl. I hope some good soul will guide me through the process:

In Not Exist "mySample.ini" goto Step2

Del mySample.ini

Echo The file has been deleted.

:Step2

myExefile

Exit

:End

Please help!

Raby

Match of word in text file

$
0
0

I want to be notified if the word imported is not in the text file. This part of the script. What am I doing wrong?

$word = gc -Path "\\noctest1\c$\temp\testimp.txt" -Filter "imported"
If ($word -match 'imported')
{"valid" }
Else
{"invalid"}


Maximo Vizcaino

Need to make web call but COMPLETELY ignore any returning data

$
0
0

Desperate for some help here.  I wrote an .asmx web service that when called and passed the computername, runs a function and outputs a .txt file to a shared directory.  That works fine.  Later down the road a system will retrieve that text file.  

I am writing the powershell script to call the web service and I don't care even one little bit about the return XML data.  However, powershell is bombing out when I make the call claiming the data and XML are invalid and such.  Can I just kick off the web call and pass the computer name and ignore any return data so my script will keep running?  If so, how might I do that?  Here is my code so far, I am on Powershell 2.0.

$hostname = $env:computername
$webservice = "http://webserviceurl/webservice/webservice.asmx/computername?computername="

New-WebServiceProxy -Uri $webservice$hostname

The web service is successfully called and does what I need.  But the script hates the return and I want to completely ignore it and move on.  Thank you!

Only OU Name

$
0
0

Hi

I have below script to pull out the enabled users from Active Directory.

Get-ADUser -Filter {enabled -eq "True"} -SearchBase "DC=child,DC=contoso,DC=org" | Select-Object Name,sAMAccountName

I want to add OU name details and for this what parameter needs to be add. I know that i can get this through distingushedname but in distingushedname, it porovide full LDAP path.

But I want only OU Name instead of distinguishedname..


Register-ObjectEvent

$
0
0
I create an event subscriber using Register-ObjectEvent, I lose the Event as soon as I close the PS console (Get-EventSubscriber shows none). How do I make it permanent? It should not get affected by closing of PowerShell console of reboot  of computer. Is it possible?

-Edatha-

Viewing all 2562 articles
Browse latest View live


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