Question

I run the following script in SP PowerShell

Add-PSSnapin Microsoft.SharePoint.Powershell -ea 0;

$web = get-spweb 'http://tvstg01/kb/customerservice/'
$list = $web.lists['Customer Service'];

foreach($file in $list.items){
    $links = $file.ForwardLinks;

    foreach($link in $links){
        if($link.url -like '*/Documents/*'){
            Write-Host $file.name $link.url
        }
    }

}

But the result will be shown in the screen and some result will be cleared, so is there a way to write the result to a notepad?

Was it helpful?

Solution

You can use Custom Objects and use Export-CSV as below.

This approach will give you more flexibility like opening in Excel and Sort, Filter etc.

Also you can easily add additional fields to output.

Add-PSSnapin Microsoft.SharePoint.Powershell -ea 0;

$web = get-spweb 'http://tvstg01/kb/customerservice/'
$list = $web.lists['Customer Service'];

$resultsarray =@()

foreach($file in $list.items){
    $links = $file.ForwardLinks;
    foreach($link in $links){
        if($link.url -like '*/Documents/*'){
            $linkObject = new-object PSObject
            Write-Host $file.name $link.url
            $linkObject | add-member -membertype NoteProperty -name "FileName" -Value $file.name
            $linkObject | add-member -membertype NoteProperty -name "Url" -Value $link.url

            $resultsarray += $linkObject
        }
    }
}

$resultsarray| Export-csv FileName.csv -notypeinformation

OTHER TIPS

Replace

Write-Host $file.name $link.url

with

"$($file.name) $($link.url)" | Tee-Object test.txt -Append

This will output the text to both the screen and test.txt (remember to clear this first)

Run the following code to get in txt file

      Add-PSSnapin Microsoft.SharePoint.Powershell -ea 0;
        $output=""
        $web = get-spweb 'http://tvstg01/kb/customerservice/'
        $list = $web.lists['Customer Service'];

        foreach($file in $list.items){
            $links = $file.ForwardLinks;

            foreach($link in $links){
                if($link.url -like '*/Documents/*'){
                    Write-Host $file.name $link.url
                     $output= $output + $file.name $link.url+"`r`n" #print to new line
                }
            }
        }  
$output  | out-file c:\myFolder\Output.txt #Output as txt file

You can use start-transcript, which records Powershell activity to a text file. Something like this:

# Store the executing directory
$thisDir = Split-Path -Parent $MyInvocation.MyCommand.Path
# Set log file to script name + '.log'
$logFile = '{0}.log' -f $MyInvocation.MyCommand

# Start logging
Start-Transcript -Path $thisDir\$logFile

Write-Host This text will be written to the log file and the screen

# Stop logging
Stop-Transcript

# Open the log file in Notepad
notepad $logFile
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top