Powershell Patching Information: Problems using Export-CSV / looping

I've made a simple script that obtains patching information from a series of servers.
The csv file I use to reference my servers is called patchlevels.csv and just contains some basic information.
ServerName,OS,ServicePack,Patches,,,,,,,
SERVER1,Server 2003 R2 Enterprise,SP2,,,,,,,,
SERVER2,Server 2003 R2 Enterprise X64 Edition,SP2,,,,,,,,
Yup, that's exactly as its formatted ^
The problem I am having is updating the Patches column with a link to the server-specific htm file (I figure I can always save as xlsx within Excel to get clickable hyperlinks). I have failed multiple times over the last few hours using
export-csv to try and update the Patches cell(s).
Here is my script minus any failed export-csv references for clarity's sake:
$currentPath = "$pwd\"
$HostFileName = "patchlevels.csv"
$CSVLoc = $currentPath + $HostFileName
Import-Csv "$CSVLoc" | ForEach-Object {
Write-Host "Processing..."
Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
$ServerName=$_.ServerName
$ServerFile = "$ServerName.htm"
$OS=$_.OS
$ServicePack=$_.ServicePack
$_.Patches = $_.Patches.replace("[","$ServerFile")
Write-Host "Server Name: $ServerName"
Write-Host "Operating System: $OS"
Write-Host "Service Pack: $ServicePack"
Write-Host "Processing Patch List"
wmic /node:$ServerName /output:$ServerName.htm qfe list
Write-Host "Patch List generated for $ServerName"
Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
Write-Host "END PROCESSING"
I can see two things that may be wrong:
1) Formatting of my CSV file (,,,,,,)
2) I am not sure about the formatting of $_.Patches = $_.Patches.replace("[","$ServerFile")
And obviously, I'm missing the export-csv commands to update the patchlevels.csv file with the htm file location (which is what this entire post is about).
Where would I put export-csv in this code to update my original csv as the script runs?
Thanks in advance for any help with this.
Kind Regards,
Stephen

I've modified the script so that it now actually works as I want it to (more-or-less).
I will look into using Get-Hotfix instead of WMIC to check that I am happy with the returned data.
Modified CSV (I changed the Patch column to a known value to simplify replace operation, I couldn't figure out how to replace " "):
ServerName,OS,ServicePack,Patches,,,,,,,
SERVER1,Server 2003 R2 Enterprise,SP2,None,,,,,,,
SERVER2,Server 2003 R2 Enterprise X64 Edition,SP2,None,,,,,,,
Working code.
$currentPath = "$pwd\"
$HostFileName = "patchlevels.csv"
$CSVLoc = @()
$CSVLoc = $currentPath + $HostFileName
Import-Csv "$CSVLoc" | ForEach-Object {
Write-Host "Processing..."
Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
$ServerName=$_.ServerName
$ServerFile = "$ServerName.htm"
$OS=$_.OS
$ServicePack=$_.ServicePack
Write-Host "Server Name: $ServerName"
Write-Host "Operating System: $OS"
Write-Host "Service Pack: $ServicePack"
Write-Host "Processing Patch List"
wmic /node:$ServerName /output:$ServerFile qfe list
Write-Host "Patch List generated for $ServerName"
Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
Write-Host "END DATA GATHERING"
Write-Host "Updating CSV File"
$update = Import-Csv "$CSVLoc"
$update | ForEach-Object {
$ServerName=$_.ServerName
$ServerFile = "$ServerName.htm"
$_.Patches = $_.Patches.replace("None",$currentpath + $ServerFile)
$update | Export-Csv $CSVLoc -NoTypeInformation -Force
Write-Host "OPERATION COMPLETE"
Thanks,
Stephen

Similar Messages

  • Problem using Export in Oracle 8.1.6.

    Hi,
    I have a problem using export utility in oracle 8i.
    I got a message:
    EXP-00056: ORACLE error 942 encountered
    ORA-00942: table or view does not exist
    EXP-00000: Export terminated unsuccessfully
    I tried running CATPROC.sql and CATEXP.sql but it did not correct the problem.
    Please help me.
    Thanks

    You may want to try using the error lookup tool available here, http://otn.oracle.com/pls/tahiti/tahiti.homepage?remark=tahiti You may be able to find the answer even though the error lookup tools is for 8.1.7 version. Otherwise, you can search the db discussion forums to see if this issue has been discussed already.

  • 2 different problems using Export Action

    I'm using LR 1.1 and Photoshop CS3 on a MacPro and PowerBook. I created an identical Action in PS to use as an Export Action in LR. It was to export .dng files, open them, run Noise Ninja (many were high ISO shots), and some other things.
    On one Mac, the files would only open in Adobe Raw Converter, so I'd still have to click to go further for each. With the other, I'd get an error message immediately in Photoshop once the file opened, saying "Feather Command not available". (I had done nothing consciously in creating the Actions (later Droplets) to put in such a command.
    My guest teacher, who knows Photoshop (and Lightroom) far better than I, knows of now reason why such a "feather" error would come up.
    Any reason why an Action written to be identical except for where the files are ultimately saved should work so differently on 2 Macs (both with OS 10.4.9)? Or how I can cure these problems? I'd love to be able to write more Actions to Droplets I can use as Export Actions from LR. (And some I've written *do* work, just not the last couple...)

    I've modified the script so that it now actually works as I want it to (more-or-less).
    I will look into using Get-Hotfix instead of WMIC to check that I am happy with the returned data.
    Modified CSV (I changed the Patch column to a known value to simplify replace operation, I couldn't figure out how to replace " "):
    ServerName,OS,ServicePack,Patches,,,,,,,
    SERVER1,Server 2003 R2 Enterprise,SP2,None,,,,,,,
    SERVER2,Server 2003 R2 Enterprise X64 Edition,SP2,None,,,,,,,
    Working code.
    $currentPath = "$pwd\"
    $HostFileName = "patchlevels.csv"
    $CSVLoc = @()
    $CSVLoc = $currentPath + $HostFileName
    Import-Csv "$CSVLoc" | ForEach-Object {
    Write-Host "Processing..."
    Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
    $ServerName=$_.ServerName
    $ServerFile = "$ServerName.htm"
    $OS=$_.OS
    $ServicePack=$_.ServicePack
    Write-Host "Server Name: $ServerName"
    Write-Host "Operating System: $OS"
    Write-Host "Service Pack: $ServicePack"
    Write-Host "Processing Patch List"
    wmic /node:$ServerName /output:$ServerFile qfe list
    Write-Host "Patch List generated for $ServerName"
    Write-Host "------------------------------------------------------------" -ForegroundColor Yellow
    Write-Host "END DATA GATHERING"
    Write-Host "Updating CSV File"
    $update = Import-Csv "$CSVLoc"
    $update | ForEach-Object {
    $ServerName=$_.ServerName
    $ServerFile = "$ServerName.htm"
    $_.Patches = $_.Patches.replace("None",$currentpath + $ServerFile)
    $update | Export-Csv $CSVLoc -NoTypeInformation -Force
    Write-Host "OPERATION COMPLETE"
    Thanks,
    Stephen

  • Another Problem Using Export.bat

    hi all:
    I use Export.bat to export pages from server.But there is thread come up:
    "/oracle/apps/ap/oie/webui/OIEACTIVEEXPENSEREPSMAINPAGE.Oiebuttonsy "Extends" on component "/oracle/apps/ap//regionMap/OIEACTIVEEXPREPSBUTTONS" component "/oracle/apps/ap/oie/webui/OIEACTIVEEXPENSEREPSMAINPAGE.OieBUTTONS can not be referenced from "/oracle/apps/ap//regionMap/OIEACTIVEEXPREPSBUTTONS because it violates scope restrictions.
    Any Ideas wiil appreciate?
    Edited by: jerry.an on 2009-7-29 下午8:56

    You may want to try using the error lookup tool available here, http://otn.oracle.com/pls/tahiti/tahiti.homepage?remark=tahiti You may be able to find the answer even though the error lookup tools is for 8.1.7 version. Otherwise, you can search the db discussion forums to see if this issue has been discussed already.

  • How to use Export-csv

    I have a loop at the end of my script which writes a bunch of stuff to the command window
    foreach($i in $hash.keys){
    write-host "Hostname: $i" ;
    Write-host "Template:" "$($hash.$i)";
    $objIwsList = $iwsObjSearcher.findAll() |
    foreach-object{
    $tmp_name = ($_.Properties.Item("distinguishedName")[0].split(',=')[3]);
    $tmp_device = ($_.Properties.Item("Vps-deviceTemplate")[0].toString().split(',=')[1])|
    where-object{$tmp_name -eq $hash.$i
    if($tmp_device -ne $null){write-host "Device:" $tmp_device}
    I'd like to export this to a CSV file but I can't figure out how to do it. It seems from all the examples I've found that you need to pass the export at the end of the pipeline? I can't just wrap this whole forloop within the export, eh?
    Any help would be appreciated.

    I've also noticed that you don't end the statements with semi-colons? Aren't you supposed to? After things like:
    $props.Device=$null
    Shouldn't it be:
    $props.Device=$null;
    As there is more than one statement running in that block? Anyhow, I'll continue to work away at it and see if there's something I can use in PS1 that will do the same thing as your -property switch.
    Thanks
    I recommend a basic book or course in PowerSHell. YTOu are not using V1 unless you are on XP.  All current versions use -property on New-Object.
    Seli-colons are not used in PowerShell and are seen as white space except in a hash where they are terminators.
    $hash=@{A=1;B-2}
    Same as:
    $hash=@{
         A=1
         B=2
    Trying to use PowerSHell by gueesing at how it works from what you see on teh Internet is a very unuseful way of learning.  It will only lead you to wrong assumptions.
    Use "$host.Version" to get the correct version.
    All current versions of PS use PS1 extension and live in the "C:\Windows\System32WindowsPowerShell\v1.0" folder.
    ¯\_(ツ)_/¯

  • Problems with Exporting CSV files

    When I tried to export the Project Management Sample Table, I noticed that the last five unchecked check boxes weren't part of the exported file. I should have seen the value False. Instead there was no value provided. This seems like a bug.
    1019,Cell Editing,Text & Cell Styling ,"Font styling (Bold, Underline, Italic), Background color, Alignment, Cell border",Future,Hickey,Woodmansee,160,150,Within Budget,
    1020,Formulas,Robust formula engine  ,"Support for significantly more math, statistics, financial and logical formulas",Enhancement,Qualizza,Woodmansee,120,130,Over Budget,
    1021,Formulas,Formula copy and paste,Ability to reuse a formula by simply copying 'n pasting it in a different cell,Future,Qualizza,Woodmansee,30,25,Within Budget,
    1022,Cell Editing,Hyperlinks,Recognize http or WWW in text and make it clickable,Future,Rein,Parmar,40,30,Within Budget,
    1023,Cell Editing,Choice List,Select a value from a pre-specified list of choices in a column,Future,DeHoyos,Parmar,40,30,Within Budget,

    I have just replicated this issue with the Excel export as well.

  • Problem using Export PDF

    i have just purchased another copy of Adobe ExportPDF annual online however when i try to convert a PDF to Word, it wont let me sign in ???

    Hi Rob,
    I apologize for the trouble. Have you since been able to sign in? It can take up to 24 hours to provision when a new subscription is purchased.
    Let me know!
    Looking forward to hearing back from you.
    Kind regards, Stacy

  • Problem while exporting a report using CSV

    Dear friends / experts ,
    after successful genration of report my end users want to export that report i.e
    while exporting a report in portal using " Export CSV" option , am getting CSV file as semicolon ( seperated instead coma(,)
    please help me where can i change those settings to achive this CSV file with coma separated.
    thanks in advance..
    regards
    anand

    Check the below link
    http://help.sap.com/saphelp_smehp1/helpdata/en/d2/11a28fc26d4042a6d230a9783152f2/content.htm
    [Steps to change the delimiter in csv export WAD or portal|http://forums.sdn.sap.com/thread.jspa?threadID=1988651]
    To set the field separator, go to SPRO and choose
    -> SAP Reference IMG
        -> SAP Customizing Implementation Guide
             -> SAP NetWeaver
                  -> Business Intelligence
                       -> Links to Other Source Systems
                            -> Connection Between Flatfile and BI System
                                     -> Set options for uploading flat files
    Regards
    KP
    Edited by: Konduru Prashanth. on Feb 29, 2012 3:13 PM

  • 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

  • Export-csv output maximum row size

    Hi all. May I know the maximum row size that can output to .csv using 'export-csv'??

    There's no limit on writing to a CSV file.
    You can try:
    # max rows to export to CSV:
    $i=0
    While ($true) { #Forever
    $i++
    $i
    "Some text" | Export-Csv -Path .\test12.csv -Append -NoTypeInformation
    until you run out of disk space, which may take a while. A million lines using the above script makes a 5 BM file..
    Now reading it back is an entirely different story. Try
    Delimit..
    Sam Boutros, Senior Consultant, Software Logic, KOP, PA http://superwidgets.wordpress.com (Please take a moment to Vote as Helpful and/or Mark as Answer, where applicable)

  • Export CSV Cmdlet goes to infinite loop

    I'm trying to aggregate data from various CSV's into one using the following line of code
    “ ls -n *.csv | %{ ipcsv $_} | epcsv allinone.csv -NoTypeInformation “ 
    It worked fine until I changed the exported csv name to OneWorldFile.csv. It looks like PS lands into an infinite loop and appends the data into the CSV. I’ll have to eventually halt the process.
    “ ls -n *.csv | %{ ipcsv $_} | epcsv OneWorldFile.csv -NoTypeInformation “
    Here is the screenshot for your verification : http://note.io/1pNoee3. Is there any reason for this behaviour? Did I miss something?
    Thank you in advance for your reply.
    Vimal.

    Thank you, Noah.  I've understood what causes this behaviour -> Parallel Processing.
    I did get an interesting reply from powershell.org forum (http://bit.ly/Tzoy3R) and the problem sorts out if pipeline is not used. Thanks to Mike F Robbins.
    Import-Csv-Path(Get-ChildItem-Name*.csv)|Export-Csv-Path .\OneWorldFile.csv-NoTypeInformation
     

  • How to add SaveFileDialog to PowerShell Get-ADUser Export-CSV

    Hi,
    I am having a bit of difficulties with getting the SaveFileDialog to work when I use the Get-ADUser export-CSV.
    Current code:
    $handler_Output_Click=
    $User = Get-Aduser $textBox1.Text -Properties DisplayName,sAMAccountName,EmailAddress,Mobile,Company,Title,Enabled,LockedOut,Description,Created,Modified,LastLogonDate,AccountExpirationDate,AccountLockoutTime,BadLogonCount,CannotChangePassword,LastBadPasswordAttempt,PasswordLastSet,PasswordExpired,LogonWorkstations,CanonicalName | Select DisplayName,sAMAccountName,EmailAddress,Mobile,Company,Title,Enabled,LockedOut,Description,Created,Modified,LastLogonDate,AccountExpirationDate,AccountLockoutTime,BadLogonCount,CannotChangePassword,LastBadPasswordAttempt,PasswordLastSet,PasswordExpired,LogonWorkstations,CanonicalName | Export-CSV C:\temp\test.csv -NoTypeInformation ';' -encoding utf8
    $richTextBox1.Text = "A file 'test.csv' has been created to C:\temp\ based on the user: $($textBox1.Text)"
    Here a specific filename is already defined and I have to edit the code each time I want a different filename.
    It would be perfect if I could implement the SaveFileDialog box so I have the ability to name the file before saving and possibly even have the option to select the file type (among .CSV and All files).
    This it the export/output button itself:
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 502
    $System_Drawing_Point.Y = 38
    $Output.Location = $System_Drawing_Point
    $Output.Name = "Output"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 23
    $System_Drawing_Size.Width = 85
    $Output.Size = $System_Drawing_Size
    $Output.TabIndex = 2
    $Output.Text = "Export as file"
    $Output.UseVisualStyleBackColor = $True
    $Output.add_Click($handler_Output_Click)
    # $form1.AcceptButton = $Output
    $Output.DataBindings.DefaultDataSourceUpdateMode = 0
    $form1.Controls.Add($Output)
    And in the beginning of my script I also have defined the following:
    [System.Windows.Forms.Application]::EnableVisualStyles();
    [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
    [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
    [reflection.assembly]::loadwithpartialname("System.Windows.Forms.SaveFileDialog") | Out-Null
    And also:
    $Output = New-Object System.Windows.Forms.Button
    Any ideas how can I implement the SaveFileDialog so when I press the "Export as file" button the PowerShell command "Get-Aduser $textBox1.Text -Properties DisplayName,sAMAc..." is ran and I can choose the file name from a pop-up
    dialog box where to save the file and also put a filename? Currently I have to edit the code in order to assign a new file name (or go rename the file from that location).
    Thank you in advance,
    Henri
    EDIT:
    I know that the below is the answer to the SaveFileDialog, however I cannot imagine how I could implement it to my script into the "Get-Aduser $textBox1.Text -Properties a,b,c,d | select a,b,c,d | Export-CSV C:\temp\test.csv" cmdlet.
    Function Get-SaveFile($initialDirectory)
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
    Out-Null
    $SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
    $SaveFileDialog.initialDirectory = $initialDirectory
    $SaveFileDialog.filter = "All files (*.*)| *.*"
    $SaveFileDialog.ShowDialog() | Out-Null
    $SaveFileDialog.filename

    Just run the dialog before exporting the file.  Why is that a problem?
    \_(ツ)_/
    It works now! I made some modifications and it works. Thank you very much for the advice.
    $handler_Output_Click={
    Add-Type -AssemblyName System.Windows.Forms
    $SaveAs1 = New-Object System.Windows.Forms.SaveFileDialog
    $SaveAs1.Filter = "CSV Files (*.csv)|*.csv|Text Files (*.txt)|*.txt|Excel Worksheet (*.xls)|*.xls|All Files (*.*)|*.*"
    $SaveAs1.SupportMultiDottedExtensions = $true;
    $SaveAs1.InitialDirectory = "C:\temp\"
    if($SaveAs1.ShowDialog() -eq 'Ok'){
    $User = Get-Aduser $textBox1.Text -Properties DisplayName,sAMAccountName,EmailAddress,Mobile,Company,Title,Enabled,LockedOut,Description,Created,Modified,LastLogonDate,AccountExpirationDate,AccountLockoutTime,BadLogonCount,CannotChangePassword,LastBadPasswordAttempt,PasswordLastSet,PasswordExpired,LogonWorkstations,CanonicalName | Select DisplayName,sAMAccountName,EmailAddress,Mobile,Company,Title,Enabled,LockedOut,Description,Created,Modified,LastLogonDate,AccountExpirationDate,AccountLockoutTime,BadLogonCount,CannotChangePassword,LastBadPasswordAttempt,PasswordLastSet,PasswordExpired,LogonWorkstations,CanonicalName | Export-CSV $($SaveAs1.filename) -NoTypeInformation ';' -Encoding UTF8
    $richTextBox1.Text = "A file $($SaveAs1.filename) has been created based on the user: $($textBox1.Text)"

  • Problem using local variable in event loop

    I have a state machine from which I want to monitor various controls, including "Start" and "Stop" buttons.  Not every state needs to monitor the controls.  At present, most states run timed loops.  In the first state that reads the front panel, I have an Event structure (inside a While loop) that monitors the various controls' Change Value events.  For numeric controls, I update variables (in shift registers) as needed.  The "Start" button is used to end the While loop controlling the Event structure, allowing the State to exit to the next state.
    My problem comes in subsequent states that employ this same idea.  Here, I put a Local Variable bound to the Start button and use the same code, but it frequently happens that when I enter this particular state, I cannot "turn on" the control -- I push the button, but it stays off.  Curiously, if it was On when I enter, I can turn it off, but then I'm stuck not being able to turn it on.
    I mocked up a very simply routine that illustrates this.  There are two sequences (corresponding to the two states).  Both use an Event loop with a local variable bound to my Stop button (really this is an LED control with custom colors).  I've deliberately moved the "initialization" (the declaration of the control in the block diagram) out of the Event loops -- putting it inside the first loop modifies the behavior in another strange way.
    Here's my thinking on how I would expect this to work:  The code outside Event Loop 1 should have little effect.  Assume the Stop button is initially Off.  You will "sit" in Event Loop 1 until you push the Stop button, changing its value to True; this value will be passed out of the Event case and cause the first While loop to exit.  You now enter the second sequence.  As I understand the Exit tunnel, it defaults to "False", so I'd expect to stay in the second Event loop until I turn the Stop button from On to Off, which will pass out a False, and keep me in the While for one more button push.  However, this doesn't happen -- I immediately exit, as though the "True" value of the Stop local variable is being seen and recognized by the Event loop (even though it hasn't changed, at least not in the context of this second loop).
    An even more curious thing occurs if I start this routine with the Stop button turned on.  Now I start in my Event loop waiting for a change, but this time the change will be from On to Off, which won't cause an exit from the frame.  This will be reflected by having the While loop count increment.  We should now be in the state of the example above, i.e. in an Event loop waiting for the control to be pushed again, and turned On.  However, clicking the control has no effect -- I cannot get it to "turn on".
    Where am I going astray in my thinking?  What is it about this method of doing things that violates the Labview paradigm?  As far as I can tell, what I'm doing is "legal", and I don't see the flaw in my reasoning, above (of course not -- otherwise I'd have fixed it myself!).  Note that because I'm using local variables inside Event loops (and I'm doing this because there are two places in my code where I want to do such testing), the Stop control is not latching (as required).  Is there something that gets triggered/set when one reads a latched control?  Do I need to do this "manually" using my local variable?
    I'll try to attach the simple VI that illustrates this behavior.
    Bob Schor
    Attachments:
    Simple Stop Conundrum.vi ‏14 KB

    altenbach wrote:
    Ravens Fan wrote:
    NEVER have multiple event structures that share the same events. 
    Actually, that's OK.  NOT OK is having multiple event structures in the same sequence structure.
    See also: http://forums.ni.com/ni/board/message?board.id=170&message.id=278981#M278981
    That's interesting.  I had always thought I read more messages discouraging such a thing rather than saying it was okay.  Your link lead me to another thread with this message. http://forums.ni.com/ni/board/message?board.id=170&message.id=245793#M245793.  Now that thread was mainly concentrating on registered user events which would be a different, but related animal. 
    So if you have 2 event structures they each have their own event queue?  So if you have a common event, one structure pulls it off its event queue and it does not affect the other structure's event queue?  I guess the inherent problem with this particular VI was that the second event structure locked the front panel.  Since the code never got to that 2nd event structure because the  first loop never stopped because the change was from true to false.  After reading your post and the others, I did some experimentation and turned off the Lock front panel on the 2nd structure, and that prevented the lockup of the program.
    Overall, the example VI still shows problems with the architecture and I think your answer should put the original poster on the right track.  I think as a rule I would probably never put the same event in multiple structures, I feel there are better ways to communicate the same event between different parts of a program,  but I learned something by reading your reply and about how the event structures work in the background.  Thanks.

  • Problem in Exporting to Excel 2007 using CRServer 2008

    Can anyone please help me know the difference between Crystal Reports Server 2008 and Business Objects XI R2? Both the support guides says that it supports Office 2007. I have a problem in exporting the reports to Excel 2007 .I have downloaded the trial version of Crystal Reports Server 2008 but still unable to view my complete reports in Excel 2007 through infoview because few of my report's colums are truncated and it still exports in Excel 2003.I have LiveOfficeXIR2_SP4 and Office 2007 installed. Is it so that i have to switch over to Business Objects XI R2 or any other to solve my problem instead of using Crystal Reports Server 2008 or is it the problem with the version of my Live office.Pls help me regarding this..
    Babita.

    Hi Ani,
       First Thank you for your reply..I have already tried exporting it in Excel 2003 but since the limit is upto 256 columns and that my report's content exceeds this limit, few of the columns are truncated. Thats why i thought that it would be better to export it in Excel 2007. But i could'nt find any way to do it so..Pls help me if there is any other way..
    Babita.

  • Get-aduser - Export-CSV -- POWERSHELL

    I need help in getting this command to export the data into a CSV.
    Get-ADUser -Filter * -Properties
    whenCreated | Where-Object {$_.whenCreated -ge ((Get-Date).AddDays(-30)).Date} | FL SamAccountName, Name, DistinguishedName, whenCreated
    | Export-Csv
    c:\scripts\ADCreatedUsers.csv
    When doing this the command does not give me anything close to what I expect.

    Duplicate thread.
    Active thread is here:
    https://social.technet.microsoft.com/Forums/scriptcenter/en-US/15c5347a-4c18-404c-a9f9-0ba48b932384/getaduser-exportcsv-powershell?forum=ITCG
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

Maybe you are looking for