How to export Powershell script information to Sharepoint?

I'm trying to export information gather from a Powershell script to a Sharepoint list. I've got a couple of powershell scripts that gather general server information from a server ex: server uptime, disk space, service tag, etc. and it will export the information
to a csv file. What I would like to do is out-put the same information gathered by the powershell scripts to a Sharepoint list directly if at all possible.
Ex:
# all this does is reads from a list and runs a script call "boottime.ps1"
get-content "\\%Data-Path-Of-List%\computers.txt" | %Data-Path-Of-Script%\boottime.ps1 |  Export-csv %Data-Path-For-CSV\Computers.csv
# then just exports the information from the boottime.ps1 script to a csv file
#I also have a script that will upload the information to a sharepoint list.
# I found that I have to run this in version 2 of powershell, so I just open a DOS prompt in Admin Priv's and type the following
powershell.exe -version 2.0
# Next I make sure the Sharepoint snap-in is loaded
if ( (Get-PSSnapin -Name Microsoft.sharepoint.powershell - erroraction silentlycontinue) -eq $null)
Add-PsSnapin Microsoft.Sharepoint.Powershell
$spweb = get-SPweb $spserver
$spdata =$spweb.getlist("%URL_Of_My_List%")
# this is the same location from the orginal Powershell script previously stated.
$ComputerInfoFile = "%Data-Path-For-CSV%\Computers.csv"
foreach ($rows in $tblData) {
# here is where I add the information from my csv file
# 2 things needs to be present
# 1st the colums have to be present in the sharepoint site before I can upload the information
# 2nd the columns have to the headers in my csv file
$spItem = $spData.AddItem()
$SpItem["ServerName"] = $row."ServerName".toString()
$SpItem["Uptime"] = $row."Uptime".toString()
$SpItem.Update()
# this just disconnects from Sharepoint
$spWeb.Dispose()
Please dismiss all the comments it just helps me understand what the code is doing, also if this is not the correct place to post this question I appologize in adavance and ask that if this is the incorrect place to post this question please provide me a
link to a where I can post such questions.

Sorry for the delay in posting this, but I ended up getting working. I'll post it in the hopes that my head scratching will save someone else some head scratching:
I ended up writting 3 PS scripts and one batch job.
1st Batch file
powershell.exe -version 2.0 -command
\\%Script-Location\Get-Server-Infor-4-SP.ps1
powershell.exe -version 2.0 -command \\%Script-Location\Delete-list-Items.ps1"
powershell -veriosn 2.0 -command
\\%Script-Location\Populate-SP.ps1
1st PS script that gets the info:
get-content
\\%Location-Of-My-File-With-List-Of-Servers%\%name-of-file%.txt |
\\%Location-Of-My-Script-To-get-the-Information-I-want | Export-csv
\\%location-of-my-output\%filename%.csv
Ex: get-content C:\scripts\computers.txt | C:\scripts\boottime.ps1 | export-csv C:\scripts\computer.csv
2nd PS script Delete-List-Items.ps1
# http:
#Script 1 Boottime.ps1:
# This script permits to get UpTime from localHost or a set of remote Computer
# usage
# localHost
# .\BootTime.ps1
# set of remote computers
# get-content .\MyserverList.txt | .\boottime.ps1
# Optionally pipe output to Export-Csv, ConverTo-Html
Process {
$ServerName = $_
if ($serverName -eq $Null) {
$serverName= $env:COMPUTERNAME
$timeVal = (Get-WmiObject -ComputerName $ServerName -Query "SELECT LastBootUpTime FROM Win32_OperatingSystem").LastBootUpTime
#$timeVal
$DbPoint = [char]58
$Years = $timeVal.substring(0,4)
$Months = $timeVal.substring(4,2)
$Days = $timeVal.substring(6,2)
$Hours = $timeVal.substring(8,2)
$Mins = $timeVal.substring(10,2)
$Secondes = $timeVal.substring(12,2)
$dayDiff = New-TimeSpan $(Get-Date –month $Months -day $Days -year $Years -hour $Hours -minute $Mins -Second $Secondes) $(Get-Date)
$Info = "" | select ServerName, Uptime
$Info.servername = $servername
$d =$dayDiff.days
$h =$dayDiff.hours
$m =$dayDiff.Minutes
$s = $daydiff.Seconds
$info.Uptime = "$d Days $h Hours $m Min $s Sec"
$Info
#Script 2: Delete-List-Items.ps1
# http://markimarta.com/sharepoint/delete-all-items-in-sharepoint-list-using-powershell/
# there seems to be a problem with running this script in version 3 or later, the workaround is to run it in version 2
# below is the cmd for doing so, just open up a DOS prompt with Admin Privileges Start-->Run-->cmd
# type then copy and paste the following line the DOS window then you can run this script
#powershell.exe -version 2.0
# make sure that the Microsoft.SharePoint.PowerShell Snap-in is installed as well
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
Add-PsSnapin Microsoft.SharePoint.PowerShell
# "Enter the site URL instead http://serverurl"
$SITEURL = "%http://serverurl%"
$site = new-object Microsoft.SharePoint.SPSite ( $SITEURL )
$web = $site.OpenWeb()
"Web is : " + $web.Title
# Enter name of the List below in the [“%List-Name%”]
$oList = $web.Lists["%List-Name%"];
# This echo out the name of the list its going to be deleting the records from
"List is :" + $oList.Title + " with item count " + $oList.ItemCount
# It’s just counting the rows/records
$collListItems = $oList.Items;
$count = $collListItems.Count - 1
# Here is where it is actually deleting the records and then out put the number or the record it deleted
for($intIndex = $count; $intIndex -gt -1; $intIndex--)
"Deleting record: " + $intIndex
$collListItems.Delete($intIndex);
#Script 3: Populate-SP_Test.ps1
# http://blogs.technet.com/b/stuffstevesays/archive/2013/07/10/3577320.aspx
# there seems to be a problem with running this script in version 3 or later, the workaround is to run it in veriosn 2
# below is the cmd for doing so, just open up a DOS prompt with Admin Privileges Start-->Run-->cmd
# type then copy and paste the following line the the DOS window then you can run this script
#powershell.exe -version 2.0
# make sure that the Microsoft.SharePoint.PowerShell Snap-in is installed
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
Add-PsSnapin Microsoft.SharePoint.PowerShell
# Here are some more varables that can be added I was not able to get this to work
#$SPComputerInfo="/Lists/PowershellTest/"
# Here is where we connect and Open SharePoint List via Powershell
$SPServer= "%http://serverurl%
$spWeb = Get-SPWeb $SPServer
$spData = $spWeb.GetList("%List-Name%")
# This is the variable for the path that has the file I want to input to SharePoint List
$InvFile="\\%location-ofList%\computers.csv"
# This is just some error checking to make sure the file exist
$FileExists = (Test-Path $InvFile -PathType Leaf)
if ($FileExists) {
"Loading $InvFile for processing..."
$tblData = import-csv $InvFile
} else {
"$InvFile not found - stopping import!"
exit
# Loop through Applications add each one to SharePoint
"Uploading data to SharePoint...."
foreach ($row in $tblData) {
#Here is where I add the information from my CSV file
#2 things have to be present
# 1. the columns have to be in the sharepoint site before I can import the information
# 2. columns have to the headers in my csv file
#"Adding entry for "+$row."Computer Information".ToString()
$spItem = $spData.AddItem()
$spItem["ServerName"] = $row."ServerName".ToString()
$spItem["Uptime"] = $row."Uptime".ToString()
#$spItem["DNSHostName"] = $row."DNSHostName".ToString()
#$spItem["DistinguishedName"] = $row."DistinguishedName".ToString()
$spItem.Update()
# This is just disconnecting from SharePoint
$spWeb.Dispose()
Enjoy, and if anyone has a better way of doing this I'm interested in knowing, thanks again
Thanks in Adavance

Similar Messages

  • How to execute powershell .ps1 file using sharepoint object model

    Hi All,
    Can some one please guide me, how can i execute .ps1 file with arguments using c# under sharepoint object model?
    MercuryMan

    Code example:
    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    runspace.Open();
    RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
    Pipeline pipeline = runspace.CreatePipeline();
    //Here's how you add a new script with arguments
    Command myCommand = new Command(scriptfile);
    CommandParameter testParam = new CommandParameter("key","value");
    myCommand.Parameters.Add(testParam);
    pipeline.Commands.Add(myCommand);
    // Execute PowerShell script
    results = pipeline.Invoke();
    See these links for more information:
    http://stackoverflow.com/questions/527513/execute-powershell-script-from-c-sharp-with-commandline-arguments
    http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C
    Blog | SharePoint Learnings CodePlex Tools |
    Export Version History To Excel |
    Autocomplete Lookup Field

  • Powershell script Information output in column instead of rows

    Dear All,
    I am required powershell script Information output  in column instead of rows.
    $usr= get-aduser -filter * | select sAMAccountName,homeDrive,TerminalServicesProfilePath,homeDirectory,physicalDeliveryOfficeName,userAccountControl,displayName,l,mail, profilepath
    $myarray = @()
    Foreach($usr1 in $usr)
    $userDN = (Get-ADUser $usr1.samaccountname).distinguishedName
    $userInfo = [ADSI]"LDAP://$userDN" | select sAMAccountName,homeDrive,TerminalServicesProfilePath,homeDirectory,physicalDeliveryOfficeName,userAccountControl,displayName,l,mail, profilepath
    $ts=$userInfo.TerminalServicesProfilePath
    $sn=$userInfo.samaccountname
    $hm=$userinfo.homeDrive
    $hd=$userinfo.homeDirectory
    $pd=$userinfo.physicalDeliveryOfficeName
    $ua=$userinfo.userAccountControl
    $dp=$userinfo.displayName
    $ll=$userinfo.l
    $ml=$userinfo.mail
    $pp=$userinfo.profilepath
    $myarray += New-Object psobject -Property @{
        Sam = $userInfo.samaccountname
        TerminalServicesProfilePath = $userInfo.TerminalServicesProfilePath
      homeDrive = $userinfo.homeDrive
        homeDirectory=$userinfo.homeDirectory
        physicalDeliveryOfficeName=$userinfo.physicalDeliveryOfficeName
        userAccountControl=$userinfo.userAccountControl
        displayName=$userinfo.displayName
         l=$userinfo.l
         mail=$userinfo.mail
         profilepath=$userinfo.profilepath
    $myarray |fl
    $myarray | Out-File "c:\final.txt"

    Hey this is such a sweet small script compared to everything else out there and I guess you can edit it to return any value you wish. One LARGE problem however: the TerminalServicesProfilePath comes back empty on all accounts regardless of whether the field
    is populated or not. This is basically because this setting is not stored in an Active Directory attribute but Terminal Services information is stored in the userParameters schema attribute as a BLOB.
    I got this script:
    $Users = ([ADSISearcher]"(&(objectCategory=person)(objectClass=user))").findall() | select path
    foreach ($user in $users) {
    $userSearch = [adsi]"$($user.path)"
    # get logon name
    $userSearch.psbase.InvokeGet(“SamAccountName”)
    # Profile Attributes
    $userSearch.psbase.InvokeGet("ProfilePath")
    # Remote Desktop Services Attributes
    $userSearch.psbase.InvokeGet("TerminalServicesProfilePath")
    which returns the value but the output is terribly unformatted. If we could integrate the two to ensure that it is correctly formatted, AND returns the TSProfile that would be awesome!
    Can anyone help me do that?
    Life is dangerous, no one has ever survived. So enjoy!
    Please do not tag an unrelated quesiton onto the end of an old and answered question.  Please read the forum guidelines before posting.
    We do not do custom scripts on demand.
    ¯\_(ツ)_/¯

  • Save output of powershell script to a SharePoint document library?

    Hi
    I've got the PS script below which scripts out our SQL replication so disaster recovery.  Is there a way to output this to a SharePoint document library so that way we can version control the file to keep multiple copies and it also avoids outputting
    this to a file share.  We would still need to have the files with the .sql extension format which is an allowed file type in our farm.
    Thanks
    #Load command-line parameters - if they exist
    param ([string]$sqlserver, [string]$filename)
    #Reference RMO Assembly
    [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Replication") | out-null
    [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Rmo") | out-null
    function errorhandler([string]$errormsg)
        writetofile ("-- Replication Script Generator run at: " + (date)) $filename 1
        writetofile ("-- [Replication Script ERROR] " + $errormsg) $filename 0
    function writetofile([string]$text, [string]$myfilename, [int]$cr_prefix)
        if ($cr_prefix -eq 1) { "" >> $myfilename }
        $text >> $myfilename
    function initializefile([string]$myfilename)
        "" > $myfilename
    trap {errorhandler($_); Break}
    #Deal with absent parameters
    [string] $hostname=hostname
    if ($sqlserver -eq "") {$sqlserver = read-host -prompt "Please enter the server name or leave blank for Hostname"}
    #if ($filename -eq "")  {$filename = read-host -prompt "Please enter the file name (eg 'c:\ReplicationBackupScript.sql')..."}
    if ($sqlserver -eq "")   {$sqlserver = $hostname}
    if ($filename -eq "")   {$filename = "d:\Rep\CreateReplication-$(get-date -format ddMMyyyy).sql"}
    # Clear file contents
    if (Test-Path  ($filename)) {Clear-Content $filename}
    $repsvr=New-Object "Microsoft.SqlServer.Replication.ReplicationServer" $sqlserver
    initializefile $filename
    # if we don't have any replicated databases then there's no point in carrying on
    if ($repsvr.ReplicationDatabases.Count -eq 0)
        writetofile ("-- Replication Script Generator run at: " + (date)) $filename 0
        writetofile "-- ZERO replicated databases on $sqlserver!!!" $filename 1
        EXIT
    # similarly, if we don't have any publications then there's no point in carrying on
    [int] $Count_Tran_Pub = 0
    [int] $Count_Merge_Pub = 0
    foreach($replicateddatabase in $repsvr.ReplicationDatabases)
            $Count_Tran_Pub = $Count_Tran_Pub + $replicateddatabase.TransPublications.Count
            $Count_Merge_Pub = $Count_Merge_Pub + $replicateddatabase.MergePublications.Count
    if (($Count_Tran_Pub + $Count_Merge_Pub) -eq 0)
        writetofile ("-- Replication Script Generator run at: " + (date)) $filename 0
        writetofile "-- ZERO Publications on $sqlserver!!!" $filename 1
        EXIT
    # if we got this far we know that there are some publications so we'll script them out
    # the $scriptargs controls exactly what the script contains
    # for a full list of the $scriptargs see the end of this script
    $scriptargs = [Microsoft.SqlServer.Replication.scriptoptions]::Creation `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludeEnableReplicationDB `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludeCreateLogreaderAgent `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludePublicationAccesses `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludeArticles `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludePublisherSideSubscriptions `
    -bor  [Microsoft.SqlServer.Replication.scriptoptions]::IncludeSubscriberSideSubscriptions
    writetofile ("-- Replication Script Generator run at: " + (date)) $filename 0
    writetofile "-- PUBLICATIONS ON $sqlserver" $filename 1
    writetofile "-- TRANSACTIONAL PUBLICATIONS ($Count_Tran_Pub)" $filename 1
    foreach($replicateddatabase in $repsvr.ReplicationDatabases)
        if ($replicateddatabase.TransPublications.Count -gt 0)
            foreach($tranpub in $replicateddatabase.TransPublications)
                writetofile "/********************************************************************************" $filename 0
                writetofile ("***** Writing to file script for publication: " + $tranpub.Name) $filename 0
                writetofile "********************************************************************************/" $filename 0
                [string] $myscript=$tranpub.script($scriptargs) 
                writetofile $myscript $filename 0
    writetofile "-- MERGE PUBLICATIONS ($Count_Merge_Pub)" $filename 1
    foreach($replicateddatabase in $repsvr.ReplicationDatabases)
        if ($replicateddatabase.MergePublications.Count -gt 0)
            foreach($mergepub in $replicateddatabase.MergePublications)
                writetofile "/********************************************************************************" $filename 0
                writetofile ("***** Writing to file script for publication: " + $mergepub.Name) $filename 0
                writetofile "********************************************************************************/" $filename 0
                [string] $myscript=$mergepub.script($scriptargs) 
                writetofile $myscript $filename 0

    Check out Using PowerShell to upload a scripts output to SharePoint
    Jason Warren
    @jaspnwarren
    jasonwarren.ca
    habaneroconsulting.com/Insights

  • How to run Powershell script (function) through Windows Task Schduler ??

    Hello All,
    i have Powershell script which is created as a function. I have to give parameters to run the script. And it is working fine. Now i want to run this script through windows task scheduler but it is not working. I dont know how to call powershell function
    through task scheduler.
    From command line i run it like this:
    . c:\script\Get-ServiceStatusReport.ps1
    dir function:get-service*
    Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
    In windows Task scheduler I am giving this: it runs but i dont receive any output :
    Program/Script:
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    Parameter:
    -file ". 'Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService  "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail  mail01.xxx.gov.pk'"
    Please HELP !!!

    Thanks for the reply:
    The script is already saved as Get-ServiceStatusReport.ps1 .
    On powershell it does not run like .\Get-ServiceStatusReport.ps1 (parameter).
    But i have to call it as function:
    Like this:
    Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
    As you said:
    I tried to run it like this:
    Program/Script:
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    Parameter:
    -file "c:\script\Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService  "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail  mail01.xxx.gov.pk'"
    But its not working , on scheduler its giving error: (0xFFFD0000)
    Please HELP !!!
    WHOLE SCRIPT:
    function Get-ServiceStatusReport
    param(
    [String]$ComputerList,[String[]]$includeService,[String]$To,[String]$From,[string]$SMTPMail
    $script:list = $ComputerList
    $ServiceFileName= "c:\ServiceFileName.htm"
    New-Item -ItemType file $ServiceFilename -Force
    # Function to write the HTML Header to the file
    Function writeHtmlHeader
    param($fileName)
    $date = ( get-date ).ToString('yyyy/MM/dd')
    Add-Content $fileName "<html>"
    Add-Content $fileName "<head>"
    Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"
    Add-Content $fileName '<title>Service Status Report </title>'
    add-content $fileName '<STYLE TYPE="text/css">'
    add-content $fileName "<!--"
    add-content $fileName "td {"
    add-content $fileName "font-family: Tahoma;"
    add-content $fileName "font-size: 11px;"
    add-content $fileName "border-top: 1px solid #999999;"
    add-content $fileName "border-right: 1px solid #999999;"
    add-content $fileName "border-bottom: 1px solid #999999;"
    add-content $fileName "border-left: 1px solid #999999;"
    add-content $fileName "padding-top: 0px;"
    add-content $fileName "padding-right: 0px;"
    add-content $fileName "padding-bottom: 0px;"
    add-content $fileName "padding-left: 0px;"
    add-content $fileName "}"
    add-content $fileName "body {"
    add-content $fileName "margin-left: 5px;"
    add-content $fileName "margin-top: 5px;"
    add-content $fileName "margin-right: 0px;"
    add-content $fileName "margin-bottom: 10px;"
    add-content $fileName ""
    add-content $fileName "table {"
    add-content $fileName "border: thin solid #000000;"
    add-content $fileName "}"
    add-content $fileName "-->"
    add-content $fileName "</style>"
    Add-Content $fileName "</head>"
    Add-Content $fileName "<body>"
    add-content $fileName "<table width='100%'>"
    add-content $fileName "<tr bgcolor='#CCCCCC'>"
    add-content $fileName "<td colspan='4' height='25' align='center'>"
    add-content $fileName "<font face='tahoma' color='#003399' size='4'><strong>Service Stauts Report - $date</strong></font>"
    add-content $fileName "</td>"
    add-content $fileName "</tr>"
    add-content $fileName "</table>"
    # Function to write the HTML Header to the file
    Function writeTableHeader
    param($fileName)
    Add-Content $fileName "<tr bgcolor=#CCCCCC>"
    Add-Content $fileName "<td width='10%' align='center'>ServerName</td>"
    Add-Content $fileName "<td width='50%' align='center'>Service Name</td>"
    Add-Content $fileName "<td width='10%' align='center'>status</td>"
    Add-Content $fileName "</tr>"
    Function writeHtmlFooter
    param($fileName)
    Add-Content $fileName "</body>"
    Add-Content $fileName "</html>"
    Function writeDiskInfo
    param($filename,$Servername,$name,$Status)
    if( $status -eq "Stopped")
    Add-Content $fileName "<tr>"
    Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$servername</td>"
    Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$name</td>"
    Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$Status</td>"
    Add-Content $fileName "</tr>"
    else
    Add-Content $fileName "<tr>"
    Add-Content $fileName "<td >$servername</td>"
    Add-Content $fileName "<td >$name</td>"
    Add-Content $fileName "<td >$Status</td>"
    Add-Content $fileName "</tr>"
    writeHtmlHeader $ServiceFileName
    Add-Content $ServiceFileName "<table width='100%'><tbody>"
    Add-Content $ServiceFileName "<tr bgcolor='#CCCCCC'>"
    Add-Content $ServiceFileName "<td width='100%' align='center' colSpan=3><font face='tahoma' color='#003399' size='2'><strong> Service Details</strong></font></td>"
    Add-Content $ServiceFileName "</tr>"
    writeTableHeader $ServiceFileName
    #Change value of the following parameter as needed
    $InlcudeArray=@()
    #List of programs to exclude
    #$InlcudeArray = $inlcudeService
    Foreach($ServerName in (Get-Content $script:list))
    $service = Get-Service -ComputerName $servername
    if ($Service -ne $NULL)
    foreach ($item in $service)
    #$item.DisplayName
    Foreach($include in $includeService)
    write-host $inlcude
    if(($item.serviceName).Contains($include) -eq $TRUE)
    Write-Host $item.MachineName $item.name $item.Status
    writeDiskInfo $ServiceFileName $item.MachineName $item.name $item.Status
    Add-Content $ServiceFileName "</table>"
    writeHtmlFooter $ServiceFileName
    function Validate-IsEmail ([string]$Email)
    return $Email -match "^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"
    Function sendEmail
    param($from,$to,$subject,$smtphost,$htmlFileName)
    [string]$receipients="$to"
    $body = Get-Content $htmlFileName
    $body = New-Object System.Net.Mail.MailMessage $from, $receipients, $subject, $body
    $body.isBodyhtml = $true
    $smtpServer = $MailServer
    $smtp = new-object Net.Mail.SmtpClient($smtphost)
    $validfrom= Validate-IsEmail $from
    if($validfrom -eq $TRUE)
    $validTo= Validate-IsEmail $to
    if($validTo -eq $TRUE)
    $smtp.UseDefaultCredentials = $true;
    $smtp.Send($body)
    write-output "Email Sent!!"
    else
    write-output "Invalid entries, Try again!!"
    $date = ( get-date ).ToString('yyyy/MM/dd')
    sendEmail -from $From -to $to -subject "Service Status - $Date" -smtphost $SMTPMail -htmlfilename $ServiceFilename

  • How to make powershell script.

    How to make script that copy content from notepad to other notepad and reverse the text?

    If you mean a .txt file then there's three aspects to your question.
    Open a file and read the text
    Reverse the text
    Save the text into a new file
    For point one, this technet article is good:
    http://technet.microsoft.com/en-us/library/ee692806.aspx
    For point two you could turn the text into one or more strings, then convert those into arrays, loop through them and then re-assemble them. This article shows you most of that:
    http://technet.microsoft.com/en-us/library/ee692804.aspx
    And finally you need to save that text as a file, there's lots of ways but the Out-File cmdlet is the simplest.
    This might also be of use:
    http://www.ehow.com/how_7174023_write-basic-powershell-script.html

  • How to add powershell script code in form application in C#

    Hi,
    i am creating a form application in C# and have powershell code which will create remote session on remote machine and execute few commands like set execution policy copy some share files install that files etc.
    I have to add this powershell script into form application in C#.
    Can some one please give me some example how to add the whole script which i have into C# code form application. Thanks in advance
    Thanks,

    Hi
    So the left is Run PowerShell Commands on Remote machine? Am I right ?
    Here  is a article talking about running  powershell commands on Remote Computers.
    http://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/
    About how to write in C#, please follow
    Joel Engineer's reply, using  process.Start() method  to start
    PowerShell.exe and Run PowerShell Commands to connect remote machine.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to export Fireworks image to MS Sharepoint

    I am building a SharePoint site and would like to know how to export the image I created in fireworks to SharePoint.  As of right now, I can export the image to the SharePoint home page, but none of the links are in tact.
    Can anyone tell me how to export the image I have created in Firework, along with the links, to the SharePoint home page???

    You did not understand my question or do not have an understanding of SharePoint or Fireworks.
    I am building an image on the home page of the SharePoint site.  I need have the user click on sections of the image to take them to certain places within the SharePoint site.  The image has been built.  The links to the pages have been added to the images with rollovers, using Adobe Fireworks.  I need to take that image, with the links and rollovers, and move that to my SharePoint home page.
    As of right now I can only move the image, but the links and rollovers do not go with it.  I have added it to a 'page viewer' web part on the Sharepoint, but all the actions take place just withing the page viewer web part, rather than moving the entire browser to the selected page.
    Can anyone help with this?

  • How to Excute powershell scripts from C#

    hi all,
    I am using Exchange server 2013, i am getting Users list in powershell using the command
    Get-Mailbox -ResultSize Unlimited | Select Name,Alias,RecipientTypeDetails | Export-Csv c:\Users.csv
    i need to get through this C# code.
    I am trying with following code , but i am getting error
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    PowerShell powershell = PowerShell.Create();
    PSCommand command = new PSCommand();
    powershell.AddCommand("Get-Mailbox");
    powershell.AddParameter("ResultSize", "Unlimited");
    powershell.Runspace = runspace;
    Collection<PSObject> results = powershell.Invoke();
    I am running code in directly in server, so no need to setup Remote powershell session.
    by running above code i am getting error below
    The term 'Get-Mailbox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again

    Hi DareDevil57,
    Thanks for reply.
    i Created new user[ExchangeAdmin] by giving full Access permissions of all users. but still i am not getting list of MailBoxes  in Exchange server.
    SecureString secureString = new SecureString();
    string myPassword = "EIS2014!@#"; string username = "[email protected]";
    foreach (char c in myPassword)
    secureString.AppendChar(c);
    PSCredential ExchangeCredentials = new PSCredential(username, secureString);
    WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://ExchangeServer.admin.com/powershell ), "http://schemas.microsoft.com/powershell/Microsoft.Exchange , ExchangeCredentials);
    Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
    runspace.Open();
    string newCommand = "Get-Mailbox -ResultSize Unlimited";
    Pipeline cmd = runspace.CreatePipeline(newCommand);
    Collection<PSObject> results = cmd.Invoke();
    runspace.Close();
    how can i get list of all Mailboxes in C# code ?

  • How to export all the site files to the new computer

    I'll be buying a new computer soon and need to export all the
    site files (usernames and passwords) to that. I know how to export
    individual site information, but the passwords are encrypted. Also,
    is there way to save all sites at once and then just transfer that
    to the new machine?

    This is a multi-part message in MIME format.
    ------=_NextPart_000_0039_01C852A0.8D4985F0
    Content-Type: text/plain;
    charset="iso-8859-1"
    Content-Transfer-Encoding: quoted-printable
    Choose Site > Manage Sites and then use the Export feature
    in the Site =
    Manager. You'll have an option to export all settings
    (including =
    username and password). DW stores them in .ste files, which
    you can =
    later use the Site Manager to Import.=20
    By the way, the Import/Export features work with multiple
    files, just do =
    a multi-select before clicking the Export button and select
    multiple =
    .ste files when importing.
    Best - Joe
    Joseph Lowery
    Vice President of Marketing, WebAssist
    Author of Dreamweaver CS3 Bible
    "Mikkola" <[email protected]> wrote in
    message =
    news:[email protected]...
    > I'll be buying a new computer soon and need to export
    all the site =
    files=20
    > (usernames and passwords) to that. I know how to export
    individual =
    site=20
    > information, but the passwords are encrypted. Also, is
    there way to =
    save all=20
    > sites at once and then just transfer that to the new
    machine?
    >
    ------=_NextPart_000_0039_01C852A0.8D4985F0
    Content-Type: text/html;
    charset="iso-8859-1"
    Content-Transfer-Encoding: quoted-printable
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
    Transitional//EN">
    <HTML><HEAD>
    <META http-equiv=3DContent-Type content=3D"text/html; =
    charset=3Diso-8859-1">
    <META content=3D"MSHTML 6.00.6000.16587"
    name=3DGENERATOR>
    <STYLE></STYLE>
    </HEAD>
    <BODY>
    <DIV><FONT face=3DArial size=3D2>Choose Site
    &gt; Manage Sites and then =
    use the=20
    Export feature in the Site Manager. You'll have an option to
    export all =
    settings=20
    (including username and password). DW stores them in .ste
    files, which =
    you can=20
    later use the Site Manager to Import.
    </FONT></DIV>
    <DIV><FONT face=3DArial
    size=3D2></FONT> </DIV>
    <DIV><FONT face=3DArial size=3D2>By the way, the
    Import/Export features =
    work with=20
    multiple files, just do a multi-select before clicking the
    Export button =
    and=20
    select multiple .ste files when
    importing.</FONT></DIV>
    <DIV><FONT face=3DArial
    size=3D2></FONT> </DIV>
    <DIV><FONT face=3DArial size=3D2>Best -
    Joe</FONT></DIV>
    <DIV><FONT face=3DArial
    size=3D2></FONT> </DIV>
    <DIV><FONT face=3DArial size=3D2>Joseph
    Lowery<BR>Vice President of =
    Marketing, <A=20
    href=3D"
    http://www.webassist.com">WebAssist</A><BR>Author
    of <A=20
    href=3D"
    http://www.idest.com/dreamweaver/">Dreamweaver
    CS3 =
    Bible</A></FONT></DIV>
    <DIV><FONT face=3DArial
    size=3D2></FONT> </DIV>
    <DIV><FONT face=3DArial size=3D2>"Mikkola"
    &lt;</FONT><A=20
    href=3D"mailto:[email protected]"><FONT
    face=3DArial=20
    size=3D2>[email protected]</FONT></A><FONT
    face=3DArial =
    size=3D2>&gt; wrote=20
    in message </FONT><A =
    href=3D"news:[email protected]"><FONT=20
    face=3DArial =
    size=3D2>news:[email protected]</FONT></A><FONT=20
    face=3DArial size=3D2>...</FONT></DIV><FONT
    face=3DArial size=3D2>&gt; =
    I'll be buying a=20
    new computer soon and need to export all the site files
    <BR>&gt; =
    (usernames and=20
    passwords) to that. I know how to export individual site
    <BR>&gt; =
    information,=20
    but the passwords are encrypted. Also, is there way to save
    all <BR>&gt; =
    sites=20
    at once and then just transfer that to the new=20
    machine?<BR>&gt;</FONT></BODY></HTML>
    ------=_NextPart_000_0039_01C852A0.8D4985F0--

  • Powershell - input information in script that is sent to a list in Sharepoint

    I got this question from a co-worker of mine. Today we sit on a wss 3.0 installation which acts as a management portal.
    Here we have an event log list, where we post events/changes. He is regulary using powershell, and would like to sit here and create the log events, filling out stuff like title, description. The rest of the information whatever that may be, like person
    filling out the log, date, tag the item as an event should be autofilled, and then sent to a SharePoint Foundation 2013 list.
    Is this possible? I was thinking that the best solution for him, would then be to have some kind of PowerShell GUI?? When he then press save/send, it is automatically sent to the correct list in SharePoint.

    Hi,
    You can create a windows application that will execute your powershell script. Below link might help:
    http://blogs.msdn.com/b/kebab/archive/2014/04/28/executing-powershell-scripts-from-c.aspx
    Best Regards,
    Brij K

  • How to Export Team Site Site Pages to .aspx and for subsequent upload to other Team Site and Web Part Customisation included. (Powershell)

    Hi guys,
    Can i please technically know how to export an .aspx file (in Site Pages library of a team site) to local file?
    Basically, SharePoint Designer has this feature "Export File"
    i Need exactly the same feature that can be done in Powershell
    I tried the following
    $web = get-spweb "MY URL"
    $folder = $web.GetFolder("SitePages")
    $files = $folder.files
    #trying to download the first file
    [System.IO.File]::WriteAllBytes("C:\\LocalPath",$files[0].OpenRead(),$true)
    The file exported via this method is Clean HTML without the Web Part Customisation!
    I NEED the web part customisation in the exported files.
    Sample downloaded via above script
    <!-- Cropping -->
    <tr>
    <td id="_invisibleIfEmpty" name="_invisibleIfEmpty" valign="top" height="100%"> <WebPartPages:WebPartZone runat="server" Title="loc:LeftColumn" ID="LeftColumn" FrameType="TitleBarOnly"/> </td>
    <td id="_invisibleIfEmpty" name="_invisibleIfEmpty" valign="top" height="100%"> <WebPartPages:WebPartZone runat="server" Title="loc:MiddleColumn" ID="MiddleColumn" FrameType="TitleBarOnly"/> </td>
    <td id="_invisibleIfEmpty" name="_invisibleIfEmpty" valign="top" height="100%"> <WebPartPages:WebPartZone runat="server" Title="loc:RightColumn" ID="RightColumn" FrameType="TitleBarOnly"/> </td>
    </tr>
    <!-- Cropping -->
    I tried using WebRequest, it returns the  End HTML, which is not working too.
    Please if anyone has done this? Or is there any SharePoint Designer Developer here and is willing to share how to perform the export in SharePoint Designer via Powershell? API available?
    Much Appreciated!
    Cheng

    Hi,
    According to your post, my understanding is that you wanted to export Team Site Site Pages to .aspx and for subsequent uploaded to other Team Site and Web Part Customisation included using Powershell.
    You can export a specific file or object from the Export-SPWeb context.
    Export-SPWeb -identity "http://sharepoint" -ItemUrl "/default.aspx"  -Path "c:\default.aspx"
    Import-SPWeb -identity "http://sharepoint" -Path "C:\default.aspx"
    Here is a similar thread for you to take a look at:
    http://sharepoint.stackexchange.com/questions/56664/how-to-download-a-sharepoint-aspx-page-from-server-using-powershell
    More information:
    http://technet.microsoft.com/en-us/library/ee428301(v=office.14).aspx
    Best Regards,
    Linda Li
    Linda Li
    TechNet Community Support

  • Get the daily incremental search crawl information using PowerShell script

    Dear Friends ,
        I want to get the daily incremental search crawl information using PowerShell script . I need this information into CSV or txt format . Can you please help me with this.
    valmiki

    Hi
    I  have got the below script which worked .
    ## SharePoint Reference
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration")
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.Search.Administration")
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.Search")
    [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
    function global:Get-CrawlHistory($url)
    trap [Exception] {
    write-error $("ERROR: " + $_.Exception.GetType().FullName);
      write-error $("ERROR: " + $_.Exception.Message);
      continue;  
    $s =
    new-Object Microsoft.SharePoint.SPSite($url);
    $c = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($s);
    $h =
    new-Object Microsoft.Office.Server.Search.Administration.CrawlHistory($c);
    Write-OutPut $h.GetCrawlHistory();
    $s.Dispose();
    Get-CrawlHistory
    -url  http://your_site_url/
      |
    Export-CsvF:\temp\search.csv
    valmiki

  • SharePoint PowerShell script to open Excel.Application on Windows server 2008 R2

    Hi
    I am building a PowerShell script to open an Excel file store on SharePoint document library.  Sound simple enough but I just couldn't get over an error and hopefully someone can help give an answer here.
    I have found many sample codes to use.  All of the sample codes show that a new object must be created for Excel application
    like ($Excel = New-Object -comobject Excel.Application) before that excel file can be read.
    When I run this comand on a SharePoint server (Windows 2008 R2) either inside the script or by itself I keep getting the following error:
     New-Object : Cannot load COM type Excel.Application.
    + $excel = New-Object <<<<  -Com Excel.Application
        + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    For the test,  I ran this comand on a Windows 7 with MS Office applications installed,  then it ran fine.
    Is that because I don't have Office application (Excel) installed on the server to run this or some services need to be turned on?
    From the sample codes, look like I should be able to run it on the Server with SharePoint installed.
    Thanks for any advice or solution to resolve my issue.
    Swanl

    So I'm assuming this won't return anything either?
    Get-WMIObject Win32_ClassicCOMClassSetting | ? {$_.VersionIndependentProgId -like 'excel.application'}
    You need Office/Excel installed on the server because you're accessing those .DLLs for the automation functionality, but depending on what you're trying to do you may be able to use one of the office viewers:
    http://www.microsoft.com/en-us/download/details.aspx?id=10 although I'm not sure how much of the com (if any) is exposed in a viewer install.  if Office is not possible due to
    budget reasons, I believe there are several 3rd party providers who can produce a com object that will handle Excel formats.

  • How to give readonly Permission rights to 1000 users with button using powershell script?

    $site = Get-SPSite
    -Identity "http://mysite/"
    $user = Get-SPUser
    -Identity "mydomain\myuser"
    -Web $site.RootWeb
    $assignment = New-Object
    Microsoft.SharePoint.SPRoleAssignment($user)
    $role = $site.RootWeb.RoleDefinitions[[Microsoft.SharePoint.SPRoleType]::Reader]
    $assignment.RoleDefinitionBindings.Add($role);
    foreach ($web in $site.AllWebs)
        if ($web.HasUniquePerm)
            $web.RoleAssignments.Add($assignment)
    With above script I can give Readonly permission to the users...but at a time I can give permission to only one user...Actually 1000 users requires these permissionMy requirement is I will have a textbox and a button.I will enter username in textbox
    and when i clicked button the required permission should be assigned to the user given in the textbox...can you please tell how can i achieve this........how make to run powershell script when button is clicked.

    Hello,
    Instead of applying security to user level, it'll be better to create a SharePoint group where you will add the users. and use the outof the box interface to give permissions.
    and for your button, just add the direct link to add user
    http://serverurl/_layouts/15/aclinv.aspx?GroupId=7&IsDlg=1 
    replacing the group ID by the id of your new group (you can see it in the url when your are in the group)
    Best regards, Christopher.
    Blog |
    Mail
    Please remember to click "Mark As Answer" if a post solves your problem or
    "Vote As Helpful" if it was useful.
    Why mark as answer?

Maybe you are looking for

  • Can you use two Time Capsules and back up both with Time Machine.

    My little iMac hard drive (250GB) is quickly filling up with my iTunes library (180GB). I have a 500GB Time Capsule which I use to back up my system via Time Capsule. I would like to move my iTunes library to an external hard drive. If I add the 1TB

  • How to get a save-enabled PDF Signature Form on SharePoint

    Hello all, My first time posting. I did numorous searches and watched every training video I can find, but I have been unable to successfully complete this task. I have a PDF form, it is an approval sheet that must be maintaind for the entire lifecyl

  • LM61 Unpack HU Materials or HU from HU

    Hi Please see attachment LM61 Unpack Screen flow. It should allow me to Unpack, but I get an error "Handling unit &1 not found in the warehouse". The HU does exist and the error message is not correct. Could someone please advise how to Unpack in RF?

  • Problem calling a jre7 class from jni

    Hi, We have a class in java 7 and need to load it from a native code. The system already load some classes in java 6 with JNI, needing an upgrade. I install the new JDK, change include directories and link references in my VC project. All was well, u

  • How to Create Tag Cloud using Flex

    Hi I am trying to create Tag cloud using Adobe Flex. Can you please give me a hint of how to proceed. Any hint will be a help. Thanks, Dev