Search code examples
powershellsplitazure-powershellpowershell-4.0

How to split before exporting to csv in PowerShell


I've this simple script and I'm wondering how can I split WebUrl value, add a new column called "UserID" and add it in there.

Right now it look like this

DisplayName      WebUrl
John Smit        http://www.web.com/personal/klmno_gmail_com

and I'm trying to add a new column like this after spliting the WebUrl. The URL format will be always consistent. Any help or suggestion would be really appreciated.

DisplayName      WebUrl                                UserID
John Smit        http://www.web.com/personal/KLMNO_gmail_com    KLMNO

        $AllSites = Get-MGSite -All
        $odSites = $AllSites |?{$_.Weburl.contains("/personal/")}
        $odSites | Select-Object -Property DisplayName, WebUrl | export-csv $Global:Export -NoTypeInformation


Solution

  • Select-Object accepts a specially formatted hash that can dynamically form new properties on the pipeline object.

    This is a quick and dirty example.

    PS> $odSites | Select-Object DisplayName, WebUrl, @{label="UserID";expression={$_.WebUrl.split('/')[3].split('_')[0]}}
    
    DisplayName WebUrl                             UserID
    ----------- ------                             ------
    John Smit   http://www.web.com/klmno_gmail_com klmno
    

    You could also use Add-Member -MemberType ScriptProperty

    PS> $odSites | Add-Member -MemberType ScriptProperty -Name UserID -Value {$this.WebUrl.split('/')[3].split('_')[0]}
    
    PS> $odSites
    
    DisplayName WebUrl                             UserID
    ----------- ------                             ------
    John Smit   http://www.web.com/klmno_gmail_com klmno