Calculate specific Date in powershell - excel

I'm a beginner in powershell
$test = ("=7*" + $newWorkSheet.Cells.Item($indexDate,9).Text + "+DATE(" + $newWorkSheet.Cells.Item($indexDate,8).Text + ";1;3)-WEEKDAY(DATE(" + $newWorkSheet.Cells.Item($indexDate,8).Text + ";1;3))-2")
$newWorkSheet.Cells.Item($indexDate,1) = $test
Result to an incomprehensive error : Exception de HRESULT : 0x800A03EC
this is what I want to put in my cell :
echo $test
=7*40+DATE(2014;1;3)-WEEKDAY(DATE(2014;1;3))-2
How can i resolve it ? Thx ! and sorry for my poor english :'(
Edit
I did :
$test = '=7*' + $newWorkSheet.Cells.Item($indexDate,9).Text + '+DATE(' + $newWorkSheet.Cells.Item($indexDate,8).Text + ';1;3)-WEEKDAY(DATE(' + $newWorkSheet.Cells.Item($indexDate,8).Text + ';1;3))-2'
if I echo $test I got what I want :
=7*40+DATE(2014;1;3)-WEEKDAY(DATE(2014;1;3))-2
but when i put $test into my cell like this :
$newWorkSheet.Cells.Item($indexDate,1) = $test
Result an error :
Exception de HRESULT : 0x800A03EC
Au caractère D:\Users\sadm\Documents\salesforce_1.ps1:839 : 1
+ $newWorkSheet.Cells.Item($indexDate,1) = $tmp1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

I search to display a specific date with a number of week and a year.
Number of week and year are containing in cells of an excel.
$newWorkSheet.Cells.Item($indexDate,9) = $idsem ##Here is my number of week
$newWorkSheet.Cells.Item($indexDate,8) = $tempDate3.ToString("yyyy")
$test = "=" + "7*" + $newWorkSheet.Cells.Item($indexDate,9).Text + '+DATE(' + $newWorkSheet.Cells.Item($indexDate,8).Text + ';1;3)-JOURSEM(DATE(' + $newWorkSheet.Cells.Item($indexDate,8).Text + ';1;3))-2'
$newWorkSheet.Cells.Item($indexDate,1) = $test
$newWorkSheet.Cells.Item($indexDate,1).NumberFormat = "jj/mm/aaaa"
$global:indexDate++
When I launch the script with powershell 5.0 I had this error :
Exception de HRESULT : 0x800A03EC
Au caractère D:\Users\sadm\Documents\salesforce_1.ps1:831 : 1
+ $newWorkSheet.Cells.Item($indexDate,1) = $test
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
with 2.0 that works...

Related

Python Jupyter Notebook loops while writing output to a text file

A jupyter notebook cell is calculating some things and prints the results.
I would like to print everything into a text file. The text file is created and written. But maybe the cell isnt properly closed as it never comes to an running end? Where is my mistake?
The code:
with open(path_out + day_number + 'factsheet.txt', 'w') as fs:
sys.stdout = fs
print("Fact Sheet:")
Lat_start = df.Wgs84Latitude[df.index.min()]
Lon_start = df.Wgs84Longitude[df.index.min()]
print("Coordinates: " , Lat_start,'°N , ', Lon_start,'°E')
print("Min. Humidity: " + "{:12.2f}".format(df.humidity.min()) + " %")
print("Max. Humidity: " + "{:12.2f}".format(df.humidity.max()) + " %")
print("Min. Temperature: " + "{:9.2f}".format(df.temperature.min()) + " °C")
print("Max. Temperature: " + "{:9.2f}".format(df.temperature.max()) + " °C")
sys.stdout = original_stdout # Reset the standard output to its original value
fs.close()
Any hint for me?
I found a solution that works without tapping into a loop, but I still do not understand why the above code leads to loop the cell.
My "workaround":
fs = open(path_out + day_number + '_factsheet.txt', 'w')
Lat_start = df.Wgs84Latitude[df.index.min()]
Lon_start = df.Wgs84Longitude[df.index.min()]
fs.write("Coordinates: " + str(Lat_start) + '°N , ' + str(Lon_start) + '°E\n\n')
fs.write("Min. Humidity: " + "{:12.2f}".format(df.humidity.min()) + " %\n")
fs.write("Max. Humidity: " + "{:12.2f}".format(df.humidity.max()) + " %\n")
fs.write("Min. Temperature: " + "{:9.2f}".format(df.Temperature.min()) + " °C\n")
fs.write("Max. Temperature: " + "{:9.2f}".format(df.Temperature.max()) + " °C\n")
fs.close()
print("Export successful")
Remark: This solution accepts only the "+"-symbol to add several contents in one write-break and I had to add th "\n" to insert a line feed which was not neccessary in the "print" solution.
But it works :-)

Error while adding tags to vm with powershell after reading from csv

I am trying to add tags to azure vm by reading from csv file with a powershell script. I want to read the value via loop and add to existing tags of vm, if any. Below is my code and the respective errors.
$data = Import-CSV C:\Documents\tags-vms.csv
foreach($info in $data){
$tags = (Get-AzResource -ResourceGroupName policyResourceGroup -Name $info.psobject.properties.value[0]).Tags
$scriptBlock = [scriptblock]::Create('#{$info.Tags}')
$newtags = (& $scriptBlock)
$tags += $newtags
Write-Host $tags
}
Now the error is
Exception calling "Create" with "1" argument(s): "At line:1 char:13
2021-12-20T16:01:09.2145247Z + #{$info.Tags}
2021-12-20T16:01:09.2147301Z + ~
2021-12-20T16:01:09.2149246Z Missing '=' operator after key in hash literal.
2021-12-20T16:01:09.2152282Z At line:1 char:13
2021-12-20T16:01:09.2154454Z + #{$info.Tags}
2021-12-20T16:01:09.2156590Z + ~
2021-12-20T16:01:09.2166796Z The hash literal was incomplete."
2021-12-20T16:01:09.2168854Z At C:\agent\_work\_temp\e8ee61c2-c3f4-4ea5-99ac-4feb671fff57.ps1:18 char:1
2021-12-20T16:01:09.2169842Z + $scriptBlock = [scriptblock]::Create('#{$info.Tags}')
2021-12-20T16:01:09.2170521Z + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2021-12-20T16:01:09.2171329Z + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
2021-12-20T16:01:09.2171826Z + FullyQualifiedErrorId : ParseException
Can someone please help.
**csv file contains**
VmName Tags
test-vm01 "loc"="us"
test-vm02 "Loc"="Us";"doseage"="Second"
I think your issue lies in this line and how you're retrieving the tag info from the CSV object from your foreach loop:
$scriptBlock = [scriptblock]::Create('#{$info.Tags}')
In the previous line in your script, to define the $tags variable, you retrieve the value of the name of the VM in the CSV object using ($info.psobject.properties.value[0]). I would attempt to use that same format in the next line, but modifying it to retrieve the tag part of the CSV object using the index of 1:
So instead of:
$scriptBlock = [scriptblock]::Create('#{$info.Tags}')
use:
$scriptBlock = [scriptblock]::Create('#{$info.psobject.properties.value[1]}')

Powershell Datahandling

Dear Stack Overflow Community,
I think you can guess it, Houston has got a problem.
Background: Our Company was attacked by Hackers and we lost a TON of data. Now, where everything is back up and running (more or less) it came to light that we have thousands and thousands of old .xls and .doc Documents on our servers which have to be converted to the newer formats before re-entering our brand new server structure.
Currently I am trying to write a script that converts XLS to XLSX. The Problem: I am good at Batch Programming but completly lost when it comes to Powershell. This is my third attempt after writing it from scratch. It does what it is supposed to do, but I don´t know how to do proper data handling in PS.
What it is supposed to do:
Ask the User where to look for XLS files.
Ask the User where to store the new XLSX files.
Take every .xls file from the directory (and subfolders), open it and save it as .xlsx to the given path.
What it does so far:
Ask the User where to look for XLS files.
Ask the User where to store the new XLSX files.
Screw up the paths completly + cant open file.
It is able to convert .xls to .xlsx when I modify the script to feed it the complete paths. So the Excel part seems to be correct. I know my data handling part is very wrong. I tried to rewrite it many times now. I left it in so you may see what I tried to do.
$LookXLS = Read-Host -Prompt 'Where do I look for XLS?'
$TargetpathXLSX = Read-Host -Prompt 'Where to save the XLSX?'
Write-Host $LookXLS
cd $LookXLS # Change Directory to given path
Get-ChildItem -Path .\ -Filter *.xls -Recurse -File -Name| ForEach-Object {
[System.IO.Path]::GetFileName($_)
$excel=New-Object -comobject Excel.Application
$excel.Visible =$TRUE
$excel.DisplayAlerts = $FALSE
$wb = $excel.Workbooks.Open($LookXLS)
$LookXLS=$TargetpathXLSX
$typ=".xlsx"
$TargetPathXLSX="$TargetpathXLSX\$_$typ"
echo $TargetPathXLSX
$excel.ActiveWorkbook.SaveAs("$TargetPathXLSX",51)
$excel.ActiveWorkbook.Close()
$excel.Quit()
}
echo Process finished.
pause
The Output looks like this:
(Comments by me because it is partly German)
PS C:\Users\USER\Desktop\Testordner\Userverzeichnis> C:\Users\USER\Desktop\new 1.ps1
Where do I look for XLS?: C:\Users\USER\Desktop\Testordner\Userverzeichnis
Where to save the XLSX?: C:\Users\USER\Desktop\Testordner\Ziel
C:\Users\USER\Desktop\Testordner\Userverzeichnis
Microsoft Excel-Arbeitsblatt (neu) (2).xls
Wir konnten 'Arbeit\Microsoft Excel-Arbeitsblatt (neu) (2).xls' nicht finden. Wurde das Objekt vielleicht verschoben, umbenannt oder gelöscht? **#Can´t find it**
In C:\Users\USER\Desktop\new 1.ps1:17 Zeichen:1
+ $wb = $excel.Workbooks.Open($_)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
C:\Users\USER\Desktop\Testordner\Ziel\Arbeit\Microsoft Excel-Arbeitsblatt (neu) (2).xls.xlsx
Es ist nicht möglich, eine Methode für einen Ausdruck aufzurufen, der den NULL hat.
**#NULL (obviously, the path is screwed up)**
In C:\Users\USER\Desktop\new 1.ps1:22 Zeichen:1
+ $excel.ActiveWorkbook.SaveAs("$TargetPathXLSX",51)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Es ist nicht möglich, eine Methode für einen Ausdruck aufzurufen, der den NULL hat.
In C:\Users\USER\Desktop\new 1.ps1:24 Zeichen:1
+ $excel.ActiveWorkbook.Close()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Microsoft Excel-Arbeitsblatt (neu).xlsx
Wir konnten 'Arbeit\Microsoft Excel-Arbeitsblatt (neu).xlsx' nicht finden. Wurde das Objekt vielleicht verschoben, umbenannt oder gelöscht?
In C:\Users\USER\Desktop\new 1.ps1:17 Zeichen:1
+ $wb = $excel.Workbooks.Open($_)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
C:\Users\USER\Desktop\Testordner\Ziel\Arbeit\Microsoft Excel-Arbeitsblatt (neu) (2).xls.xlsx\Arbeit\Microsoft Excel-Arbeitsblatt (neu).xlsx.xlsx
**#It gets worse every time it loops.**
Es ist nicht möglich, eine Methode für einen Ausdruck aufzurufen, der den NULL hat.
In C:\Users\USER\Desktop\new 1.ps1:22 Zeichen:1
+ $excel.ActiveWorkbook.SaveAs("$TargetPathXLSX",51)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Es ist nicht möglich, eine Methode für einen Ausdruck aufzurufen, der den NULL hat.
In C:\Users\USER\Desktop\new 1.ps1:24 Zeichen:1
+ $excel.ActiveWorkbook.Close()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
I hope, somehow you can help me. I´m not a PS guy, but sadly Batch can´t work with Excel. I don´t think I am too far from a solution.
Try this -
$LookXLS = Read-Host -Prompt 'Where do I look for XLS?'
$TargetpathXLSX = Read-Host -Prompt 'Where to save the XLSX?'
Write-Host "$($LookXLS) is where we look" -ForegroundColor cyan
cd $LookXLS # Change Directory to given path
Get-ChildItem -Path .\ -Filter *.xls -Recurse | ForEach-Object {
$path = ($_.fullname).substring(0, ($_.FullName).lastindexOf("."))
$excel = New-Object -comobject Excel.Application
$excel.Visible = $TRUE
$excel.DisplayAlerts = $FALSE
$wb = $excel.Workbooks.Open($_.FullName)
$path += ".xlsx"
$wb.saveas($path, 51)
$wb.close()
$excel.Quit()
}
The above code changes the xls files to xlsx. You need to add the code for copying the xlsx files to the target folder.

Azure Powershell Command failure when using Invoke-AzsRegistrationValidation

I have been following the steps given here(https://learn.microsoft.com/en-us/azure-stack/operator/azure-stack-validate-registration?view=azs-2008&tabs=az) to validate a subscription but when i run the invoke command it fails with the below error:
> PS C:\WINDOWS\system32> Invoke-AzsRegistrationValidation
> -RegistrationSubscriptionID $subscriptionID Invoke-AzsRegistrationValidation : Parameter set cannot be resolved
> using the specified named parameters. At line:1 char:1
> + Invoke-AzsRegistrationValidation -RegistrationSubscriptionID $subscri ...
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : InvalidArgument: (:) [Invoke-AzsRegistrationValidation], ParentContainsErrorRecordExcept
> ion
> + FullyQualifiedErrorId : AmbiguousParameterSet,Invoke-AzsRegistrationValidation
The obvious question is do you have the correct subscriptionID in $SubscriptionID
The doc you reference suggest some logs might be created, is there anything in them that help?
Log location (contains PII):
C:\Users\username\AppData\Local\Temp\AzsReadinessChecker\AzsReadinessChecker.log**
s
Report location (contains PII):
C:\Users\username\AppData\Local\Temp\AzsReadinessChecker\AzsReadinessCheckerReport.json

How to redirect "println" commands output to a file in Groovy

I would like to redirect out of println command which is details of job like Build name, status, time etc to another file.
Below is snippet of my code who's output i want to redirect to a file.
def lastBuildEnvVars = lastbuild.getEnvVars()
println 'Product Name : ' + lastBuildEnvVars['PRODUCT_NAME'] + 'Version : ' + lastBuildEnvVars['PRODUCT_VERSION'] + 'Result: ' + lastbuild.result + 'Time: ' + lastbuild.timestampString2 + '\n'
println 'Result: ' + lastbuild.result + '\nTime: ' + lastbuild.timestampString2
OutPut of println is
Current Product Name : OMA_KENAN_FX_READINESS
Product Version :
Result: SUCCESS
Time: 2019-08-31T01:25:26Z
def logFile = new File("output.log")
logFile.append('Product Name : ' + lastBuildEnvVars['PRODUCT_NAME'] + 'Version : ' + lastBuildEnvVars['PRODUCT_VERSION'] + 'Result: ' + lastbuild.result + 'Time: ' + lastbuild.timestampString2 + '\n')
logFile.append('Result: ' + lastbuild.result + '\nTime: ' + lastbuild.timestampString2)
You can assign a line to a string variable and then do:
def entry = 'Result: ' + lastbuild.result + '\nTime: ' + lastbuild.timestampString2
println(entry)
logFile.append(entry)
Then you could write a method called, say logIt(entry) that does the print and write to file:
def logIt(entry) {
//you have to let this method know about the file object somehow
println(entry)
logFile.append(entry)
}
and so on and so on.

Resources