Need to run powershell script in a bat file
I have a ps1 file with the following:
Get-ADUser -Filter * -SearchBase "ou=<HOSPOU>,ou=Domain Users and Groups,dc=<hospdomain>,dc=local" -Properties Description,EmailAddress| Select-Object -Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\<server>\home2$\information
services\IS STAFF\Documentation\AD Info\smcusers.csv";
I have a bat file:
@ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%smcusers.ps1
%windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command import-module ActiveDirectory "%PowerShellScriptPath%";
But while it launches powershell with the AD module, It apparently cannot read the ps1 file.
I get:
H:\>C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command i
mport-module ActiveDirectory "H:\smcusers.ps1";
Import-Module : A positional parameter cannot be found that accepts argument 'H
:\smcusers.ps1'.
At line:1 char:14
+ import-module <<<< ActiveDirectory H:\smcusers.ps1;
+ CategoryInfo : InvalidArgument: (:) [Import-Module], ParameterB
indingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell
.Commands.ImportModuleCommand
I have tried to modify the parameters
%windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command import-module ActiveDirectory -File "%PowerShellScriptPath%";
Still no luck.
I need to be able to run this as a scheduled task.
Karon W
Apparently I don't know where to put everything.
I have a single line:
%windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-module ActiveDirectory; -Command {Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress|Select-Object
-Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\svr-resource2\home2$\information services\IS STAFF\Documentation\AD Info\smcusers.csv"}
This is the response:
H:\>C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-mod
ule ActiveDirectory; -Command {Get-ADUser -Filter * -SearchBase "ou=Shannon Memo
rial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Descripti
on,EmailAddress | Select-Object -Property Name,SamAccountName,Description,Email
Address | Export-Csv "\\svr-resource2\home2$\information services\IS STAFF\Docu
mentation\AD Info\smcusers.csv"}
'Select-Object' is not recognized as an internal or external command,
operable program or batch file.
I modified to 2 lines:
%windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-module ActiveDirectory;
Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress|Select-Object -Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\svr-resource2\home2$\information
services\IS STAFF\Documentation\AD Info\smcusers.csv"
This is the response:
H:\>C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-mod
ule ActiveDirectory;
PS H:\> exit ************I had to type*****************
H:\>Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Gr
oups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress | Select-O
bject -Property Name,SamAccountName,Description,EmailAddress | Export-Csv "\\sv
r-resource2\home2$\information services\IS STAFF\Documentation\AD Info\smcusers.
csv"
'Get-ADUser' is not recognized as an internal or external command,
operable program or batch file.
If I paste the command in before I type exit, it works.
If I paste:
%windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit import-module ActiveDirectory;
I am put in the ad powereshell
Then I paste:
Get-ADUser -Filter * -SearchBase "ou=Shannon Memorial,ou=Domain Users and Groups,dc=shannonhealth,dc=local" -Properties Description,EmailAddress|Select-Object -Property Name,SamAccountName,Description,EmailAddress|Export-Csv "\\svr-resource2\home2$\information
services\IS STAFF\Documentation\AD Info\smcusers.csv"
and I get the expected output.
What do I need to have in the bat file so the 2nd line of the script will run? and where does it go?
Karon W
Similar Messages
-
Run powershell commands on a bat file
Hello,
I can call powershell on command line as below:
C:\>echo I am in Command Shell
I am in Command Shell
C:\>powershell
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS C:\> Write-Host I am in Powershell
I am in Powershell
PS C:\> exit
C:\>echo I returned to Command Shell
I returned to Command Shell
But I want to create a bat file and run these commands in bat file. To do this, I copied and pasted same codes to Test.bat file:
echo I am in Command Shell
powershell
Write-Host I am in Powershell
exit
echo I returned to Command Shell
But after "powershell" command nothing worked as below:
C:\>.\Test.bat
C:\>echo I am in Command Shell
I am in Command Shell
C:\>powershell
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS C:\>
I want this output:
I am in Command Shell
I am in Powershell
I returned to Command Shell
How can I handle this problem.
PS: I don't want to use powershell file (*.ps1).
ThanksIn my Test.bat file there are some commands. My Test.bat file is sth like this:
@echo off
echo I am in Command Shell
powershell.exe
Write-Host I am in Powershell
$Var = "Some words"
Write-Host My ID: $Id, String: $Var
exit
echo I returned to Command Shell
There are other different commands, such as importing modules or setting variables or configuring computer settings,.... So, I think "powershell -command" is not applicable.
In brief;
Above codes work in command line.
But when I use same codes in a batch file, nothing works in powershell. Result is sth line this:
C:\>Test.bat
I am in Command Shell
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.
PS C:\> -
Passing parameters with spaces to SCCM Run PowerShell Script task
I am working on an OS deployment task sequence in SCCM 2012 R2 with several Run PowerShell Script tasks. Most of them run fine, but I am having trouble with the one I need to pass parameters to.
The parameters I need to pass are:
-ComputerOU "ou=All Workstations,dc=contoso,dc=com" -GroupDN "cn=Group1,ou=All Groups,dc=contoso,dc=com"
I have that line (with actual DNs) entered in Parameters of the task.
But when the script runs on the target machine, the values of the parameters in the script are truncated at the spaces. $ComputerOU is set to "ou=All" and $GroupDN is set to "cn=Group1,ou=all"
What syntax should I be using the Parameters field of the Task in order to properly pass PowerShell parameter string values that include spaces?
Tim Curwick
MadWithPowerShell.comThank you, TC, but I am not calling the parameters from within PowerShell.
The parameters are in the settings of a task sequence task to be used by the task to launch a script. The syntax I am using would be correct for use within PowerShell or from a command line or batch script, but SCCM appears to be doing some parsing
before or while it is passing them to the script, possibly dropping the quotes which causes mishandling of the spaces in the string values.
Historically, it is always challenging to give one application parameters to pass to another application, and the required syntax can get quite tricky when the two application handle quotes or spaces differently, or when the parent application wants to parse
something intended to be passed on as is to the child application.
I'm sure someone has already figured out what the syntax needs to be for doing this with an SCCM 'Run PowerShell Script" task, it's just one of those issues that is hard to Google effectively.
Any other ideas?
Tim Curwick
MadWithPowerShell.com -
OSD - Task Sequence to run powershell script
Hello,
I'm building up an image with OSD and will be layering some components to meet our needs with some powershell scripts. At the moment we will not have this device add itself to the domain so it'll be in a workgroup. The scripts are on a share that everyone has
read access to. Should I add a task sequence that will map a drive letter with domain credentials and have the task sequence call the script from that drive letter?That is possible to do, but why would you not create a package/application with the script and let it download and run locally?
Daniel Ratliff | http://www.PotentEngineer.com -
Run Powershell Script task sequence
Hi,
Anyone have good documentation on how to use the Run PowerShell Script task sequence ?
ThanksIf you are just interested in running a powershell command without creating a package, you can do this with the the Command line step by using this format in the command line:
PowerShell -ExecutionPolicy bypass -Command "& {your powershell commands}"
Here is an example of a multiline command to increase the agents cache size. Notice the ";"'s which are used to delineate a new line.
PowerShell -ExecutionPolicy bypass -Command "& {$UIResourceM gr = New-Object -ComObject UIResource.UIResourceMgr;$Cache = $UIResourceMgr.GetC acheInfo();$Cache.TotalSize = "20480"}" -
Issue with running powershell script in pssessions
Hi Everyone,
I am trying to run powershell script from remote machine using below commands
C:\Users\user>"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
-command "$s= New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
http://Exchservername/PowerShell/ -Authentication Kerberos ; Import-PSsession $s; "C:\Failback.ps1"
and Below is the failback.ps1.
$mbxs = Get-MailboxDatabase | Sort Name
ForEach($mbx in $mbxs)
$MBdb=$mbx.Name $ServerHosting=$mbx.Server.Name
if($mbx.activationPreference.value -eq 1)
If ($ServerHosting -ne $ActivationPreference.Key.Name)
Move-ActiveMailboxDatabase $MBdb -ActivateOnServer $ActivationPreference.Key.Name -confirm:$False
Below is what i am getting.What is your question? Are you pointing out the yellow text? This is normal, and appears every time EMS is opened.
I should also point out that Microsoft provides a script to re-balance databases, if that's what you're trying to accomplish:
You can use the RedistributeActiveDatabases.ps1 script to balance the active mailbox databases copies across a DAG. This script moves databases between their copies in an attempt to have an equal number of mounted databases on each server in DAG. If required,
the script also attempts to balance active databases across sites.
https://technet.microsoft.com/en-us/library/dd335158(v=exchg.141).aspx
Mike Crowley | MVP
My Blog --
Baseline Technologies -
Run Powershell Script from Server
I am new to MDT so please forgive me. I am looking for a way for the MDT server to run a script locally after a server has been deployed. I saw you can do something similar where you use remoting in the task sequence. That is not
allowed or enabled in my environment. Is there any way for the MDT server to know it is done then it runs a script?The unattend file has several locations that scripts could be run from, either in the specialize pass or oobeSystem pass.
http://technet.microsoft.com/en-us/library/cc748874(v=ws.10).aspx -- this also gives you some demos on how to create your own unattend, though most basic settings are handled by
MDT.
You could also look into utilizing the run and runonce keys -
http://msdn.microsoft.com/en-us/library/aa376977%28v=vs.85%29.aspx -
How do I run a script on a .indb file?
How do I run a script on a .indb file? What should I do differently than in running one on a single indd file?
I do this like so:
var inddFiles = GetFilesFromBook();
for (var i = 0; i < inddFiles.length; i++) {
inddFile = inddFiles[i];
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
doc = app.open(inddFile);
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.INTERACT_WITH_ALL;
// Process document
doc.close(SaveOptions.YES);
function GetFilesFromBook() {
var bookContent, file,
activeBook = app.activeBook,
files = [];
for (var i = 0; i < activeBook.bookContents.length; i++) {
bookContent = activeBook.bookContents[i];
if (bookContent.status != BookContentStatus.MISSING_DOCUMENT) {
file = new File(bookContent.fullName);
files.push(file);
return files;
Here is the whole script that you can use as example. -
Running powershell script with customer parameters as a scheduled task
tfl wrote:I guess I don't get why you are wanting thisMy regular tasks run,. and take data from data files. Want your batch to get processed today? Then add it to the queue file by 5:00 PM.. The task runs at 5:01 and works with whatever data is available. And if the file is empty, nothing happens each night. If you want to pass parameters like this, then why bother with a scheduled task? You'd need to remove the old one and add the new one each time. Which is extra work and complexity, especially if the task at hand is in any way 'dangerous' if run twice with the same data (ie you forget to change the task or remove it).I'm using a scheduled task to trigger the script, I'm using the "on event" trigger and then calling the script as an action. The method I was using before (calling via a bat file with the event Id hard coded into that"...
Hi all,Having one of those hair pulling issues where something should work but for some reason its blindly refusing not to!I've created this script that is a bit of an extension to the email on eventID for task scheduled. It basically pulls out the various information from the actual event and fires off an email to our alerting team to investigate etc.That all works great, but what I'm now trying to do is get it to accept a custom parameter so the actual event ID its looking for doesn't have to be hard coded and can be passed to it via the commandline etc. I've got it all setup and work great but for the life of me can't get it to work correctly when set as a scheduled task. This is what the command basically looks like:powershell -executionpolicy bypass -command "& 'pathtofile\script.ps1' -evtid 8004"The latter part is the customer...
This topic first appeared in the Spiceworks Community -
Need Help on powershell Script to send mails in different languages
Hello, Just wanted to use the script below to remind users of password expiry date (I got it from internet New-Passwordreminder.ps1). We have companies in many countries, so the email should be in the language of that country. So since our users are in different
OU's according to countries, I thought some one could help me edit this script and say if the user is in AB ou then email in english will be sent, if in BC ou then the email will be in Russian....So in the script I will have all the languages I need
to have written.
<#
.SYNOPSIS
Notifies users that their password is about to expire.
.DESCRIPTION
Let's users know their password will soon expire. Details the steps needed to change their password, and advises on what the password policy requires. Accounts for both standard Default Domain Policy based password policy and the fine grain
password policy available in 2008 domains.
.NOTES
Version : v2.6 - See changelog at
http://www.ehloworld.com/596
Wish list : Better detection of Exchange server
: Set $DaysToWarn automatically based on Default Domain GPO setting
: Description for scheduled task
: Verify it's running on R2, as apparently only R2 has the AD commands?
: Determine password policy settings for FGPP users
: better logging
Rights Required : local admin on server it's running on
Sched Task Req'd : Yes - install mode will automatically create scheduled task
Lync Version : N/A
Exchange Version : 2007 or later
Author : M. Ali (original AD query), Pat Richard, Exchange MVP
Email/Blog/Twitter :
[email protected] http://www.ehloworld.com @patrichard
Dedicated Post :
http://www.ehloworld.com/318
Disclaimer : You running this script means you won't blame me if this breaks your stuff.
Info Stolen from : (original)
http://blogs.msdn.com/b/adpowershell/archive/2010/02/26/find-out-when-your-password-expires.aspx
: (date)
http://technet.microsoft.com/en-us/library/ff730960.aspx
: (calculating time)
http://blogs.msdn.com/b/powershell/archive/2007/02/24/time-till-we-land.aspx
http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/23fc5ffb-7cff-4c09-bf3e-2f94e2061f29/
http://blogs.msdn.com/b/adpowershell/archive/2010/02/26/find-out-when-your-password-expires.aspx
: (password decryption)
http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/f90bed75-475e-4f5f-94eb-60197efda6c6/
: (determine per user fine grained password settings)
http://technet.microsoft.com/en-us/library/ee617255.aspx
.LINK
http://www.ehloworld.com/318
.INPUTS
None. You cannot pipe objects to this script
.PARAMETER Demo
Runs the script in demo mode. No emails are sent to the user(s), and onscreen output includes those who are expiring soon.
.PARAMETER Preview
Sends a sample email to the user specified. Usefull for testing how the reminder email looks.
.PARAMETER PreviewUser
User name of user to send the preview email message to.
.PARAMETER Install
Create the scheduled task to run the script daily. It does NOT create the required Exchange receive connector.
.EXAMPLE
.\New-PasswordReminder.ps1
Description
Searches Active Directory for users who have passwords expiring soon, and emails them a reminder with instructions on how to change their password.
.EXAMPLE
.\New-PasswordReminder.ps1 -demo
Description
Searches Active Directory for users who have passwords expiring soon, and lists those users on the screen, along with days till expiration and policy setting
.EXAMPLE
.\New-PasswordReminder.ps1 -Preview -PreviewUser [username]
Description
Sends the HTML formatted email of the user specified via -PreviewUser. This is used to see what the HTML email will look like to the users.
.EXAMPLE
.\New-PasswordReminder.ps1 -install
Description
Creates the scheduled task for the script to run everyday at 6am. It will prompt for the password for the currently logged on user. It does NOT create the required Exchange receive connector.
#>
#Requires -Version 2.0
[cmdletBinding(SupportsShouldProcess = $true)]
param(
[parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
[switch]$Demo,
[parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
[switch]$Preview,
[parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
[switch]$Install,
[parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
[string]$PreviewUser
Write-Verbose "Setting variables"
[string]$Company = "Contoso Ltd"
[string]$OwaUrl = "https://mail.contoso.com"
[string]$PSEmailServer = "10.9.0.11"
[string]$EmailFrom = "Help Desk <[email protected]>"
[string]$HelpDeskPhone = "(586) 555-1010"
[string]$HelpDeskURL = "https://intranet.contoso.com/"
[string]$TranscriptFilename = $MyInvocation.MyCommand.Name + " " + $env:ComputerName + " {0:yyyy-MM-dd hh-mmtt}.log" -f (Get-Date)
[int]$global:UsersNotified = 0
[int]$DaysToWarn = 14
[string]$ImagePath = "http://www.contoso.com/images/new-passwordreminder.ps1"
[string]$ScriptName = $MyInvocation.MyCommand.Name
[string]$ScriptPathAndName = $MyInvocation.MyCommand.Definition
[string]$ou
[string]$DateFormat = "d"
if ($PreviewUser){
$Preview = $true
Write-Verbose "Defining functions"
function Set-ModuleStatus {
[cmdletBinding(SupportsShouldProcess = $true)]
param (
[parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true, HelpMessage = "No module name specified!")]
[string]$name
if(!(Get-Module -name "$name")) {
if(Get-Module -ListAvailable | ? {$_.name -eq "$name"}) {
Import-Module -Name "$name"
# module was imported
return $true
} else {
# module was not available (Windows feature isn't installed)
return $false
}else {
# module was already imported
return $true
} # end function Set-ModuleStatus
function Remove-ScriptVariables {
[cmdletBinding(SupportsShouldProcess = $true)]
param($path)
$result = Get-Content $path |
ForEach { if ( $_ -match '(\$.*?)\s*=') {
$matches[1] | ? { $_ -notlike '*.*' -and $_ -notmatch 'result' -and $_ -notmatch 'env:'}
ForEach ($v in ($result | Sort-Object | Get-Unique)){
Remove-Variable ($v.replace("$","")) -ErrorAction SilentlyContinue
} # end function Get-ScriptVariables
function Install {
[cmdletBinding(SupportsShouldProcess = $true)]
param()
http://technet.microsoft.com/en-us/library/cc725744(WS.10).aspx
$error.clear()
Write-Host "Creating scheduled task `"$ScriptName`"..."
$TaskPassword = Read-Host "Please enter the password for $env:UserDomain\$env:UserName" -AsSecureString
$TaskPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($TaskPassword))
# need to fix the issue with spaces in the path
schtasks /create /tn $ScriptName /tr "$env:windir\system32\windowspowershell\v1.0\powershell.exe -psconsolefile '$env:ExchangeInstallPath\Bin\exshell.psc1' -command $ScriptPathAndName" /sc Daily /st 06:00 /ru $env:UserDomain\$env:UserName /rp
$TaskPassword | Out-Null
if (!($error)){
Write-Host "done!" -ForegroundColor green
}else{
Write-Host "failed!" -ForegroundColor red
exit
} # end function Install
function Get-ADUserPasswordExpirationDate {
[cmdletBinding(SupportsShouldProcess = $true)]
Param (
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, HelpMessage = "Identity of the Account")]
[Object]$accountIdentity
PROCESS {
Write-Verbose "Getting the user info for $accountIdentity"
$accountObj = Get-ADUser $accountIdentity -properties PasswordExpired, PasswordNeverExpires, PasswordLastSet, name, mail
# Make sure the password is not expired, and the account is not set to never expire
Write-Verbose "verifying that the password is not expired, and the user is not set to PasswordNeverExpires"
if (((!($accountObj.PasswordExpired)) -and (!($accountObj.PasswordNeverExpires))) -or ($PreviewUser)) {
Write-Verbose "Verifying if the date the password was last set is available"
$passwordSetDate = $accountObj.PasswordLastSet
if ($passwordSetDate -ne $null) {
$maxPasswordAgeTimeSpan = $null
# see if we're at Windows2008 domain functional level, which supports granular password policies
Write-Verbose "Determining domain functional level"
if ($global:dfl -ge 4) { # 2008 Domain functional level
$accountFGPP = Get-ADUserResultantPasswordPolicy $accountObj
if ($accountFGPP -ne $null) {
$maxPasswordAgeTimeSpan = $accountFGPP.MaxPasswordAge
} else {
$maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
} else { # 2003 or ealier Domain Functional Level
$maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
if ($maxPasswordAgeTimeSpan -eq $null -or $maxPasswordAgeTimeSpan.TotalMilliseconds -ne 0) {
$DaysTillExpire = [math]::round(((New-TimeSpan -Start (Get-Date) -End ($passwordSetDate + $maxPasswordAgeTimeSpan)).TotalDays),0)
if ($preview){$DaysTillExpire = 1}
if ($DaysTillExpire -le $DaysToWarn){
Write-Verbose "User should receive email"
$PolicyDays = [math]::round((($maxPasswordAgeTimeSpan).TotalDays),0)
if ($demo) {Write-Host ("{0,-25}{1,-8}{2,-12}" -f $accountObj.Name, $DaysTillExpire, $PolicyDays)}
# start assembling email to user here
$EmailName = $accountObj.Name
$DateofExpiration = (Get-Date).AddDays($DaysTillExpire)
$DateofExpiration = (Get-Date($DateofExpiration) -f $DateFormat)
Write-Verbose "Assembling email message"
[string]$emailbody = @"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<table id="email" border="0" cellspacing="0" cellpadding="0" width="655" align="center">
<tr>
<td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="46" height="28" align="absMiddle">
if ($HelpDeskURL){
$emailbody += @"
<font style="font-size: 10px; color: #000000; line-height: 16px; font-family: Verdana, Arial, Helvetica, sans-serif">If this e-mail does not appear properly, please <a href="$HelpDeskURL" style="font-weight:
bold; font-size: 10px; color: #cc0000; font-family: verdana, arial, helvetica, sans-serif; text-decoration: underline">click here</a>.</font>
$emailbody += @"
</td>
</tr>
<tr>
if ($HelpDeskURL){
$emailbody += @"
<td height="121" align="left" valign="bottom"><a href="$HelpDeskURL"><img src="$ImagePath/header.gif" border="0" alt="Description: $ImagePath/header.gif"
width="655" height="121"></a></td>
}else{
$emailbody += @"
<td height="121" align="left" valign="bottom"><img src="$ImagePath/header.gif" border="0" alt="Description: $ImagePath/header.gif" width="655" height="121"></td>
$emailbody += @"
</tr>
<tr>
<td>
<table id="body" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="1" align="left" valign="top" bgcolor="#a8a9ad"><img src="$ImagePath/spacer50.gif" alt="Description: $ImagePath/spacer50.gif" width="1"
height="50"></td>
<td><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="46" height="106"></td>
<td id="text" width="572" align="left" valign="top" style="font-size: 12px; color: #000000; line-height: 17px; font-family: Verdana, Arial, Helvetica, sans-serif">
if ($DaysTillExpire -le 1){
$emailbody += @"
<div align='center'>
<table border='0' cellspacing='0' cellpadding='0' style='width:510px; background-color: white; border: 0px;'>
<tr>
<td align='right'><img width='36' height='28' src='$ImagePath/image001b.gif' alt='Description: $ImagePath/image001b.gif'></td>
<td style="font-family: verdana; background: #E12C10; text-align: center; padding: 0px; font-size: 9.0pt; color: white">ALERT: You must change your password today or you will be locked out!</td>
<td align='left'><img border='0' width='14' height='28' src='$ImagePath/image005b.gif' alt='Description: $ImagePath/image005b.gif'></td>
</tr>
</table>
</div>
$emailbody += @"
<p style="font-weight: bold">Hello, $EmailName,</p>
<p>It's change time again! Your $company password expires in <span style="background-color: red; color: white; font-weight: bold;"> $DaysTillExpire </span> day(s), on $DateofExpiration.</p>
<p>Please use one of the methods below to update your password:</p>
<ol>
<li>$company office computers and Terminal Server users: You may update your password on your computer by pressing Ctrl-Alt-Delete and selecting 'Change Password' from the available options. If you use a $company laptop in addition
to a desktop PC, be sure and read #3 below.</li>
<li>Remote Outlook Client, Mac, and/or Outlook Web App users: If you only access our email system, please use the following method to easily change your password:</li>
<ul>
<li>Log into <a href="$owaurl">Outlook Web App</a> using Internet Explorer (PC) or Safari or Firefox (Mac).</li>
<li>Click on the Options button in the upper right corner of the page.</li>
<li>Select the "Change Password" link to change your password.</li>
<li>Enter your current password, then your new password twice, and click Save</li>
<li><span style="font-weight: bold">NOTE:</span> You will now need to use your new password when logging into Outlook Web App, Outlook 2010, SharePoint, Windows Mobile (ActiveSync) devices, etc. Blackberry
Enterprise Users (BES) will not need to update their password. Blackberry Internet Service (BIS) users will be required to use their new password on their device.</li>
</ul>
<li>$company issued laptops: If you have been issued a $company laptop, you must be in a corporate office and directly connected to the company network to change your password. If you also use a desktop PC in the office, you must
remember to always update your domain password on the laptop first. Your desktop will automatically use the new password.</li>
<ul>
<li>Log in on laptop</li>
<li>Press Ctrl-Alt-Delete and select 'Change Password' from the available options.</li>
<li>Make sure your workstation (if you have one) has been logged off any previous sessions so as to not cause conflict with your new password.</li>
</ul>
</ol>
<p>Think you've got a complex password? Run it through the <a href="The">http://www.passwordmeter.com/">The Password Meter</a></p>
<p>Think your password couldn't easily be hacked? See how long it would take: <a href="How">http://howsecureismypassword.net/">How Secure Is My Password</a></p>
<p>Remember, if you do not change your password before it expires on $DateofExpiration, you will be locked out of all $company Computer Systems until an Administrator unlocks your account.</p>
<p>If you are traveling or will not be able to bring your laptop into the office before your password expires, please call the number below for additional instructions.</p>
<p>You will continue to receive these emails daily until the password is changed or expires.</p>
<p>Thank you,<br />
The $company Help Desk<br />
$HelpDeskPhone</p>
if ($accountFGPP -eq $null){
$emailbody += @"
<table style="background-color: #dedede; border: 1px solid black">
<tr>
<td style="font-size: 12px; color: #000000; line-height: 17px; font-family: Verdana, Arial, Helvetica, sans-serif"><b>$company Password Policy</b>
<ul>
<li>Your password must have a minimum of a $MinPasswordLength characters.</li>
<li>You may not use a previous password.</li>
<li>Your password must not contain parts of your first, last, or logon name.</li>
<li>Your password must be changed every $PolicyDays days.</li>
if ($PasswordComplexity){
Write-Verbose "Password complexity"
$emailbody += @"
<li>Your password requires a minimum of two of the following three categories:</li>
<ul>
<li>1 upper case character (A-Z)</li>
<li>1 lower case character (a-z)</li>
<li>1 numeric character (0-9)</li>
</ul>
$emailbody += @"
<li>You may not reuse any of your last $PasswordHistory passwords</li>
</ul>
</td>
</tr>
</table>
$emailbody += @"
</td>
<td width="49" align="left" valign="top"><img src="$ImagePath/spacer50.gif" alt="" width="49" height="50"></td>
<td width="1" align="left" valign="top" bgcolor="#a8a9ad"><img src="$ImagePath/spacer50.gif" alt="Description: $ImagePath/spacer50.gif" width="1"
height="50"></td>
</tr>
</table>
<table id="footer" border="0" cellspacing="0" cellpadding="0" width="655">
<tr>
<td><img src="$ImagePath/footer.gif" alt="Description: $ImagePath/footer.gif" width="655" height="81"></td>
</tr>
</table>
<table border="0" cellspacing="0" cellpadding="0" width="655" align="center">
<tr>
<td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="36" height="1"></td>
<td align="middle" valign="top"><font face="Verdana" size="1" color="#000000"><p>This email was sent by an automated process.
if ($HelpDeskURL){
$emailbody += @"
If you would like to comment on it, please visit <a href="$HelpDeskURL"><font color="#ff0000"><u>click here</u></font></a>
$emailbody += @"
</p><p style="color: #009900;"><font face="Webdings" size="4">P</font> Please consider the environment before printing this email.</p></font>
</td>
<td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="36" height="1"></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
if (!($demo)){
$emailto = $accountObj.mail
if ($emailto){
Write-Verbose "Sending demo message to $emailto"
Send-MailMessage -To $emailto -Subject "Your password expires in $DaysTillExpire day(s)" -Body $emailbody -From $EmailFrom -Priority High -BodyAsHtml
$global:UsersNotified++
}else{
Write-Verbose "Can not email this user. Email address is blank"
} # end function Get-ADUserPasswordExpirationDate
if ($install){
Write-Verbose "Install mode"
Install
Write-Verbose "Checking for ActiveDirectory module"
if ((Set-ModuleStatus ActiveDirectory) -eq $false){
$error.clear()
Write-Host "Installing the Active Directory module..." -ForegroundColor yellow
Set-ModuleStatus ServerManager
Add-WindowsFeature RSAT-AD-PowerShell
if ($error){
Write-Host "Active Directory module could not be installed. Exiting..." -ForegroundColor red;
if ($transcript){Stop-Transcript}
exit
Write-Verbose "Getting Domain functional level"
$global:dfl = (Get-AdDomain).DomainMode
# Get-ADUser -filter * -properties PasswordLastSet,EmailAddress,GivenName -SearchBase "OU=Users,DC=domain,DC=test" |foreach {
if (!($PreviewUser)){
if ($ou){
Write-Verbose "Filtering users to $ou"
$users = Get-AdUser -filter * -SearchScope subtree -SearchBase $ou -ResultSetSize $null
}else{
$users = Get-AdUser -filter * -ResultSetSize $null
}else{
Write-Verbose "Preview mode"
$users = Get-AdUser $PreviewUser
if ($demo){
Write-Verbose "Demo mode"
# $WhatIfPreference = $true
Write-Host "`n"
Write-Host ("{0,-25}{1,-8}{2,-12}" -f "User", "Expires", "Policy") -ForegroundColor cyan
Write-Host ("{0,-25}{1,-8}{2,-12}" -f "========================", "=======", "===========") -ForegroundColor cyan
Write-Verbose "Setting event log configuration"
$evt = new-object System.Diagnostics.EventLog("Application")
$evt.Source = $ScriptName
$infoevent = [System.Diagnostics.EventLogEntryType]::Information
$EventLogText = "Beginning processing"
$evt.WriteEntry($EventLogText,$infoevent,70)
Write-Verbose "Getting password policy configuration"
$DefaultDomainPasswordPolicy = Get-ADDefaultDomainPasswordPolicy
[int]$MinPasswordLength = $DefaultDomainPasswordPolicy.MinPasswordLength
# this needs to look for FGPP, and then default to this if it doesn't exist
[bool]$PasswordComplexity = $DefaultDomainPasswordPolicy.ComplexityEnabled
[int]$PasswordHistory = $DefaultDomainPasswordPolicy.PasswordHistoryCount
ForEach ($user in $users){
Get-ADUserPasswordExpirationDate $user.samaccountname
Write-Verbose "Writing summary event log entry"
$EventLogText = "Finished processing $global:UsersNotified account(s). `n`nFor more information about this script, run Get-Help .\$ScriptName. See the blog post at
http://www.ehloworld.com/318."
$evt.WriteEntry($EventLogText,$infoevent,70)
# $WhatIfPreference = $false
# Remove-ScriptVariables -path $MyInvocation.MyCommand.Name
Remove-ScriptVariables -path $ScriptPathAndNameHi petro_jemes,
Just a little claritification, you need to add the value to the variable "[string]$ou", and also change the language in the variable "$emailbody" in the function "Get-ADUserPasswordExpirationDate".
I hope this helps. -
How to run Powershell script (function) through Windows Task Schduler ??
Hello All,
i have Powershell script which is created as a function. I have to give parameters to run the script. And it is working fine. Now i want to run this script through windows task scheduler but it is not working. I dont know how to call powershell function
through task scheduler.
From command line i run it like this:
. c:\script\Get-ServiceStatusReport.ps1
dir function:get-service*
Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
In windows Task scheduler I am giving this: it runs but i dont receive any output :
Program/Script:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Parameter:
-file ". 'Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk'"
Please HELP !!!Thanks for the reply:
The script is already saved as Get-ServiceStatusReport.ps1 .
On powershell it does not run like .\Get-ServiceStatusReport.ps1 (parameter).
But i have to call it as function:
Like this:
Get-ServiceStatusReport -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk
As you said:
I tried to run it like this:
Program/Script:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Parameter:
-file "c:\script\Get-ServiceStatusReport.ps1 -ComputerList C:\script\server.txt -includeService "Exchange","W32Time" -To [email protected] -From [email protected] -SMTPMail mail01.xxx.gov.pk'"
But its not working , on scheduler its giving error: (0xFFFD0000)
Please HELP !!!
WHOLE SCRIPT:
function Get-ServiceStatusReport
param(
[String]$ComputerList,[String[]]$includeService,[String]$To,[String]$From,[string]$SMTPMail
$script:list = $ComputerList
$ServiceFileName= "c:\ServiceFileName.htm"
New-Item -ItemType file $ServiceFilename -Force
# Function to write the HTML Header to the file
Function writeHtmlHeader
param($fileName)
$date = ( get-date ).ToString('yyyy/MM/dd')
Add-Content $fileName "<html>"
Add-Content $fileName "<head>"
Add-Content $fileName "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"
Add-Content $fileName '<title>Service Status Report </title>'
add-content $fileName '<STYLE TYPE="text/css">'
add-content $fileName "<!--"
add-content $fileName "td {"
add-content $fileName "font-family: Tahoma;"
add-content $fileName "font-size: 11px;"
add-content $fileName "border-top: 1px solid #999999;"
add-content $fileName "border-right: 1px solid #999999;"
add-content $fileName "border-bottom: 1px solid #999999;"
add-content $fileName "border-left: 1px solid #999999;"
add-content $fileName "padding-top: 0px;"
add-content $fileName "padding-right: 0px;"
add-content $fileName "padding-bottom: 0px;"
add-content $fileName "padding-left: 0px;"
add-content $fileName "}"
add-content $fileName "body {"
add-content $fileName "margin-left: 5px;"
add-content $fileName "margin-top: 5px;"
add-content $fileName "margin-right: 0px;"
add-content $fileName "margin-bottom: 10px;"
add-content $fileName ""
add-content $fileName "table {"
add-content $fileName "border: thin solid #000000;"
add-content $fileName "}"
add-content $fileName "-->"
add-content $fileName "</style>"
Add-Content $fileName "</head>"
Add-Content $fileName "<body>"
add-content $fileName "<table width='100%'>"
add-content $fileName "<tr bgcolor='#CCCCCC'>"
add-content $fileName "<td colspan='4' height='25' align='center'>"
add-content $fileName "<font face='tahoma' color='#003399' size='4'><strong>Service Stauts Report - $date</strong></font>"
add-content $fileName "</td>"
add-content $fileName "</tr>"
add-content $fileName "</table>"
# Function to write the HTML Header to the file
Function writeTableHeader
param($fileName)
Add-Content $fileName "<tr bgcolor=#CCCCCC>"
Add-Content $fileName "<td width='10%' align='center'>ServerName</td>"
Add-Content $fileName "<td width='50%' align='center'>Service Name</td>"
Add-Content $fileName "<td width='10%' align='center'>status</td>"
Add-Content $fileName "</tr>"
Function writeHtmlFooter
param($fileName)
Add-Content $fileName "</body>"
Add-Content $fileName "</html>"
Function writeDiskInfo
param($filename,$Servername,$name,$Status)
if( $status -eq "Stopped")
Add-Content $fileName "<tr>"
Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$servername</td>"
Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$name</td>"
Add-Content $fileName "<td bgcolor='#FF0000' align=left ><b>$Status</td>"
Add-Content $fileName "</tr>"
else
Add-Content $fileName "<tr>"
Add-Content $fileName "<td >$servername</td>"
Add-Content $fileName "<td >$name</td>"
Add-Content $fileName "<td >$Status</td>"
Add-Content $fileName "</tr>"
writeHtmlHeader $ServiceFileName
Add-Content $ServiceFileName "<table width='100%'><tbody>"
Add-Content $ServiceFileName "<tr bgcolor='#CCCCCC'>"
Add-Content $ServiceFileName "<td width='100%' align='center' colSpan=3><font face='tahoma' color='#003399' size='2'><strong> Service Details</strong></font></td>"
Add-Content $ServiceFileName "</tr>"
writeTableHeader $ServiceFileName
#Change value of the following parameter as needed
$InlcudeArray=@()
#List of programs to exclude
#$InlcudeArray = $inlcudeService
Foreach($ServerName in (Get-Content $script:list))
$service = Get-Service -ComputerName $servername
if ($Service -ne $NULL)
foreach ($item in $service)
#$item.DisplayName
Foreach($include in $includeService)
write-host $inlcude
if(($item.serviceName).Contains($include) -eq $TRUE)
Write-Host $item.MachineName $item.name $item.Status
writeDiskInfo $ServiceFileName $item.MachineName $item.name $item.Status
Add-Content $ServiceFileName "</table>"
writeHtmlFooter $ServiceFileName
function Validate-IsEmail ([string]$Email)
return $Email -match "^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"
Function sendEmail
param($from,$to,$subject,$smtphost,$htmlFileName)
[string]$receipients="$to"
$body = Get-Content $htmlFileName
$body = New-Object System.Net.Mail.MailMessage $from, $receipients, $subject, $body
$body.isBodyhtml = $true
$smtpServer = $MailServer
$smtp = new-object Net.Mail.SmtpClient($smtphost)
$validfrom= Validate-IsEmail $from
if($validfrom -eq $TRUE)
$validTo= Validate-IsEmail $to
if($validTo -eq $TRUE)
$smtp.UseDefaultCredentials = $true;
$smtp.Send($body)
write-output "Email Sent!!"
else
write-output "Invalid entries, Try again!!"
$date = ( get-date ).ToString('yyyy/MM/dd')
sendEmail -from $From -to $to -subject "Service Status - $Date" -smtphost $SMTPMail -htmlfilename $ServiceFilename -
I am trying to run a PowerShell script to upload files into a SharePoint site in an Azure environment...the script works fine on my local machine, but every time I run it in Azure (remotely), I get errors. Here is what my simple script looks like...
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
Write-Host "Loading Sharepoint Module "
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
Add-PSSnapin -Name Microsoft.SharePoint.PowerShell
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell) -eq $null )
Write-Host "Failed to load sharepoint snap-in. Could not proceed further, Aborting ..."
Exit
#Script settings
$webUrl = "http://sampleWebUrl"
$docLibraryName = "My Documents"
$docLibraryUrlName = "My%20Documents"
$localFolderPath = get-childitem "C:\Upload\Test Upload\My Documents\" -recurse
$contentType = "ContenttType1"
#Open web and library
$web = Get-SPWeb $webUrl
write-host "Web:" $web
$docLibrary = $web.Lists[$docLibraryName]
write-host "docLibrary:" $docLibrary
$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
write-host "files:" $files
If ($contentType = "ContenttType1")
#Open file
$fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()
# Gather the file name
$FileName = $File.Name
#remove file extension
$NewName = [IO.Path]::GetFileNameWithoutExtension($FileName)
#split the file name by the "-" character
$FileNameArray = $NewName.split("_")
$check = $FileNameArray.Length
#Add file
$folder = $web.getfolder($docLibrary.rootFolder.URL)
write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
$spFile = $folder.Files.Add($folder.Url + "/" + $file.Name, [System.IO.Stream]$fileStream, $true)
$spItem = $spFile.Item
write-host "Success"
write-host "SP File:" $spFile
write-host "SP Item" $spItem
#populate columns
$spItem["Column1"] = $FileNameArray[0]
$spItem["Column2"] = $FileNameArray[1]
$spItem.Update()
$fileStream.Close();
Again, I can run this on my local machine and it works just fine, but when I attempt to run it on the Azure environment I get this error...
Get-Item : Cannot find path 'C:\powershellscripts\12653_B7045.PDF' because it does not exist.
At C:\PowerShellScripts\Upload-FilesIntoSharePointTester.ps1:32 char:42
+ $files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\powershellscripts\12653_B7045.PDF:String) [Get-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
What strikes me first is the fact that the file its looking for is in the "C:\Upload\Test Upload\My Documents\" directory, but the error keeps saying "C:\powershellscripts\" which is where my script resides and not the files I want to
upload into SharePoint. When I step through the code, all the variables are holding the correct values. The $localFolderPath shows the name of files that I am attempting to upload, so it recognizes them. But once I step through this particular line of code,
the error occurs...
$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()
Is this an error caused because I am remoting into the Azure environment? Has anyone dealt with this issue before? I would really appreciate the help. Thanks
Update: quick thing I noticed is that these two lines of code are returning null values. Again, is this handled differently in Azure or remotely? I ask cause this is the way I know how to do this, locally.
$docLibrary = $web.Lists[$docLibraryName]
$files = ([System.IO.DirectoryInfo] (Get-Item $localFolderPath)).GetFiles()"...square brackets are wildcard characters in Windows PowerShell..."
When you use cd without a parameter it uses the -Path parameter. In this case you'll have to escape the square brackets so they are not considered wildcards. Each of the commands in the first example does the exact same thing.
cd 'Learn PowerShell `[Do Whatever`]'
cd -Path 'Learn PowerShell `[Do Whatever`]'
cd (or Set-Location) also has a literal path parameter (-LiteralPath) that does not require using an escape character (`) before each of the brackets. Hope this helps.
cd -LiteralPath 'Learn PowerShell [Do Whatever]' -
I'm just learning PS scripting and Chef Programming, so I'm sure I'm missing something simple. I'm trying to run a recipe that is using PS as the interpreter. I've ensured I'm running PS in 64 bit with admin privileges, and have Imported the ServerManager
module. I even added a line to my script to have it run that first, but am still receiving an error in my script. I'm running this on a VM of Server 2008R2
Script:
powershell_script 'Install IIS' do
code "Import-Module ServerManager -passthru"
code "Add-WindowsFeature Web-Server"
guard_interpreter :powershell_script
not_if "(Get-WindowsFeature -Name Web-Server).Installed"
end
Error:
PS C:\Users\Administrator\chef-repo> chef-apply webserver.rb
Recipe: (chef-apply cookbook)::(chef-apply recipe)
* powershell_script[Install IIS] action run
================================================================================
Error executing action `run` on resource 'powershell_script[Install IIS]'
================================================================================
Mixlib::ShellOut::ShellCommandFailed
Expected process to exit with [0], but received '1'
---- Begin output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat
None -File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
STDOUT:
STDERR: The term 'Add-WindowsFeature' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
---- End output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat No
ne -File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
Ran "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -File "C:/Us
ers/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" returned 1
Resource Declaration:
# In webserver.rb
1: powershell_script 'Install IIS' do
2: code "Import-Module ServerManager -passthru"
3: code "Add-WindowsFeature Web-Server"
4: guard_interpreter :powershell_script
5: not_if "(Get-WindowsFeature -Name Web-Server).Installed"
6: end
Compiled Resource:
# Declared in webserver.rb:1:in `run_chef_recipe'
powershell_script("Install IIS") do
action "run"
retries 0
retry_delay 2
guard_interpreter :powershell_script
command "\"powershell.exe\" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -Fi
le \"C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1\""
backup 5
returns 0
code "Add-WindowsFeature Web-Server"
interpreter "powershell.exe"
cookbook_name "(chef-apply cookbook)"
recipe_name "(chef-apply recipe)"
not_if "(Get-WindowsFeature -Name Web-Server).Installed"
end
[2014-12-24T10:29:56-08:00] FATAL: Stacktrace dumped to C:/chef/cache/chef-stacktrace.out
[2014-12-24T10:29:56-08:00] FATAL: Mixlib::ShellOut::ShellCommandFailed: powershell_script[Install IIS] ((chef-apply coo
kbook)::(chef-apply recipe) line 1) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0
], but received '1'
---- Begin output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None
-File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
STDOUT:
STDERR: The term 'Add-WindowsFeature' is not recognized as the name of a cmdlet, function, script file, or operable prog
ram. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
---- End output of "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -
File "C:/Users/ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" ----
Ran "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -File "C:/Users/
ADMINI~1/AppData/Local/Temp/chef-script20141224-432-mxaa9u.ps1" returned 1Hi There,
We have a application named Microsoft SCOM. That as well requires ISS to be installed. I tried this long back and it worked in powershell. Below is the powershell script i used to install IIS and some specific features from it. Hope it helps in altering
it and making one of your own script.
1. Launch the PowerShell command
prompt
Run this command
Import-Module ServerManager
3. Press Enter
4. Run this
command
Add-WindowsFeature NET-Framework-Core,Web-Metabase,Web-WMI,Web-Static-Content,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Asp-Net,Web-Net-Ext,Web-ISAPI-Ext,Web-ISAPI-Filter,Web-Filtering,Web-Windows-Auth,
Web-Mgmt-Console –restart
Gautam.75801 -
Why MicroSoft 2000 SR needed while running the script using test manager???
hi all,
whenever I trying to run a script using test manager,one POP-UP comes which starts installing MICROSOFT 2000 SR.
and in few seconds it complaining for some missing component,
can any body tell me why it is happening.
what is the need of Microsoft 2000 SR while running the script in test manager.
tnx
USOniUSoni
I have seen that problem happening before, even that i was never able to figure out why, something that you can try is changing the service log in credentials for both:
Oracle Application Testing Suite Agent Service
Oracle Application Testing Suite Application Service
and use a proper user with admin rights.
let me know if that helped
Regards
Alex -
Run PowerShell Script from a Event Receiver
Hi,
Just looking around on the net for some documentation for running a PowerShell script via an Event Receiver. We want to be able to make changes to the script and not change anything in the ER.
Sadly using a workflow isn't an option here.
Looking for websites that give some examples really, or if anyone has done this.
Regards
If this is helpful please mark it so. Also if this solved your problem mark as answer.Hi TemPart:
string cmdArg = “C:\\Scripts\\test.ps1″;
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(cmdArg);
Collection [PSObject] results = pipeline.Invoke(); // please Update [] bracket with less then and greater then bracket
runspace.Close();
Had to modify this slightly:
string cmdArg = “Powershell.exe -file C:\\Scripts\\test.ps1″;
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(cmdArg);
Collection [PSObject] results = pipeline.Invoke(); // please Update [] bracket with less then and greater then bracket
runspace.Close();
If this is helpful please mark it so. Also if this solved your problem mark as answer.
Maybe you are looking for
-
Can anybody explain when/how Pages 5.1 uses "author color?" No matter what I set as the author color, Pages picks a different color for the deletion/insertion text. Sometimes green, sometimes organge, etc. It wouldn't matter except I have trouble se
-
Home.uix file not found for Enterprise Manager 10g R1
I installed Oracle 10 R1, Enterprise manager was not working. It was giving error 404 file not found. I checked the error log, found that home.uix file was not found. So is there any source from net to get any uix missing files. or what else could b
-
Hi, Small suggestion but I feel its an important one, There needs to be an apps suggestions thread, broken downn into sub catagories where customers can go and post suggestions for new apps and delvelopers can go and get new ideas for creating them.
-
Dear Sirs, Is there something like alerts in SAP? Like we have in microsoft outlook? When we have a meeting to attend, we insert date and time and the system throws up a pop-up alert 30 minutes in advance. Similarly, when I enter a statistical postin
-
Export failed, archive corrupt error
Hi - I am getting an Export failed, archive may be corrupt error when I try to export my EAR from Workshop 9.2 MP1. (Oddly enough, if I build my EAR with the exported Ant scripts, that works. I can deploy and run this EAR). An the EAR is truly corrup