I'm pretty new to Powershell and would like to output the result of a command to a file which has a timestamp. Currently I could get the date but I can't get the time. Here is what I have:
mstest /testcontainer:"C:\CodedUITests\CodedUISP.dll" /resultsfile:"C:\CodedUITests\TestResults\result $(get-date -f yyyy-MM-dd)$.trx"
How can I get the time as well?
After a quick google search I found this reference:
Get-Date -f yyyy-MM-dd-HH-mm-ss
I'm doing almost the same thing! Here's my code:
$outputFile = "$tempLocation\work\$($solutionName)_$((Get-Date -Format s).ToString().Replace('-','').Replace(':','')).trx"
Write-Verbose "$($MyInvocation.MyCommand.Name): Running MSTest.exe..."
Invoke-ExternalCommand MSTest.exe #(
"/testcontainer:$testContainer",
"/resultsfile:$outputFile")
```
Invoke-ExternalCommand is just an abstracted function that calls the mstest command. Doing this allows me to mock the call making Pester testing easier.
This is what the trc file is named: SolutionName_20151015T113206.trx
Related
I have written a PS script, which replaces a specific string at the beginning of the file, adds another piece of string to the end of the file, and finally it puts out an XML.
My code might be ugly (I am not a programmer/engineer or anything, just trying to make life easier for some family members who are running a small business), but it works:
$content = Get-Content -Path 'C:\Users\blabla\Desktop\4440341930.txt'
$newContent = $content -replace 'text to be replaced','this is going to replace stuff'
$newContent | Set-Content -Path 'C:\Users\blabla\Desktop\4440341930.txt'
Add-Content C:\Users\blabla\Desktop\4440341930.txt '</Items>'
$x = [xml](Get-Content "C:\Users\blabla\Desktop\4440341930.txt")
$x.Save("C:\Users\blabla\Desktop\4440341930.xml")
I would like them to be able to run this script from the context menu, by right clicking on a txt file. I did a little research and I kind of get what I have to add to Registry, however, I'm not sure how to make it work. Since the path of each file that they are going to right click on is going to be different, the path that I'm specifying in $content is not going to work.
What do I have to modify in my code to be able to add it to the Registry?
To accomplish this you need to:
Create a Shortcut in the SendTo Folder: "$DestinationPath\AppData\Roaming\Microsoft\Windows\SendTo"
The target: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
The Arguments: -File "d:\path\your PS1 file"
In your program read the file name passed by Explorer as:
Param
(
[Parameter(Mandatory=$false)]
[String] $FilePath
)
I've written a Setup Function that accomplishes steps 1-3 that I include in all my programs that I want on the context menu and then just run the program with the -Setup switch. We're not supposed to post developed code here, but if you can't figure it out let me know and I'll post it and hope I don't get killed for it. LOL!
UPDATE:
If you want to pass more than one file you need to process the files a little differently. Delete the Param block above and then use this type of code to retrieve the files.
If ($Args.count -eq 0) {
$Message = "No Files were passed from File Explorer."
[Void]$MsgBox::Show(
"$Message","System Exit",$Buttons::OK, $MBIcons::Stop)
Show-PowerShell
Exit #Comment out for testing from ISE!
}
Else {
$FilesToCopy = $Args
}
I have a command which runs a program in silent mode, it uses an XML file for the data repository and a word template to create multiple word documents based on a filter xml file.
The command I use is:
"P:\ath to\executable" -Username:Admin -Password:Pa55w0rd -Datadefinition:"C:\Data.xml" -Datafilter:"C:\Filter.xml" -wordtemplate:"C:\Batch\Paul1.dotx" -Targetdocument:="C:\Batch\Paul1.pdf" -filetype:PDF -Log:"C:\Logs\error.log" -Usage:DOCGENSILENT
I need to run this as a PowerShell script which I have mostly managed:
set-executionpolicy unrestricted
$datadefinition = Get-Content "C:\Data file.xml"
$datafilter = Get-Content "C:\Filter for data file.xml"
$wordTemplate = Get-Content "C:\"C:\Template\Paul1.dotx"
$targetFolder = Get-Content "C:\"C:\Paul\Paul.pdf"
Stop-Job = "Executable path" -Username:Admin -Password:Pa55w0rd -Datadefinition:%dataDefinition% -Datafilter:%dataFilter% -wordtemplate:%wordTemplate% -Targetdocument:%targetFolder% -filetype:docx -Log:%logPath% -Usage:DOCGENSILENT
Stop-Job 1
set-executionpolicy restricted
Write-Host -NoNewLine "Press any key to continue..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
My issue is that the script starts the executable but then doesnt pass the Variables, can anyone guide me in the right direction to fix this?
Getting this working depends on the behavior of your executable. Some things I noticed:
Shouldn't this:
$wordTemplate = Get-Content "C:\"C:\Template\Paul1.dotx"
be this:
$wordTemplate = "C:\Template\Paul1.dotx"
Are you sure you need Get-Content? (Aside from that, the path and quoting in your sample are not correct.)
Shouldn't this:
$targetFolder = Get-Content "C:\"C:\Paul\Paul.pdf"
be this:
$targetDocument = "C:\Paul\Paul.pdf"
I doubt Get-Content is correct here, since presumably your output file doesn't exist yet? I also renamed the variable so it makes more sense in your command.
In fact, are you sure you need Get-Content for any of those? Aren't you specifying filenames, not the content of the files?
In PowerShell, variables are prefixed with $ rather than being surrounded by %.
Using Set-ExecutionPolicy within a script to enable scripts to run is pointless, because the script is already running. (That is, if execution policy prevented script execution, PowerShell wouldn't let you run the script in the first place.)
If my guesses regarding your variables are correct, I think your script should look something like this (note also that I specified a $logFile variable, which I didn't see in your script):
$datadefinition = "C:\Users\Administrator\data\Sample Model_146_object type(s).xml"
$datafilter = "C:\Users\Administrator\data\Sample Model_146_object type(s).xml"
$wordtemplate = "C:\Users\Administrator\Templates\Base object.docx"
$targetdocument = "C:\Users\Administrator\Result\sample test15"
$logfile = "C:\Users\Administrator\Logs\C4W Error.log"
& "C:\Program Files (x86)\Communicator4Word.exe" -Username:Admin -Password: -Datadefinition:$datadefinition -Datafilter:$datafilter -wordtemplate:$wordtemplate -Targetdocument:$targetdocument -filetype:docx -Log:$logfile -Usage:DOCGENSILENT
I don't know the behavior of Communicator4Word.exe when you use -Password: with no password after it. (Is that a syntax error, or should you just omit -Password: altogether?)
I have a Google sheet where I have published a CSV to the web.
I am trying to use PowerShell to download the CSV.
After the CSV downloads I log the event in a the log file with datestamp.
I use Windows Task Scheduler to do this daily.
I have tried to use the code below, and it seems to work if I copy/paste it into PowerShell, but when I double-click to run it, I get errors.
$client = New-Object System.Net.WebClient
$client.DownloadFile(“https://docs.google.com/spreadsheets/d/e/2xxxxxxxxxxxxxxxxxxxxxxxx/pub?gid=xxxx&single=true&output=csv”,“C:\Users\xxxxxxxxxx\sent_ordes.txt")
function Get-TimeStamp {
return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)
}
Write-Output "$(Get-TimeStamp) Sent Orders Powershell run " | Out-File
C:\Users\xxxxxxxxxxxxxx\Sent_Orders.log -Append
I don't seem to be able to get any complex PowerShell to run in a chef recipe. The upload fails to Chef if I add anything like a IF or function param into the resource block. Is this just how it works and I need to code around it or is there some other way to make this work?
powershell_script 'Install' do
code <<-EOH
If ((Test-Path D:\Chef) -eq $True)
{
Do something
}
EOH
end
Error returned is pretty blank, even wtih -n -V
FATAL: Cookbook file has a ruby syntax error
After spending a lot of time looking at this, I've worked out the issue.
log 'Add features - Start'
powershell_script 'install-iis-features' do
code <<~CODE
Function ChefLog
{Param ([string]$logstring)
$logfile = "D:\\ChefpsLogs\\Logfile.txt"
$date = Get-date
$date = $date.ToString("dd-MM-yyyy-HH-mm")
add-content $logfile -value "$date :: $logstring"
}
Cheflog "Testing"
CODE
end
log 'Add features - End'
The CODE <<~
CODE
Section being the fix, I've not used this before but after reading about it I guessed this was the fix.
The case: I have a project where I use nuget packages sharing small libraries between components. I use nuget packages produced by CI builds and once they are done I let the pull request go into master branch and this build will produce a new nuget package which will be used in production.
Nuget package created by CI build has the following properties:
Version number: X.Y.Z-CI-yyyyMMdd-HHmmss
Contains pdb files too
Contains documentation xml file
Nuget package create by Release build has the following properties:
Version number: X.Y.Z
Contains documentation xml file
VSTS build provides the option to use datetime in build name, so it will be unique always. The problem is here.
VSTS build uses localtime (I'm in GMT+2)
NugetCommand task of VSTS uses only UTC and bug ticket about it
As a result I have a strangle looking consistency between my builds and nuget packages:
Nuget package: 1.0.0-CI-20170709-201010
Build: BuildName-BranchName-20170709-181010
Another problem NugetCommand and VSTS cooperation is that, they take the timestamp in different moment, so there is a difference between the two timestamp beside the two hours. It is not that big deal because I don't kick off builds on same build-branch in every second, but still...
NugetCommand has the ability to read the version number of the package it will create from BuildNumber, which is the same as VSTS going to give the new artifact.
So, I would like to solve this problem until they make it more consistent. I already reported to them a few requests. What I figured out so far is using PowerShell to populate a variable with timestamp and it will be used by VSTS build and NugetCommand task.
I followed the example here but it deals with only strings and not date.
I put together the following script, but it does not provide the result I would like to have.
Powershell task 1:
Write-Host "Setting up the date time for build variable and nuget package identifiers"
Write-Host "##vso[task.setvariable variable=dateTimeIdentifier]Get-Date -format yyyyMMdd-Hmmss"
Write-Host "Get-Date -format yyyyMMdd-Hmmss"
Get-Date -format yyyyMMdd-Hmmss
Powershell task 2 where the argument is:
-dateTimeIdentitfier"$(dateTimeIdentifier)"
Write-Host "Checking: $(dateTimeIdentifier)"
And the result is where you can see that the Powershell command is the value of the variable not the formatted datetime.
Setting up the date time for build variable and nuget package identifiers
Get-Date -format yyyyMMdd-Hmmss
20170709-202457
Checking: Get-Date -format yyyyMMdd-Hmmss
I know how to solve issues like this in bash, but I don't have build agent where bash is available.
Bash like solution would like to be like this, which is not correct, but the command between `` will be executed first and the result will be passed through the remaining command as parameter.
Write-Host "##vso[task.setvariable variable=dateTimeIdentifier]`Get-Date -format yyyyMMdd-Hmmss`"
My question is, how to solve this in VSTS build and its task environment? Is there a solution for this? Is my approach correct?
You can change your first PowerShell task (Powershell task 1) as below:
Write-Host "Setting up the date time for build variable and nuget package identifiers"
$date=$(Get-Date -format yyyyMMdd-Hmmss)
Write-Host "##vso[task.setvariable variable=dateTimeIdentifier]$date"
Write-Host "Get-Date -format yyyyMMdd-Hmmss"
Get-Date -format yyyyMMdd-Hmmss
Add a variable in power shell script, and then set a VSTS (Azure DevOps) variable to use in subsequent tasks
If you want to have the datetime show when you write the output using write-host, and I highly recommend you use write-output instead, you can do the following:
$DateTime = Get-Date -format yyyyMMdd-Hmmss
Write-Host "Checking: $DateTime"
This will output this:
Checking: 20170710-64624
EDIT: Now for your issue, sorry I missed it the first time, the dateTimeIdentifier being returned looks like it is a string "Get-Date -format yyyyMMdd-Hmmss"
So if you want to execute that code, you need to first, make a script block, then execute that script block.
$ScriptBlock = [ScriptBlock]::Create("Get-Date -format yyyyMMdd-Hmmss")
& $ScriptBlock