I can't post all of the script contenet, but the basic idea is that it downloads JSON and converts it to objects using the ConvertFrom-Json
cmdlet. Some objects are filtered out, and the rest are written to an XML/XLS document (in the Excel 2003 format). This file is then attached to an email and sent to various people.
The problem I'm having is that it only works when run from the Powershell ISE. Once I try setting up a scheduled task, calling it from cmd, or even calling it from powershell, the attached file is completely empty. It is as if some functions do not run (the one that loops through and creates all rows).
I can continue to run from ISE for the time being, but the idea of this script is to send out an automatic email that will require no intervention. Any ideas as to what could be causing this?
You need to run the script "dot sourced" which can be done like this
powershell.exe -noexit -file c:\test.ps1
or
pwershell.exe -noexit ". c:\test.ps1"
See this link under the -File section http://technet.microsoft.com/en-us/library/hh847736.aspx
Based on the answer from the comments to the original post, it seems that the script was (unexpectedly?) working in the ISE because of the bug/quirk/feature that allows scripts run in the ISE to be aware of variables used in the console window and vice-versa.
This can often cause logic problems or unexpected results when a script runs with a variable already defined (and not initialized carefully in the script).
Ways to avoid this problem:
http://powershell.com/cs/blogs/tips/archive/2015/02/12/getting-a-clean-powershell-environment.aspx
To make sure a script runs in a completely clean test environment, you could of course restart the PowerShell ISE. A more convenient way is to open another PowerShell tab: in the PowerShell ISE, choose File/New PowerShell Tab.
Set-StrictMode 2
in your script to catch undefined variables, etc.https://technet.microsoft.com/en-us/library/hh849692.aspx
Set-StrictMode -Version 2.0
- Prohibits references to uninitialized variables (including uninitialized variables in strings).
- Prohibits references to non-existent properties of an object.
- Prohibits function calls that use the syntax for calling methods.
- Prohibits a variable without a name (${}).
I have had this problem be for and for me executing the scrip using single-threaded function from powershell worked. You could also try some other options, go to this link to find more info.
Example
powershell.exe -noexit c:\test.ps1 -sta
将缺少的变量或函数更改为全局。
function global:mycall{}
开始你的脚本:
[cmdletbinding()]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.