Powershell script error adding integers
Hi All, I am trying to add integers but the script is not running. I am using variable "a" with the same line of thinking as
$arg in $args
$a in $as
# create a script thats adds numbers using foreach
# put an if statement if the numbers are not valid
My script begins here:
set-psdebug -strict
$total = 0
foreach($a in $as)
if ( $a -as[int] -eq $null)
{ Write-host "this is not a valid number"
exit 1
$total += $a
Write-host "The total is $total"
I am calling my script with the following line: .\finalexam\foreachadd.ps1 6 6 i
The error is :
The variable '$as' cannot be retrieved because it has not been set.
At C:\cmd.practise\finalexam\foreachadd.ps1:8 char:15
+ foreach($a in $as)
+ ~~~
+ CategoryInfo : InvalidOperation: (as:String) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined
Thank-you
SQL 75
(LearningPowerhsell)
You need to go back and study the very initial basics of PowerShell. You are repeatedly guessing wrong and misunderstanding how this works. Without the fundamentals you will be forever lost.
Try to understand why and how the following works. Read the basics of using PowerShell variables and loops.
$as=1,2,'x',4,5,'z'
$total=0
foreach($a in $as){
if($a -as [int]){
$total+=$a
}else{
Write-host "$a cannot be converted to a valid integer 32"
Write-host "The total is $total"
You also need to learn how to format your code. Tat would make it easier for you too see your mistakes.
\_(ツ)_/
Similar Messages
-
Powershell script assistance - adding another property to existing script
This is not my script but was written by Richard L. Mueller. It works perfectly for us but I would like to know if the account is enabled or disabled when the output is created. Basically it would output the name, lastlogon and then either enabled or disabled.
I've attempted to add a new property by adding another " $Searcher.PropertiesToLoad.Add" and "$Result.Properties.Item ".
It works fine if I add something like "givenName" but I can't find the property name to show if the account is enabled or disabled.
The entire script is shown below:
# PSLastLogon.ps1
# PowerShell script to determine when each user in the domain last
# logged on.
# Copyright (c) 2011 Richard L. Mueller
# Hilltop Lab web site - http://www.rlmueller.net
# Version 1.0 - March 16, 2011
# This program queries every Domain Controller in the domain to find the
# largest (latest) value of the lastLogon attribute for each user. The
# last logon dates for each user are converted into local time. The
# times are adjusted for daylight savings time, as presently configured.
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the copyright owner above has no warranty, obligations,
# or liability for such use.
Trap {"Error: $_"; Break;}
$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"
$Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
$Searcher.PropertiesToLoad.Add("distinguishedName") > $Null
$Searcher.PropertiesToLoad.Add("lastLogon") > $Null
# Create hash table of users and their last logon dates.
$arrUsers = @{}
# Enumerate all Domain Controllers.
ForEach ($DC In $D.DomainControllers)
$Server = $DC.Name
$Searcher.SearchRoot = "LDAP://$Server/" + $Domain.distinguishedName
$Results = $Searcher.FindAll()
ForEach ($Result In $Results)
$DN = $Result.Properties.Item("distinguishedName")
$LL = $Result.Properties.Item("lastLogon")
If ($LL.Count -eq 0)
$Last = [DateTime]0
Else
$Last = [DateTime]$LL.Item(0)
If ($Last -eq 0)
$LastLogon = $Last.AddYears(1600)
Else
$LastLogon = $Last.AddYears(1600).ToLocalTime()
If ($arrUsers.ContainsKey("$DN"))
If ($LastLogon -gt $arrUsers["$DN"])
$arrUsers["$DN"] = $LastLogon
Else
$arrUsers.Add("$DN", $LastLogon)
# Output latest last logon date for each user.
$Users = $arrUsers.Keys
ForEach ($DN In $Users)
$Date = $arrUsers["$DN"]
"$DN;$Date"It is part of the userAccountControl attribute. Retrieve that attribute for each user and test if the ADS_UF_ACCOUNTDISABLE bit (2) is set.
-- Bill Stewart [Bill_Stewart] -
Powershell Script Error, its saying The term is not recognized as the name of cmdlet
Hi,
When i am running following script into powershell, getting this error. i was not able to find out what could be the cause?Please
help me out.
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
functionCreate-SPFoldersBulk
Param
[parameter(Mandatory=$true)][string]$SiteUrl,
[parameter(Mandatory=$true)][string]$LibraryName,
[parameter(Mandatory=$true)][string]$CSVPath
# Import CSV
[array]$FolderList
= Import-Csv
$CSVPath
# Script Variables
$spWeb
= Get-SPWeb
$SiteUrl
$spList
= $spWeb.Lists[$LibraryName]
Foreach
($folderGroup
in
$FolderList) {
# Create Parent Folder
$parentFolder
= $spList.Folders.Add("",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$folderGroup.Root)
$parentFolder.Update()
Write-Host "The Parent folder" $folderGroup.Root "was
successfully created" -foregroundcolor Green
# Loop variables
$i = 1
$col = "S"
$colID = $col + $i
While ($folderGroup.$colID -ne $null)
$newSubfolder = $splist.Folders.Add($parentFolder.Folder.ServerRelativeUrl,
[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$folderGroup.$colID)
$newSubfolder.Update()
Write-Host "The subfolder" $folderGroup.$ColID
"was successfully created"
-foregroundcolor
Cyan
$i++
$colID
= $col
+ $i
$spWeb.Dispose()Well assuming that is the entirety of your Create-SPFoldersBulk.ps1 script then the first issue is that it does currently do anything. Your script defines a function but then doesn't call it.
You're then running the script correctly as :
.\Create-SPFoldersBulk.ps1
and then I'm guessing you're trying to run the function, but that won't work from a command line. That's why you're getting the error, PowerShell doesn't know about the function outside of the code execution, and won't run the script instead since you haven't
added .\ before it.
If you really want it to be using a function then you'll need code later in the script to call that function, eg add the function call you entered at the prompt into the script at the bottom, and then run the script like you did initially, or if you're looking
to be able to run the script and be able to pass those parameters to it from the prompt then you probably want to adjust the script to :
Param (
[parameter(Mandatory=$true)][string]$SiteUrl,
[parameter(Mandatory=$true)][string]$LibraryName,
[parameter(Mandatory=$true)][string]$CSVPath
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
# Import CSV
[array]$FolderList = Import-Csv $CSVPath
# Script Variables
$spWeb = Get-SPWeb $SiteUrl
$spList = $spWeb.Lists[$LibraryName]
Foreach ($folderGroup in $FolderList) {
# Create Parent Folder
$parentFolder = $spList.Folders.Add("",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$folderGroup.Root)
$parentFolder.Update()
Write-Host "The Parent folder" $folderGroup.Root "was successfully created" -foregroundcolor Green
# Loop variables
$i = 1
$col = "S"
$colID = $col + $i
While ($folderGroup.$colID -ne $null)
$newSubfolder = $splist.Folders.Add($parentFolder.Folder.ServerRelativeUrl, [Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$folderGroup.$colID)
$newSubfolder.Update()
Write-Host "The subfolder" $folderGroup.$ColID "was successfully created" -foregroundcolor Cyan
$i++
$colID = $col + $i
$spWeb.Dispose()
and then call the script from the prompt as :
.\Create-SPFoldersBulk.ps1 -SiteUrl "https://spdev.baordbooks.com/legal/DAP/" -LibraryName "DAP Documents" -CSVPath "C:\Script_Files\folderList.csv" -
Error while adding the app in the sharepoint(2013) page through powershell script
Hi,
I have created one powershell script to uninstall and install the sharepoint 2013 apps. The code is working fine, but after adding the app in the page I am getting the error "
Internet Explorer can not display the webpage".
If I am deploying the app through Visual Studio, its getting deployed successfully and I am getting an option to trust the app.And I am able to add it in the page. But this permission is not coming when I am installing the app using power shell.
Please let me know whether to do any modifications to the power shell script.
Thanks.
PradeepHi,
We are using sharepoint hosted app.
Below is the script to uninstall and install the app.
cls
Add-PSSnapin Microsoft.SharePoint.PowerShell –ea SilentlyContinue
# uninstall the app
Write-Host "uninstallation of app"
$InstalledSPApps = Get-SPAppInstance -Web "http://mySharepointSite.xyz.com"
$appToUninstall = $InstalledSPApps | where {$_.Title -eq 'myCustomSharepointApp'}
if ($appToUninstall -ne $null)
Uninstall-SPAppInstance -Identity $appToUninstall ;
Write-Host "uninstalled successfully"
# Import-SPAppPackage
Write-Host "Import the app"
pause
$sourceApp = ([microsoft.sharepoint.administration.spappsource]::RemoteObjectModel);
$myspapp = Import-SPAppPackage -Path "D:\SharePoint 2013\AppsSolution\myCustomSharepointApp.app" -Site "http://mySharepointSite.xyz.com" -Source $sourceApp ;
Write-Host "Enter to install the app"
pause
$app = Install-SPApp -Web "http://mySharepointSite.xyz.com" -Identity $myspapp;
$AppName = $app.Title;
Write-Host "app '$AppName' registered"
pause
$appInstance = Get-SPAppInstance -Web "http://mySharepointSite.xyz.com" | where-object {$_.Title -eq $AppName};
$counter = 1;
$maximum = 150;
$sleeptime = 2;
Write-Host -ForegroundColor White "Please wait..." -NoNewline;
pause
while (($appInstance.Status -eq ([Microsoft.SharePoint.Administration.SPAppInstanceStatus]::Installing)) -and ($counter -lt $maximum))
Write-Host "." -NoNewline;
sleep $sleeptime;
$counter++;
$appInstance = Get-SPAppInstance -Web "http://mySharepointSite.xyz.com" | where-object {$_.Title -eq $AppName}
pause
if ($appInstance.Status -eq [Microsoft.SharePoint.Administration.SPAppInstanceStatus]::Installed)
Write-Host "The App was successfully installed.";
$appUrl = $appInstance.AppWebFullUrl;
Write-Host -ForegroundColor White "The App is available at '$appUrl'."; -
PowerShell script : Directory object not found error in Get-ADGroupMember
I am new in powershell scripting. I am writing a script to add users in different AD Groups. while doing so I do the following:
Check if the user already exist in the group:
$mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAccountName -eq $sam}
If user does not exist then add the user to the group.
When I manually run the script its runs flawless, without any errors. But when I schedule the script to run it gives an error as follows:
3/30/2015 8:32:15 AM Directory object not foundAt + $mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAc ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~ Error at Line:$mbr_exist = Get-ADGroupMember
$grpname | Where-Object {$_.SamAccountName -eq $sam}
The strange thing is the user for which it throws the error is present in the group.I am not sure why this error is occurring when scheduled. Can any one please help? All the suggestions will be appreciated
Note: (The script is scheduled using Windows Task Scheduler)
try
# # Initialize the variables we will use
$status = 'false'
$drivename = "H:"
$sysdate = Get-Date -UFormat "%m_%d_%Y"
$foldername = $drivename + "\Script_Result\PowershellData"+ $sysdate
$backup_folder = "$foldername\AD_Groups_Backup"
$updatedGroup = "$foldername\Updated_AD_Groups_LogFiles"
$LogFilePath = "$foldername\Log_Update_ADGroups"+$sysdate+".log"
# # Initialize the arrays we will use
$GroupArray = @()
# # maintain log of program startup
$logdate = get-date
$logdate.ToString() + "`tStarted script to Update AD user Groups..." | Out-File -FilePath $LogFilePath
# # Create a sub folder to store the backup files
$fileexist = Test-Path $backup_folder -PathType Container
if($fileexist -ne 'False')
New-Item -ItemType Directory $backup_folder
# # Create a sub folder to store Updated AD group Log files
$fileexist = Test-Path $updatedGroup -PathType Container
if($fileexist -ne 'False')
New-Item -ItemType Directory $updatedGroup
# # Take back up of the AD groups data
Get-ADGroupMember -Identity "Group1" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
Get-ADGroupMember -Identity "Group2" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
Get-ADGroupMember -Identity "Group3" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
Get-ADGroupMember -Identity "Group4" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
(an so on..... 11 such groups )
# # Fetch AD Users data
$ADusers = Get-ADUser -filter {(EmployeeNumber -gt 1) -and (EmployeeNumber -ne "N/A") -and (Enabled -eq $true)} -Properties * | Sort-Object -Property EmployeeNumber
$ADusers.Count
foreach($u in $ADusers)
$sam = $u.SamAccountName
$empnum = $u.EmployeeNumber
$mgr = $u.mgr
$fsal = $u.'fsalary-Hourly'
$comp = $u.Company
$ofc = $u.Office
Write-Host "$sam : $empnum : $mgr :$fsal : $comp : $ofc" -ForegroundColor Yellow
$GroupArray = @()
# # Check if the user fits in any of the 11 scenarios
if($comp -eq "US")
# scenario 7
write-host "7. Add to US Employees"
$GroupArray += "US Employees"
if($mgr -eq "Y")
Write-Host "1. ADD to US MAnagers"
$group = "US Managers"
$GroupArray += $group
if(($fsal -eq "Hourly") -and ($ofc -ne "Canton"))
Write-Host "3. Add to US Hourly (excluding Canton)"
$group = "US Hourly (excluding Canton)"
$GroupArray += $group
if(($fsal -eq "Hourly") -and ($ofc -eq "Canton"))
write-host "4. Add to US Canton Hourly"
$group = "US Canton Hourly"
$GroupArray += $group
if(($fsal -eq "Salaried") -and ($ofc -eq "Corporate" -or $ofc -eq "Landis Lakes 1" -or $ofc -eq "Landis Lakes 2"))
Write-Host "5. Add to US Salaried Corporate"
$group = "US Salaried Corporate"
$GroupArray += $group
if(($fsal -eq "Salaried") -and ($ofc -ne "Corporate" -and $ofc -ne "Landis Lakes 1" -and $ofc -ne "Landis Lakes 2"))
Write-Host "6. Add to US Salaried Plant"
$group = "US Salaried Plant"
$GroupArray +=$group
elseif($comp -eq "canada")
# scenario 9
write-host "9. Canada Employees"
$GroupArray += "Canada Employees"
if($mgr -eq "Y")
Write-Host "2. Add to Canada Managers"
$group = "Canada Managers"
$GroupArray += $group
if($fsal -eq "Hourly")
Write-Host "10. Add to Canada Hourly"
$group = "Canada Hourly"
$GroupArray += $group
if($fsal -eq "Salaried")
Write-Host "11. Add to Canada Salaried Plant"
$group = "Canada Salaried Plant"
$GroupArray += $group
elseif($ofc -eq "Corporate" -or $ofc -eq "Landis Lakes 1" -or $ofc -eq "Landis Lakes 2")
Write-Host "8. Add to Corporate Employees"
$GroupArray += "Corporate Employees"
write-host "Final Group List" -ForegroundColor Green
$grplen = $GroupArray.Length
#$GroupArray
$grplen
for($i= 0; $i -lt $grplen; $i++)
$grpname = $GroupArray[$i]
write-host "$sam will be added to Group : $grpname" -ForegroundColor Magenta
# # Check if the user is already present in the Group
$mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAccountName -eq $sam}
if($mbr_exist -eq $null)
# #Add user to US Managers group
Add-ADGroupMember -Identity $grpname -Members $sam
Write-Host "1. User $sam is added to $grpname group" -ForegroundColor Green
# # documenting the user list that are added to this group
$grpmbr = New-Object PSObject
$grpmbr | Add-Member -MemberType NoteProperty -Name "EmployeeNumber" -Value $empnum
$grpmbr | Add-Member -MemberType NoteProperty -Name "SamAccountName" -Value $sam
$grpmbr | Add-Member -MemberType NoteProperty -Name "Name" -Value $u.Name
$grpmbr | Add-Member -MemberType NoteProperty -Name "DistinguishedName" -Value $u.DistinguishedName
$grpmbr | Add-Member -MemberType NoteProperty -Name "mgr" -Value $mgr
$grpmbr | Add-Member -MemberType NoteProperty -Name "Company" -Value $comp
$grpmbr | Add-Member -MemberType NoteProperty -Name "Salary/Hourly" -Value $fsal
$grpmbr | Add-Member -MemberType NoteProperty -Name "Office" -Value $ofc
$grpmbr | Add-Member -MemberType NoteProperty -Name "ADGroup" -Value $grpname
$grpmbr | Export-Csv "$updatedGroup\ADUsers_To_Group($grpname)_$sysdate.csv" -Append -NoTypeInformation
else
Write-Host "Member $sam already exist in $grpname group" -ForegroundColor Red
$logdate = get-date
$logdate.ToString() + "`tCompleted script to Update Update AD Groups..." | Out-File -FilePath $LogFilePath -Append
$status = 'true'
return $status
catch
$err_lineno = $error[0].InvocationInfo.ScriptLineNumber
$err_line = $error[0].InvocationInfo.Line
$ExceptionMessage = $_.Exception.Message
#$ExceptionMessage
$error_info = $error[0].ToString() + $error[0].InvocationInfo.PositionMessage
Write-Host "$error_info " -ForegroundColor Red
$FailedItem = $_.Exception.ItemName
if($ExceptionMessage)
$logdate.ToString() + "`t $error_info " | out-file "$foldername\ErrorLog_Update_AD_Groups$sysdate.log" -append
"Line Number: $err_lineno . `nError at Line: $err_line" | out-file "$foldername\ErrorLog_Update_AD_Groups$sysdate.log" -append
#Invoke-Item "C:\ErrorLog.log"
$status = 'false'
return $statusHi mdkelly, Sorry for such a late reply (due to credential issues).
I am using Windows task scheduler to schedule the task. I am given the administrator access to the server (Windows Server 2012). So I think I set to run the script under system account.
My apologies for asking this, am I missing something while scheduling the script through task scheduler? how to check if the scheduled task is running under who's credentials? How to pass my (admin) credentials, so that the script execution won't face
a problem? Any suggestion on the above questions will be helpful. (I tried to search on net for the questions but didn't get any conclusive answers)
Thanks in advance. -
Execute Process Task Error - Powershell script
I've got a powershell script that is executed through a Execute Process Task that is giving me an error when executed through the Execute Package Utility on a 64bit server.
"c:\windows\system32\windowspowershell\v1.0\powershell.exe" ""& 'C:\CubeArchive\Linked DB to XMLA.ps1'"" at "", The process exit code was "1" while the expected was "0".
Here's the rub:
It runs fine from Visual Studio on that server.
On my local maching (32bit), it runs fine from both Visual Studio and Execute package Utility.
Does anyone have any idea why this is happening?
Thanks,
JasonOk - found the problem.
This is the first time that I'm using powershell.
I had set the ExecutionPolicy on that machine to unrestricted from the powershell console beforehand.
But unknown to me, this setting was only applicable to the 32 bit environment.
I set the 64 bit environment to unrestricted and it worked. (I added another Execution Process Task to the package to set this before hand - I only did this once and now can remove it.)
I thought that the setting for powershell would be server wide, I didn't know that there was a distinction of the 32 bit and 64 bit environments.
Thanks,
Jason -
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 -
An unknown error occurred while executing the PowerShell script:
Hello all,
Not the most descriptive title, granted. I'm hoping this may prompt the next version toprovide additional valuable content.
Kindly requesting any help on this problem. I'm running VMM 2012 R2 version 3.2.7668
When I try to look at properties of an existing Private Cloud, I get this error, only if I "look" at certain attributes. If I stay away from the specific attributes, everything is hunky dory. For reasons unknown, after I get this error, I have
to exit and go back into VMM in order to get anything else to run.
The text in the error dialogue box is not entirely applicable because I was connected to the VMM server and will connect again, when I exit/relaunch.
An unknown error occurred while executing the PowerShell script:
The connection to the VMM management server scvmm2.mmmmmm.com was lost.
Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager service is started
on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
Try the operation again. If the issue persists, contact Microsoft Help and Support.
ID: 27235
This is what I get in Events
Warning 4/9/2015 3:27:04 PM PowerShell (Microsoft-Windows-PowerShell) 4100 Executing Pipeline
Log Name: Microsoft-Windows-PowerShell/Operational
Source: Microsoft-Windows-PowerShell
Date: 4/9/2015 3:27:04 PM
Event ID: 4100
Task Category: Executing Pipeline
Level: Warning
Keywords: None
User: mmmmmm\paufra
Computer: tools-francis.mmmmmm.com
Description:
Error Message = The connection to the VMM management server scvmm2.mmmmmm.com was lost. (Error ID: 1610)
Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager service is started
on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
Fully Qualified Error ID = 1610,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.GetSCReplicationGroupCmdlet
Recommended Action = Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager
service is started on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
Context:
Severity = Warning
Host Name = Default Host
Host Version = 4.0
Host ID = 94963cd4-5979-4786-9da2-c8814de8c7c3
Host Application = C:\Program Files\Microsoft System Center 2012 R2\Virtual Machine Manager\Bin\VmmAdminUI.exe
Engine Version = 4.0
Runspace ID = 359d7a46-3752-4929-8c09-0de4152d10e4
Pipeline ID = 16
Command Name = Get-SCReplicationGroup
Command Type = Cmdlet
Script Name =
Command Path =
Sequence Number = 91
User = mmmmmm\paufra
Shell ID = Microsoft.PowerShell
User Data:
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Microsoft-Windows-PowerShell" Guid="{A0C1853B-5C40-4B15-8766-3CF1C58F985A}" />
<EventID>4100</EventID>
<Version>1</Version>
<Level>3</Level>
<Task>106</Task>
<Opcode>19</Opcode>
<Keywords>0x0</Keywords>
<TimeCreated SystemTime="2015-04-09T22:27:04.993655700Z" />
<EventRecordID>285</EventRecordID>
<Correlation ActivityID="{48059811-1A63-41E1-9057-7498D0E4FC20}" />
<Execution ProcessID="2344" ThreadID="4076" />
<Channel>Microsoft-Windows-PowerShell/Operational</Channel>
<Computer>tools-francis.mmmmmm.com</Computer>
<Security UserID="S-1-5-21-4008432563-1984933819-4238309236-2721" />
</System>
<EventData>
<Data Name="ContextInfo"> Severity = Warning
Host Name = Default Host
Host Version = 4.0
Host ID = 94963cd4-5979-4786-9da2-c8814de8c7c3
Host Application = C:\Program Files\Microsoft System Center 2012 R2\Virtual Machine Manager\Bin\VmmAdminUI.exe
Engine Version = 4.0
Runspace ID = 359d7a46-3752-4929-8c09-0de4152d10e4
Pipeline ID = 16
Command Name = Get-SCReplicationGroup
Command Type = Cmdlet
Script Name =
Command Path =
Sequence Number = 91
User = mmmmmm\paufra
Shell ID = Microsoft.PowerShell
</Data>
<Data Name="UserData">
</Data>
<Data Name="Payload">Error Message = The connection to the VMM management server scvmm2.mmmmmm.com was lost. (Error ID: 1610)
Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager service is started
on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
Fully Qualified Error ID = 1610,Microsoft.SystemCenter.VirtualMachineManager.Cmdlets.GetSCReplicationGroupCmdlet
Recommended Action = Ensure that scvmm2.mmmmmm.com is online and that you can access the server remotely from your computer. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. Or, you can ensure that the Virtual Machine Manager
service is started on scvmm2.mmmmmm.com. Then connect to scvmm2.mmmmmm.com and try the command again using the new connection. If the command fails again because of a connection failure, restart the Virtual Manager service and then try the operation again.
</Data>
</EventData>
</Event>Hi Sir,
First , please try to run the VMM configuration analyzer on that computer :
http://www.microsoft.com/en-us/download/details.aspx?id=41555
In addition , please try to use "VMMTrace" mentioned in following article to collect trace log and find some useful information :
http://blogs.technet.com/b/jonjor/archive/2011/01/07/vmmtrace-simplified-scvmm-tracing.aspx
Best Regards,
Elton Ji
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected] . -
Please Vote if you find this to be helpful!
App-V PowerShell: Script to Query XenApp Servers for App-V Publishing Errors and Output an Excel Document with the Results
Just posted this to the wiki:
http://social.technet.microsoft.com/wiki/contents/articles/25323.app-v-powershell-script-to-query-xenapp-servers-for-app-v-publishing-errors-and-output-an-excel-document-with-the-results.aspxHi 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. -
Error with SMLets in an Orchestrator called PowerShell Scripts
Hi!
This is likely so simple I am overlooking the problem but...
I have a "Run .Net Script" activity in an Orchestrator 2012 SP1 Runbook. It calls SMLets. The issue is it runs in the PowerShell ISE on the Runbook server without issue. It runs in the Runbook Tester just fine. But if I
call the runbook with the PowerShell script, it errors out on the first call the a SMLets provide cmdlet.
A Few Detail:
We loaded the latest SMLets from CodePlex. We can use the cmdlets in both the 32-bit and 64-bit environments.
The very first line of the PowerShell script is: Import-Module SMLets
The first SM cmdlet is: $class = Get-SCSMClass System.WorkItem.Activity.ReviewActivity$
The Runbook Containing the PowerShell Script:
And lastly, the Event of the error thrown:
In trying to make this work we have tried to run the script remotely on the SCSM server (New-PSSession and Invoke-Command). Failures due to rights on the SCSM server.
My opinion is the issue is a rights issue but we cannot find the difference between any of the accounts testing/debugging and the Orchestrator Runbook Service account. I can run the PowerShell and the Runbook Tester when logged on as the
Orchestrator Runbook Service account. It works until I have to call the runbook with the PowerShell Activity. It just like my Account. We've even set the account on the security tab of the Invoke Runbook Activity.
Is there something I've overlooked? Something in the install of the SMLets, maybe? A clue? Help?
If nothing else, thank you for letting me voice my issue onto the 'Net. Maybe someone else has been down this road and can tell me where the off-ramp is. ;-)
Ray Watters,
Chicago, ILHi,
also make sure that your PS scriptruns with Windows PowerShell (x86) (32bit)
http://www.sc-orchestrator.eu/index.php/scoblog/64-using-64bit-powershell-cmdlets-in-the-run-net-script-activity-from-orchestrator
or with PowerShell V2
http://www.sc-orchestrator.eu/index.php/scoblog/102-running-powershell-30-with-the-run-net-script-activity
Regards,
Stefan
www.sc-orchestrator.eu ,
Blog sc-orchestrator.eu -
I failed to use any Powershell script in Global Conditions with error 87D00327. The script is signed and tested without problem. Setting execution policy doesn't change the result at all.
Error message as below:
In-line script returned error output: File C:\Windows\CCM\SystemTemp\e7001c04-3966-46a7-9622-26c36d9c45de.ps1 cannot
be loaded. The file C:\Windows\CCM\SystemTemp\e7001c04-3966-46a7-9622-26c36d9c4
5de.ps1 is not digitally signed. The script will not execute on the system. Ple
ase see "get-help about_signing" for more details..
At line:1 char:2
+ & <<<< 'C:\Windows\CCM\SystemTemp\e7001c04-3966-46a7-9622-26c36d9c45de.ps1'
+ CategoryInfo : NotSpecified: (:) [], PSSecurityException
+ FullyQualifiedErrorId : RuntimeException
ScriptProvider 6/23/2014 1:45:06 PM 2516 (0x09D4)
ScriptProvider::CreateInstanceEnumAsync - Script Execution Returned :1, Error Message:File C:\Windows\CCM\SystemTemp\e7001c04-3966-46a7-9622-26c36d9c45de.ps1 cannot
be loaded. The file C:\Windows\CCM\SystemTemp\e7001c04-3966-46a7-9622-26c36d9c4
5de.ps1 is not digitally signed. The script will not execute on the system. Ple
ase see "get-help about_signing" for more details..
At line:1 char:2
+ & <<<< 'C:\Windows\CCM\SystemTemp\e7001c04-3966-46a7-9622-26c36d9c45de.ps1'
+ CategoryInfo : NotSpecified: (:) [], PSSecurityException
+ FullyQualifiedErrorId : RuntimeException
ScriptProvider 6/23/2014 1:45:06 PM 2516 (0x09D4)
Failed in discovering instance.
Script is not signed (Error: 87D00327; Source: CCM) ScriptProvider 6/23/2014 1:45:06 PM 2516 (0x09D4)
Failed to do HandleExecQueryAsync().
Script is not signed (Error: 87D00327; Source: CCM) ScriptProvider 6/23/2014 1:45:06 PM 2516 (0x09D4)
Failed to process CScriptProvider::GExecQueryAsync.
Script is not signed (Error: 87D00327; Source: CCM) ScriptProvider 6/23/2014 1:45:06 PM 2516 (0x09D4)
I can't figure out a way to capture the temp script file mentioned in the error message so I can't verify the script locally.
Any help will be appreciated.
Sean
Regards, SeanHi, Sean.
There was a product issue with signed PowerShell detection method scripts that has been fixed in R2 CU2. I just noticed it's not mentioned in the KB article for CU2. I'm not sure what happened here but I'll have somebody look into this.
Anyway, there's a couple of caveats to consider regarding this fix in your scenario. Firstly if you're creating a PowerShell script detection method you must not copy/paste the script text -- you need to "Open" it. Secondly, if you have any previously created
PowerShell script detection methods with signed scripts, you will need to re-add the detection script (again using "Open"). Finally, you must use an administrator console that's been updated to CU2 and a client that's been updated to CU2 for this fix to be
effective.
I hope this helps resolve the issue for you.
Check out my Configuration Manager blog at http://aka.ms/ameltzer -
Message
Executed as user: CORPTST\XXXXX. A job step received an error at line 1 in a PowerShell script. The corresponding line is 'set-executionpolicy RemoteSigned -scope process -Force'. Correct the script and reschedule the job. The error information returned
by PowerShell is: 'Security error. '. Process Exit Code -1. The step failed.
I receive this error during the sql server job 'syspolicy_purge_history' execution when sql server got upgraded form SQL Server 2008 to 2014.Hi Vishnu,
According to the error message, it also occurs in SQL Server 2012. Here is a feedback about the error in the link below.
https://connect.microsoft.com/SQLServer/feedback/details/754063/sql-server-2012-syspolicy-purge-history-job-step-3-fails-with-security-error
To resolve this issue, please change the value of the following registry key from ‘RemoteSigned’ to ‘Unrestricted’. For more details, you can review this similar
blog.
HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps120\ExecutionPolicy
Thanks,
Lydia Zhang -
Hello,
I'm currently starting to develop management packs for SCOM, i understand the basics and can build a simple management pack using powershell.
During testing i'm running into a problem, when running the powershell script directly it gives an error. If i use the discovery script in a management pack everything works ok.
The error is:
Exception calling "CreateDiscoveryData" with "3" argument(s): "Ongeldige klassereeks (Exception from HRESULT: 0x800401F3 (CO_E_CLASSSTRING))"
Part of it is in dutch but it means something like invalid class.
I tried to run the script on one of our management servers but it also gives this error.
It's very frustrating because i want to test the discovery scripts first before building the complete management pack.
Thanks for your help!Something along these lines should work for you:
.\DiscoveryTest.ps1 -sourceID ([guid]::NewGuid().ToString("B")) -managedEntityID ([guid]::NewGuid().ToString("B"))
Of course your parameter names and numbers may differ.
It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link. -
Trouble adding leading zeros to numbers in PowerShell script
I am new to PowerShell scripting (so have mercy on me please!), and I'm trying to write a script that takes simplified, menu-based user input to create a folder on the network named based on a month number and the year. The month must be expressed as a two-digit
number, but I'm trying to make it simple enough that the user only needs to input a one-digit number (for the first nine months of the year) and have the script add the leading zero (for example, if a user inputs the number "2" for February, the
script will output "02").
Here is a portion of my script:
# Get current year
$year = Get-Date -Format yyyy
# Provide menu of months for user to choose from
Write-Host "Choose the name of the month for the folder you want to create."
Write-Host "1. January"
Write-Host "2. February"
Write-Host "3. March"
Write-Host "4. April"
Write-Host "5. May"
Write-Host "6. June"
Write-Host "7. July"
Write-Host "8. August"
Write-Host "9. September"
Write-Host "10. October"
Write-Host "11. November"
Write-Host "12. December"
Write-Host " "
Do {
$mNum = Read-Host "Select the number of the month (1 - 12): "
# Convert the menu item to the month name
switch ($mNum)
1 {$month = "January"}
2 {$month = "February"}
3 {$month = "March"}
4 {$month = "April"}
5 {$month = "May"}
6 {$month = "June"}
7 {$month = "July"}
8 {$month = "August"}
9 {$month = "September"}
10 {$month = "October"}
11 {$month = "November"}
12 {$month = "December"}
default {"Invalid entry. Please select a number from 1 - 12 (without the trailing period)."}
# Validate user input. Current code is cumbersome; try to find more elegant method.
While ($mNum -ne 1 -and $mNum -ne 2 -and $mNum -ne 3 -and $mNum -ne 4 -and $mNum -ne 5 -and `
$mNum -ne 6 -and $mNum -ne 7 -and $mNum -ne 8 -and $mNum -ne 9 -and $mNum -ne 10 -and `
$mNum -ne 11 -and $mNum -ne 12)
# Add leading zeros to month number
$fNum = "{0:D2}" -f $mNum
Write-Host $fNum
When I run it, I don't get the leading zero. However, when I create a very basic script, it seems to work:
$mNum = 3
$fNum = "{0:D2}" -f $mNum
Write-Host $fNum
Can anyone offer any suggestions as to what I might be doing wrong?
Also, if anyone has a suggestion on how to better validate the user input (making sure they enter a number between 1 and 12), I would appreciate that as well..NET formatting is a complicated subject
http://msdn.microsoft.com/en-us/library/26etazsy(v=vs.110).aspx#FormatStrings
I'm not sure how all that documentation applies when you attempt to format a value that is already a string.
In general, formatting is described as "Formatting is the process of converting an instance of a class,
structure, or enumeration value to its string representation". If it is already a string I'm not sure what to expect.
For example,
<# C: #> '3',3,'03',03,'003',003 | % { "{0:D2}" -f $_ }
3
03
03
03
003
03
<# C: #> -
SCCM 2012 PowerShell script gets progressively slower with each machine added to a collection
Firstly, I hope this question firs in this forum.
I have a PowerShell script that I created the imports a CSV file and adds the machine names to a collection as a direct membership. There are 5000 machines total in the list. When the script first starts, the average per machine is just a few tenths of a
second. Once it reaches about 10% the average is up to almost 4 seconds and that time is getting larger with each machine. I tried using the CMDLets for SCCM but they were even slower than the WMI seemed to be.
What is the reason for this increase?
Is there anything I can do to not have this happen?
My script:
$ErrorActionPreference= 'continue'
$FilesInFolder = Get-ChildItem $PSScriptRoot
$CSVFiles = $FilesInFolder | where {$_.extension -eq ".csv"}
$SiteCode = "US1"
Function AddToCollection-WithWMI
ForEach ($File in $CSVFiles)
$CollectionStart = Get-Date
$CollectionName = $File.Name.TrimEnd(".csv")
$PClist = Import-CSV $File.FullName
Write-Host "Populating Collection: " $CollectionName
$i = 1
$PCRollingTime = New-Object System.TimeSpan
ForEach($PC in $PClist)
$PCStart = Get-Date
$ResourceName = $PC.SerialNumber
Write-Host $i "of" $PClist.Count
$ResourceQuery = Get-WmiObject -Namespace "Root\SMS\Site_US1" -Class SMS_R_SYSTEM -Filter "Name = '$ResourceName'"
$CollectionQuery = Get-WmiObject -Namespace "Root\SMS\Site_US1" -Class SMS_Collection -Filter "Name = '$CollectionName' and CollectionType='2'"
$CollectionQuery.Get()
IF($ResourceQuery -ne $null)
#Create new direct membership rule
$NewRule = ([WMIClass]"\\Localhost\root\SMS\Site_US1:SMS_CollectionRuleDirect").CreateInstance()
$NewRule.ResourceClassName = "SMS_R_System"
$NewRule.ResourceID = $ResourceQuery.ResourceID
$NewRule.Rulename = $ResourceQuery.Name
#Commit changes
$CollectionQuery.CollectionRules += $NewRule.psobject.baseobject
$CollectionQuery.Put() | Out-Null
$NewRule = $null
ELSE
Write-Host "No Device ID found for: " $PC.SerialNumber
$CollectionQuery = $null
$ResourceQuery = $null
$PCFinish = Get-Date
$TimeSpan = New-TimeSpan -Start $PCStart -End $PCFinish
$PCRollingTime = $TimeSpan + $PCRollingTime
If(($i % 25) -eq 0)
$CurrentAvgPerPC = $PCRollingTime.TotalSeconds / $i
Write-Host "The current average is" $CurrentAvgPerPC "seconds."
$SecondsToETA = ($CurrentAvgPerPC * ($PClist.Count - $i))
$ETA = Get-Date
$ETA = $ETA.AddSeconds($SecondsToETA)
Write-Host "The Estimated time of complete is" $ETA
If(($i % 250) -eq 0)
$PCRollingTime
$i++
$CollectionQuery = Get-WmiObject -Namespace "Root\SMS\Site_US1" -Class SMS_Collection -Filter "Name = '$CollectionName' and CollectionType='2'"
$CollectionQuery.Get()
#Initiate the collection evaluator
$CollectionQuery.RequestRefresh()
$CollectionFinish = Get-Date
AddToCollection-WithWMII haven't checked the complete code, but it doesn't look very efficient. For example I would take the collection query out the loop for all the pcs, simply because it's always the same and would save you about 4999 queries.
My Blog: http://www.petervanderwoude.nl/
Follow me on twitter: pvanderwoude
^^ This
Additionally, you could likely replace most of the WMI calls you do with the built in SCCM PowerShell cmdlets. The two lines below will check to see if a Device Object for a specific PC exists and if it does, adds it to your collection
$PCID = Get-CMDevice -Name $PC.SerialNumber
if ($PCID -ne $null) {
Add-CMDeviceCollectionDirectMembershipRule -CollectionName $CollectionName -ResourceId $PCID
If you want to check to see if the collection exists before trying to add devices to it, you can use the Get-CMDeviceCollection cmdlet.
Get-CMDeviceCollection -Name $CollectionName
Moo.
Maybe you are looking for
-
Delivery Output determiantion using Delivery type & Item category
Dear all, I am facing a problem while triggering output using Delivery type/Item Category access in access sequence xyz. I have maintained the condition record for this access and did all the necessary customization settings. When i maintain the cond
-
More FMS & Flash CS3 not loading FLV
I consider myself an intelligent fellow, but getting Flash CS3 to stream vis FMS is killing me. I've read the posts here where people are describing similar situations. I've read several websites that show kinda similar methods of getting this done,
-
Next week I plan to upgrade my Vista W500 to Windows 7 (with a clean install from the upgrade discs I got via the upgrade program). Are there any possible issues I should be aware of? In particular I've heard about issues with the switchable graphi
-
My account can not update. Please Help
and please check this problem too.https://discussions.apple.com/thread/4143915
-
Hi, where can I idnetify the size of the iPhoto Library?