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

Merge csvs to append columns not rows

$
0
0

I have four csv files with 2-6 columns in (about 30 rows each) and I need to merge them together into one csv file containing the columns. Is this do-able in PowerShell?

Thanks in advance
Adam

EDIT - I'm thinking something along the lines of:

for each csv{
for each column{
read in the column

}

}
output the variables as a new csv


Dump object properties and values to string / variable

$
0
0

Hi all,

I'm creating some automation scripts for Office 365 to add mailboxes to eDiscovery as part of an offboarding process.  So a user's mailbox will be added to legal hold and then the AD object is deleted.  I want to keep some data about the user in each new mailbox search.  The mailbox search has got a "Description" property on Office 365... basically a big text box where u can keep a description of each mailbox search.

Long story short, I'm building a string variable which has all the data of the user which I will ultimate use when I create the new mailbox search object.  To achieve this, I run a command on office365 and this holds the user properties in an object...like:

$MsolUser = Get-MsolUser -UserPrincipalName $UserUPNToOffboard

This gives me a whole bunch of data if I run $MsolUser | fl ... for example:

PS C:\> $MsolUser | fl

ExtensionData                          : System.Runtime.Serialization.ExtensionDataObject
AlternateEmailAddresses                : {test@test.com}
AlternateMobilePhones                  : {}
AlternativeSecurityIds                 : {}
BlockCredential                        : True
City                                   : 
CloudExchangeRecipientDisplayType      : 1073741824
Country                                :
Department                             : Information Services
DisplayName                            : Test User
Errors                                 : {Microsoft.Online.Administration.ValidationError,
                                         Microsoft.Online.Administration.ValidationError}
Fax                                    :
FirstName                              : test
ImmutableId                            : rcmeg5BX002hsl0oXcEs1A==
IsBlackberryUser                       : False
IsLicensed                             : False
LastDirSyncTime                        : 10/30/2014 6:24:17 PM
LastName                               : test
LastPasswordChangeTimestamp            : 9/12/2014 3:35:06 PM
LicenseReconciliationNeeded            : False
Licenses                               : {}
LiveId                                 : 10037FFE8A4F6083
MobilePhone                            :
ObjectId                               : 918265f1-12ba-4874-a330-5f2fc514fa2c
Office                                 : Head Office
OverallProvisioningStatus              : None
PasswordNeverExpires                   : True
PasswordResetNotRequiredDuringActivate :
PhoneNumber                            :
PortalSettings                         :
PostalCode                             : 

and so forth.

Now, I want that FL data in my description box... I'm trying to build this into a variable, and my first part of my "description building" is:

$Description = "eDiscovery mailbox hold for offboarded user $DisplayName.  `n `n MSOL Dump: 

So... first part works ($Displayname comes from $DisplayName = $MsolUser.DisplayName).  But for the life of me I can't get that object and all it's properties and values into that variable... 

In the end, I want my $Description variable to look something like this:

eDiscovery mailbox hold for offboarded user Test User.  

MSOL Dump:

ExtensionData                          : System.Runtime.Serialization.ExtensionDataObject
AlternateEmailAddresses                : {test@test.com}
AlternateMobilePhones                  : {}
AlternativeSecurityIds                 : {}
BlockCredential                        : True
City                                   : 
CloudExchangeRecipientDisplayType      : 1073741824
Country                                :
Department                             : Information Services
DisplayName                            : Test User
Errors                                 : {Microsoft.Online.Administration.ValidationError,
                                         Microsoft.Online.Administration.ValidationError}
Fax                                    :
FirstName                              : test
ImmutableId                            : rcmeg5BX002hsl0oXcEs1A==
IsBlackberryUser                       : False
IsLicensed                             : False
LastDirSyncTime                        : 10/30/2014 6:24:17 PM
LastName                               : test
LastPasswordChangeTimestamp            : 9/12/2014 3:35:06 PM
LicenseReconciliationNeeded            : False
Licenses                               : {}
LiveId                                 : 10037FFE8A4F6083
MobilePhone                            :
ObjectId                               : 918265f1-12ba-4874-a330-5f2fc514fa2c
Office                                 : Head Office
OverallProvisioningStatus              : None
PasswordNeverExpires                   : True
PasswordResetNotRequiredDuringActivate :
PhoneNumber                            :
PortalSettings                         :
PostalCode                             : 

Anyone got any ideas?


\\Tjopsta// http://www.tjopsta.net

System.Drawing.Bitmap($_.FullName) fails with "Online only" files stored on OneDrive

$
0
0

Hi,

I want to retrieve the DateTaken from JPG files that are stored on my OneDrive. If the file is available offline, the code works fine. However, if the file is "Online only" the code below breaks when creating the New-Object System.Drawing.Bitmap and generates the following error: "New-Object : Exception calling ".ctor" with "1" argument(s): "Parameter is not valid."

Is there any way to work around this problem?

[reflection.assembly]::loadwithpartialname("System.Drawing") | out-null
Get-ChildItem ($Path + "\*") -include @('*.jpg', '*.jpeg') -Force | ForEach-Object {
        if (! $DateTimeArg)
        {       
            $pic = New-Object System.Drawing.Bitmap($_.FullName)
            $ExifDate = $pic.GetPropertyItem(36867)
            $DateTaken = (New-Object System.Text.UTF8Encoding).GetString($ExifDate.Value)
            $DateTime=[datetime]::ParseExact($DateTaken,"yyyy:MM:dd HH:mm:ss`0",$Null)
            $pic.Dispose()

Howto pass variables to parameters to functions?

$
0
0

Hi all,

How do you pass variables as parameters to other executables within Powershell? i.e. what is the proper way?

[DBG]: PS E:\Development>> BCP.exe "$Query" queryout "$FileAddress" $ServerName $LoginUser $LoginPass -w -t"_"
SQLState = 08001, NativeError = 17
Error = [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied.
SQLState = 01000, NativeError = 67
Warning = [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()).

[DBG]: PS E:\Development>> Invoke-Expression "BCP.exe ""$Query"" queryout ""$FileAddress"" $ServerName $LoginUser $LoginPass -w -t""_"""

Starting copy...

2 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.): total        1

[DBG]: PS E:\Development>> 

In the first example, I tried using the variables directly, as when I used them within a string it looked fine, but they don't appear to be interpreted by Powershell - for example the server address being passed to BCP is $ServerName, not -S "(local)\PROD2000" as expected. So the first example fails.

In the second example, it works but you have to use the Invoke-Expression command after allowing PowerShell to interpret the string fully...

What is the proper way of passing the contents in variables onto executables as parameters?

Thanks,
Jay :)


If you shake a kettle, does it boil faster?

need WMI command to delete local user Accounts

$
0
0

hi Guys

in PowerShell 4.0, i have created a query which gets the list of all non-built-in Local user Accounts in windows 8.1 except administrator & Guest & i need 2nd part of the command, removes those non-built in users.

but when i pipe that into Remove-WMIObject command, i got the following error:

i did a lot of search but didn't find any command to pipe to Get-WMIObject be able to delete Local user accounts 

any solution please

thanks in advanced

New-ADUser error

$
0
0

Hello,

I am trying to create new users with CSV file in PowerShell.

The CSV file contains:

name,givenname,surname,displayname,samaccountname

mike111,mike,kyles,mike kyles,mikyles

robert111,robert,storm,robert storm,rostorm

In PowerShell I do the following:

$user = ImportCsv -Path c:\csvfile.csv

$name = $user.name

$given = $user.givenname

$sur = $user.surname

$sam = $user.samaccountname

$display = $user.displayname
New-ADUser -Name "$name" -givenname "$given" -surname "$sur" -displayname "$display" -SamAcco
untName "$sam" -path "ou=users,dc=azazum,dc=com" -AccountPassword (ConvertTo-SecureString Pa$$w0rd -AsPlainText -Force) -Enabled $true -ChangePasswordAtLogon $true -Server azazum.com

The error:

New-ADUser : Directory object not found
At line:1 char:1+ New-ADUser -Name "$name" -givenname "$given" -surname "$sur" -displayname "$disp ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : ObjectNotFound: (CN=Mike111 Robe...c=azazum,dc=com:String) [New-ADUser], ADIdentityNotFo
   undException+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,M
   icrosoft.ActiveDirectory.Management.Commands.NewADUser

Can someone please suggest why does it fail?

Need help for a class assignment

$
0
0

My instructor is no help at all and won't answer any of my questions.  He told us to google this assignment in order for us to complete it. 

This was the assignment:

    • This script should do the following:
      1. Create a variable called $ara_procs
      2. Obtain a list of processes, sort by ID, and place the results inside of $ara_procs (you must use pipes)
      3. Use a foreach to loop on the array; within the loop:
        • At the start of the loop, print "----------------------------------------"
        • Print the ID and process name together (ex. 7096 iexplore)
        • Using an if statement, if the main window title for the process is NOT null and NOT an empty string (GOOGLE/YAHOO: "how to use null in powershell")
        1. Create 5 variables: $title, $paged, $pkpaged, $virtual, $pkvirtial
        2. Set each variable equal to the appropriate property in the current process object (with exception of the title variable, the rest should be numbers to be displayed in the console)
        3. Using interpolation, print "Main window title: title" replacing the word title with the appropriate variable
        4. Using interpolation, print "Paged mem: mem" replacing the word mem with the appropriate variable
        5. Using interpolation, print "Peak paged mem: mem" replacing the word mem with the appropriate variable
        6. Using interpolation, print "Virtual mem: mem" replacing the word mem with the appropriate variable
        7. Using interpolation, print "Peak virtual mem: mem" replacing the word mem with the appropriate variable
  1. Save the script as Lesson10_3.ps1
  2. Test the script in Powershell
  3. This is what I have written so far:

    $ara_procs = @(Get-Process | sort-object id)

    foreach( $proc in $ara_procs )
    {
        
        write-host "-------------------------------"
        
        
        $title = $proc.MainWindowTitle
        $paged = $proc.PagedMemorySize
        $pkpaged =$proc.PeakPagedMemorySize
        $virtual =$proc.VirtualMemorySize
        $pkvirtual = $proc.PeakVirtualMemorySize
        






        write-host "Main window title: $title"
        write-host "Paged mem: $paged"
        write-host "Peak paged mem: $pkpaged"
        write-host "Virtual mem: $virtual"
        write-host "Peak virtual mem: $pkvirtual"


    }









    write-host
    write-host
    write-host "Press enter key to continue ..."
    read-host
    # end of script

    If anyone could help me with this I would be eternally grateful.

    Control MP4 playback using powershell

    $
    0
    0

    I have found that i can start a movie using ....
        $player = new-object -com WMPLAYER.OCX  
        $player.openplayer("c:\dir1\subdir\movie.mp4")  

    Things I would like to be able to do are....
    - redirect the playback to a WiDi device ( Play to )
    - Pause
    - Play ( un-pause )
    - Stop

    Thanks
    Tom


    foreach loop... get managedby for a list of distribution groups

    $
    0
    0

    hello all. thanks for the time. this is probably a simple one. but for some reason i can't get this working.  I am trying to get the managedby property of a distribution list.  i can easily get that for one but i want to call a list of distros from a text file.

    for one group:

    Get-DistributionGroup groupname | select displayname -expandproperty managedby | select displayname,name

    for a list.. I am doing this but it is looping:

    get-content c:\output\lists.txt | foreach {get-distributiongroup | select displayname -expandproperty managedby | select displayname,name} | export-csv c:\output\managedby.csv

    what am i doing wrong? or is there an easier path... all help is appreciated.  thank you.

    Is it an easier way to manage seterror

    $
    0
    0

    Hi,

    I have a form and on the OK button, I am validating each field. At the end, if everything is OK then I close the form.

    I am checking each field with If ... elseif. Would it be possible to make a single if for each field and set or unset the error and at the end if there is no error just close the field?

    If([String]::IsNullorEmpty($TxtNomLogiciel.Text)) {
       $ErrorProvider.SetError($TxtNomLogiciel, "Le champs du nom du logiciel ne doit pas être vide")
       }
      Elseif ([String]::IsNullorEmpty($ComboManufacturiers.Text)) {
       $ErrorProvider.SetError($ComboManufacturiers, "Un nom du manufacturier doit être inscrit")
       $ErrorProvider.SetError($TxtNomLogiciel, "")
       }
      Elseif ([String]::IsNullorEmpty($TxtVersionLogiciel.Text)) {
       $ErrorProvider.SetError($TxtVersionLogiciel, "Le champs de version du logiciel ne doit pas être vide")
       $ErrorProvider.SetError($ComboManufacturiers, "")
       }
      Elseif ([String]::IsNullorEmpty($TxtEmplacement.Text)) {
       $ErrorProvider.SetError($TxtEmplacement, "Le champs d'emplacement de la trousse ne doit pas être vide")
       $ErrorProvider.SetError($TxtVersionLogiciel, "")
       }
      Elseif (-not(Test-Path -Path $TxtEmplacement.Text)) {
       $ErrorProvider.SetError($TxtEmplacement, "L'emplacement inscrit est invalide (je ne le trouve pas)")
       }
      Else {$MainForm.Close()}

     

    Thanks,

    François

    Write console output to file

    $
    0
    0

    As I write the results  deleted text files to a file?

    ********************************************

    foreach ($path in Get-Content "folders.txt") {

    Get-ChildItem $path -Recurse  | Where-Object { $_.creationtime -lt (Get-Date).AddDays(-120) -and (!($_.psIsContainer))} | Remove-Item -Verbose 

    ********************************************

    Thanks

    Test-Path with different Culture

    $
    0
    0

    I'm trying to find the best way to test-path of a Network location that includes a special Danish character in a directory. (it runs from Orchestrator and therefor the culture is set to en-US)

    I found this rather old post on changing culture in the current PowerShell session and it might work. Would this still be a good way to do it today, or is there a better way to do this?

    http://blogs.msdn.com/b/powershell/archive/2006/04/25/583235.aspx

    PowerShell console font

    $
    0
    0

    Hi

    How is possible to change the font for PS console.  it seems to be impossible.  I know there are 3 fonts avaiable but no matter.  I would like use it in my profile so I don't have to change it every time I open PS console.

    thanks

    mjksgea

    Error handling, background jobs

    $
    0
    0

    Hello, having a script which will query FEP installation and Signature version on remote computers
    If the computers are online and everything works, there is no problém.

    How to deal with exceptions like

    ItemNotFoundException, PSRemotingTransportException (Access to the server denied), PSremoting not enabled .. 

    I would like to have output like

    name;Product;Version;ErrorHandling 
    server1;;;AccessDenied
    server2;;;ItemNotFound
    server3;Microsoft Forefront Endpoint Protection;1.175.2096.0;
    server4;;;ItemNotFound
    server5;;;ServerOffline

    Param ([int]$BatchSize=20) #list of servers [array]$source = (get-adcomputer -filter {operatingsystem -like "Windows server*" -and name -like "s*exf*"}) |select -expandproperty dnshostname #scriptblock $blok = { $mycol = @() $AVSignatureVersion = Get-ItemProperty 'hklm:\SOFTWARE\Microsoft\Microsoft Antimalware\Signature Updates\' |select -Expandproperty AvSignatureVersion $ProductName = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |?{$_.displayname -like "*Microsoft Forefront Endpoint*" -and ($_.installLocation)} |select -ExpandProperty Displayname $MyObject = New-Object PSObject -Property @{ AVSignatureVersion = $AVSignatureVersion ProductName = $ProductName ErrorHandling =

    } $mycol += $MyObject $mycol } $i = 0 for ($i=0; $i -lt $itemCount;$i += $batchSize){ $activeJobCount += 1; $totalJobCount += 1; $HostList = @() $HostList += $source |select -skip $i -first $batchsize $j = invoke-command -computername $Hostlist -scriptblock $blok -asjob }

    Please guide me how to these exceptions into $errorhandling variable

    .. and.. i guess,  some errors are getting inside scriptblock ([ItemNotFound]) and others like [accessDenied]  outside?  So, is it possible to get the job exception into $myCol?

    Help importing csv file to active directory.

    $
    0
    0
    I've read quit a few posts on this subject, but none have any specifics as to the attributes I'm wanting to import to active directory. Any help would be great, I need to import from a csv file the attributes "name, manager, email, location, phone. I'm new at powershell so any help would be great. Thanks.

    disabling password complexity via powershell

    $
    0
    0

    hi friends

    i spent lots of time searching entire internet to find a command or script (powershell, cmd, VB, registry...) to be able to disable password complexity. there are few solutions which none of them works.

    i wonder how what a pity if we can't do such simple thing in Microsoft windows

    i really need that because i have created a script which contains many lines which automates windows customization which i always need in my classrooms for testing & teaching purposes

    thanks for any help

    ps script does not sen email when run from a bat file

    $
    0
    0

    when im running the script from the powershell app on windows 2008r2 server it sends the email with no problem. but when im using a bat file to call to the ps1 file for schedule jobs the whole script is run except for the email sending function, please look at the attached files, how can i fix that?

    During Foreach read another foreach - PLZ HELP!

    $
    0
    0

    Hi all powershell gurus out there.

    I have a foreach which opens a URL from URLListl.txt and doing aMeasure-command on them. The result from Measure-command writes to event-log. 

    In another text file i have country list, like:

    USA
    Canada
    Brazil
    and so on....

    I want in write eventlogs Message to read from this Text file and write it with the Measure-command result in Message part of the eventlog.

    The below is my script which works fine but it creates two entries for each URL.

    
    function Measure-Site
    {
        $URLListFile = "C:\yourname\URLList.txt"
    	$URLList = Get-Content $URLListFile -ErrorAction SilentlyContinue
    	Foreach ($Uri in $URLList)
    	        {
    
    		    $Time = Measure-Command {
    			C:\yourname\MainScript.ps1}
    			$Time.TotalSeconds
    
    
    
        $countrycode = (Get-Content c:\yourname\URLListcountry.txt)
          foreach ($SiteCode in $CountryCode)
                {
    	        $LogFileExist = Get-EventLog -list | Where-Object { $_.LogDisplayName -eq "Scriptcheck" }
    
    			if (! $LogFileExist)
    			{
    				New-EventLog -LogName "Scriptcheck" -Source "Scripts"
    			}
    			if ($Time.Totalseconds -lt 25)
    			{
    				Write-EventLog -LogName "Scriptcheck" -Source "Scripts" -EntryType information -EventId 100 -Message " $SiteCode `nTotal Time: $Time"
    			}
    			elseif ($Time.Totalseconds -gt 25)
    			{
    				Write-EventLog -LogName "Scriptcheck" -Source "Scripts" -EntryType warning -EventId 101 -Message " $SiteCode  `nTotal Time: $Time"
    			}
                }
                }
    }
    
    
    if (Get-Process -name iexplore -ErrorAction SilentlyContinue)
        {
    	Stop-Process -Name iexplore
        }
    Measure-Site

    Create internet explorer object from process ID

    $
    0
    0

    Hi,

    I want to create a object for open instance of internet explorer and pass username and password to it.

     

    By using the below command I am getting the process object but how can we create internet explorer object from it so that I can access document elements.

     

    gps | ? {$_.mainwindowtitle -match 'Service'} | select name, mainwindowtitle

    Thanks

    Prasanna

    Problem with concatenating strings

    $
    0
    0

    Hi Forum;
    I'm writing a script for: open a list of a servers (having an IP-Adress), create a loop, determine a special folder on every server, copy a file into this folder, go to the next server.
    I have a function RunSQLSMO getting me name of the special folder:

    function RunSQLSMO($SQLServerName,$DatabaseName, $SQLCmd)
    {
         $srv = New-Object("Microsoft.SqlServer.Management.Smo.Server") $SQLServerName
         $MyDatabase = $srv.Databases[$DatabaseName]
         return $MyDatabase.ExecuteWithResults($SQLCmd)
    }

    having:

    $sqlServer = "150.xxx.xxx.xxx\myInstance"
    $dataBase = "myDB"
    $sqlCommand = "select PFAD_MSSQL + 'Reports' as pfad from myDB.dbo.myTAb"
    $Results=RunSQLSMO $sqlServer $dataBase $sqlCommand
    $a=$Results.Tables | ft -hidetableheaders
    $pfad + '\' + $a

    I'll get:
    $a= L:\MSSQL_Instance\MSSQL.8\MSSQL\Reports 
    but:
    $pfad + '\' + $a is giving back:
    157.163.136.18\Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Int
    ernal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData

    I'd like to have: 150.xxx.xxx.xxx\myInstance\L:\MSSQL_Instance\MSSQL.8\MSSQL\Reports 

    Thanks for your help

    Purclot

    Viewing all 21975 articles
    Browse latest View live


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