I have CSV file with incorrect date format 19-08-22:01:00 (yy-MM-dd:HH:mm)
When I open it in excel it is not showing in date format. So I would like to convert this value using powershell.
I tried to change it using below command. But didnt work
$d = '19-08-22:01:00'
get-date $d
Could someone please help me to convert the date in correct format in which excel recognize it as date.
I would use DateTime.ParseExact():
$OldDate = '19-08-22:01:00'
# We need a provider so we pick the invariant one.
$Provider = [CultureInfo]::InvariantCulture
$OldDateFormat = 'yy-MM-dd:HH:mm'
# This format works well with Excel, assuming you use . and not , as a radix
$NewDateFormat = 'yyyy-MM-dd HH:mm:ss.fff'
$NewDate = [DateTime]::ParseExact($OldDate, $OldDateFormat, $Provider)
$NewDate.ToString($NewDateFormat)
If your only goal is fixing the format, you just need to replace that first colon with a space:
$d -replace '(?<=-\d{1,2}):', ' '
Related
I have a string with different length. I want to cut a specific word in my string.
Please help, I am new to PowerShell.
I tried this code, it's still not what I need.
$String = "C:\Users\XX\Documents\Data.txt"
$Cut = $String.Substring(22,0)
$Cut
My expectation is that I can return the word Data.
Assuming the string is always the same format (i.e. a path ending in a filename), then there are quite a few ways to do this, such as using regular expressions. Here is a slightly less conventional method:
# Define the path
$filepath = "C:\Users\XX\Documents\Data.txt"
# Create a dummy fileinfo object
$fileInfo = [System.IO.FileInfo]$filePath
# Get the file name property
$fileInfo.BaseName
Of course, you could do all of this in one step:
([System.IO.FileInfo]"C:\Users\XX\Documents\Data.txt").BaseName
If the path is an existing one, you could use
(Get-Item $String).BaseName
Otherwise
(Split-Path $String -Leaf) -Replace '\.[^\.]*$'
While in that specific example the simplest way is to use Substring(startPosition,length) to extract file name you'd probably want to use something like this:
(("C:\Users\XX\Documents\Data.txt".split("\\"))[-1].Split("."))[0]
Explanation:
("C:\Users\XX\Documents\Data.txt".split("\\"))[-1]
that part split the path by \ and returns last item (escaping it seems to be not mandatory by the way so you can use .split("\") instead of .split("\\")). From it you receive Data.txt so you have to separate name and extension. You can do this by splitting by . and choosing first element returned
There are number of ways of doing it depending upon your input -
Method 1 - Hard-coding using the sub-string function.
$String = "C:\Users\XX\Documents\Data.txt"
$Cut = $String.Substring(22,4)
$Cut
The above approach will work for a single input but will become difficult to manage for multiple inputs of different lengths.
Method 2 - Using the split method
$String = "C:\Users\XX\Documents\Data.txt"
$cut = $String.Split("\")[-1].split(".")[0]
$cut
Split method will split string into substring. The index [-1] will return the last value returned by the split method.
The second split is to return the word Data from the word Data.txt.
Method 3 - If the input is a file path
$string = Get-ChildItem $env:USERPROFILE\Desktop -File | select -First 1
$Cut = $String.BaseName
More about method 3 here.
If you can use Powershell 6 - SplitPath
#Requires -Version 6.0
Split-Path $String -LeafBase
I want to get the index of the last "\" occurrence in order to trim the "Activity" word and keep it, from following string in PowerShell:
$string = "C:\cmb_Trops\TAX\Auto\Activity"
I'm converting the code from VBScript to PowerShell and in VB there's this solution :
Right(string, Len(string) - InStrRev(string, "\"))
Using Right and InStrRev functions which makes the life more easier. Unfortunately I didn't find anything like it in PowerShell. Can't find any option to scan from the end of the string.
$String.Split("\")[-1]
Or if $String is actually a real path, you might consider:
Split-Path $String -Leaf
$string = "C:\cmb_Trops\TAX\Auto\Activity"
$string = $string.Substring($string.lastIndexOf('\') + 1)
echo $string
Check out:
https://community.spiceworks.com/topic/1330191-powershell-remove-all-text-after-last-instance-of
I need to parse some time string that comes in a format like ddmmyyyyhhmmssXXX. The XXX part is millisecond. In the below code Im ignoring the millisecond part. It works but I get the error:
garbage at end of string in strptime: 293 at /usr/local/lib64/perl5/Time/Piece.pm line 482.
Whats the proper format that I should use.
$time = '11032014182819802';
$format = '%d%m%Y%H%M%S';
$t = Time::Piece->strptime($time, $format);
Time::Piece->strptime(substr($time, 0, -3), $format);
since Time::Piece does not support milliseconds.
If you care about the milliseconds and want to preserve them, you'll need to look into using something else (e.g., DateTime::Format::Strptime).
You can use DateTime::Format::Strptime if you want to parse milliseconds, then you may try this:
my $Strp = new DateTime::Format::Strptime(
pattern => '%d%m%Y%H%M%S%3N',
);
my $date = $Strp->parse_datetime("11032014182819802");
print $date->millisecond ,"\n";
I have a list of users in a text file who's names are in the following format: xn-tsai-01.
How do I script to remove the xn- KEEP THIS -01 so the output is like: tsai
I know how to do this in bash but not too familiar with powershell.
Thanks in advance!
Why not use Substring method. If you will always trim the first three characters, you can do the following assuming the variable is a string type.
$string = xn-tsai-01
$string.Substring(3)
Here is a quick way to do it using regex:
'xn-tsai-01' -replace '.*?-(.*)-.*','$1'
Example with a list:
(Get-Content list.txt) -Replace '.*?-(.*)-.*','$1'
You can use the .NET string method IndexOf("-") to find the first, and LastIndexOf("-") to find the last occurrence of "-" within the string.
Use these indexes with Substring() to remove the unnecessary parts:
function Clean-Username {
param($Name)
$FirstDash = $Name.IndexOf("-") + 1
$LastDash = $Name.LastIndexOf("-")
return $Name.Substring( $f, $l - $f )
}
PS C:\> Clean-UserName -Name "xn-tsai-01"
tsai
Boe's example is probably going to be the most efficient.
Another way is to use the split() method if they're in a uniform format.
Get-Content .\list.txt | % { ($_.Split('-'))[1] }
% is an alias for ForEach
How do you use Data::Table::Excel for converting .csv to .xls file format.
I want to do the conversion with the tables2xls subroutine:
my $t = Data::Table::fromFile("testresults-2013-07-01.csv");
my #arr = $t->csv;
Data::Table::Excel::tables2xls("results.xls", $t ,\#arr);
I tried the code above but I was not able get what I expected.
Last line must be:
Data::Table::Excel::tables2xls("results.xls", [$t] ,["Sheet name for your Table"]);
And here is colors example like you want:
Data::Table::Excel::tables2xls("results.xls", [$t] ,["Sheet name for your Table"], [["white","silver","gray"]]);