Скрипт Powershell не выводит данные в файл за пределами ISE - PullRequest
0 голосов
/ 07 июня 2018

Я понимаю, что у других людей были подобные вопросы, но ни один не похож на этот.Я создал скрипт ps1 для преобразования файла объектов XML в файл CSV с строками, представляющими некоторые из этих данных.Вчера вечером я смог запустить пакетный файл и конвертировать файлы, но сегодня утром он сохраняет пустой CSV-файл, когда я запускаю из пакета, но он отлично работает, когда я запускаю его в Powershell ISE.

Я запускаю изпакетный файл с режимом -STA, позволяющим открывать диалоговые окна:

powershell -sta C:\Users\*******\Downloads\JiraXMLtoCSV.ps1

А вот сценарий (было трудно заставить этот блок кода lol извинить '}'):

    # This function will open a file-picker for the user to select their Jira XML Export
    Function Get-JiraXMLFile(){ 
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null;
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog;
$OpenFileDialog.initialDirectory = Get-Location;
$OpenFileDialog.filter = "XML files (*.xml)|*.xml";
$OpenFileDialog.ShowDialog() | Out-Null;
$OpenFileDialog.filename;
$OpenFileDialog.ShowHelp = $true;
}

    # This function will open the file save dialong to allow the user to choose location and name of the converted XML-to-CSV file
    Function Get-SaveFile(){ 
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null;

$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog;
$SaveFileDialog.initialDirectory = Get-Location;
$SaveFileDialog.filter = "CSV files (*.csv)|*.csv";
$SaveFileDialog.ShowDialog() | Out-Null;
$SaveFileDialog.filename;
$SaveFileDialog.ShowHelp = $true;
} 




    # Invoke the file-picker function and obtain input file 
    $inputFile = Get-JiraXMLFile;

    #initialize list for items that will be extracted from XML Input File
    $list = @(); 

    # Loop through all the items in Jira XML export file
    foreach ( $item in $XMLFile.rss.channel.item ) {

# Create a new hash object
$issue = @{}; 

# Gather wanted attributes
$issue.Key = $item.key.InnerXML;
$issue.StatusColor = $item.statusCategory.colorName;
$issue.Status = $item.status.InnerXML;

# Check for comments 
if ( $item.comments ) {
    # Record the comments with column name/header format as follows: comment #0 | comment #2|...
    # Change this value to 1 if you want to see it start at comment #1 instead of comment #0
    $incrementalCounter = 0;
    # Loop through all comments on the issue
    foreach ( $comment in $item.comments.comment ) {
        $issue.("comment #"+$incrementalCounter) = $comment.InnerXML;
        $incrementalCounter += 1;
    }

}
#Create an object to be added to the list
$object = New-Object –TypeName PSObject –Prop $issue;
Write-Output $object;

# add this issue to the list to convert/export to CSV
$list += $object;

}

# Open File Saving window to choose file name and location for the new
$OutputFile = Get-SaveFile;
$list | Export-Csv -Path ($OutputFile) -NoTypeInformation;

И если вы хотите, чтобы какой-нибудь пример XML помог мне узнать, что я делаю неправильно:

    <rss version="0.92">
    <channel>
    <title>XML Export</title>
    <link>...</link>
    <description>An XML representation of a search request</description>
    <language>en-us</language>
    <issue start="0" end="7" total="7"/>
    <build-info>...</build-info>
    <item>
    <title>[AJT-46] another new story</title>
    <project id="1652" key="AJT">Advanced Training</project>
    <description/>
    <environment/>
    <key id="220774">AJT-46</key>     
    <status id="16615" iconUrl="https://website.com/" description="Desc text">To Do</status>
    <statusCategory id="2" key="new" colorName="gray"/>
    <labels></labels>
    <created>Tue, 5 Jun 2018 11:25:38 -0400</created>
    <updated>Tue, 5 Jun 2018 11:29:00 -0400</updated>
    <due/>
    </item>
    </channel>
    </rss>

Он работал прошлой ночью, а теперь -не работает, когда я появился этим утром, поэтому ничего не изменилось, о чем я знаю, я тоже не перезагрузился.Это все еще работает в Powershell ISE, что хорошо, но мне нужен метод пакетного файла для человека, для которого я делаю это.Любая помощь, советы и т. Д. Приветствуется!Спасибо

1 Ответ

0 голосов
/ 07 июня 2018

Изменения, которые я сделал, и теперь это работает, разделенный двойным переводом строки:

# Invoke the file-picker function and obtain input file 
[Xml]$inputFile = Get-JiraXMLFile;


# Grab all the items we exported, ignore the header info
if ( $inputFile ) {
    #$XmlComments = Select-Xml "//comment()" -Xml $inputFile;
    #$inputFile.RemoveChild($XmlComments);
    $items = Select-Xml "//rss/channel/item" -Xml $inputFile;
}


# Iterate over items and grab important info to be put into CSV format
foreach ( $item in $items ){
# Create a new hash object
$issue = @{}; 


# Gather wanted attributes
if( $item.Node.key){
    $issue.Key = $item.Node.key.InnerXML;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...