Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

How to add or append the notes in telephone tab

$
0
0

Hi

I have below script to update the notes info in Telephone tab of AD User properties. But through this, old info replaced and only show the new one.

Import-Csv .\script\userlist.csv | foreach {Set-ADUser $_.SamAccountName -Replace @{info="Disable user."}}

Now I want to append or add additional notes instead of replacing the old notes.

Please help me or guide me


quota management

$
0
0

Hi all,

I'm trying to script storage quotas on a windows 2012 server. I am running the console as admin but I get the following error though;

PS C:\Windows\system32> New-FsrmQuota -CimSession Server10 -Path "C:\temp" -Description "limit usage to 20 MB based on template." -Template "20 MB Limit"
New-FsrmQuota : 0x80045301, The requested object was not found.
At line:1 char:1
+ New-FsrmQuota -CimSession Server10 -Path "C:\temp" -Description "limit usage to ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (MSFT_FSRMQuota:Root/Microsoft/.../MSFT_FSRMQuota) [New-FsrmQuota], CimExc
   eption
    + FullyQualifiedErrorId : HRESULT 0x80045301,New-FsrmQuota
    + PSComputerName        : Server10

The template does exist. Any ideas what this could be?

Thanks in advance.

Get-ADForest -Identity $domain

$
0
0

Hi all,

Get-ADForest -Identity $domain

When I am running this command, its saying that "could not find a forest identified  by"..

please help me...

my mail id smooth.munna@gmail.com

regards,

Bhalotia


PK Bhalotia

Excel Charts in Powershell

$
0
0

I've been using the following article "Integrating Microsoft Excel with Powershell Part 2" to creat excel charts using Powershell.  I've tweaked it a bit to use pie charts instead of bar graphs and have included 2 charts on one worksheet.  Everything works fine except that the title for the second chart errors out with the follow message:

Property 'Text' cannot be found on this object; make sure it exists and is settable.

Any ideas on how to resolve this and add a title to the second chart?

The line of code causing the error is:

$chart2.ChartTitle.Text = "Helpdesk Tickets Period 2"

Here is the full script below:

[datetime]$P1 = "1/1/2013"
[datetime]$P2 = "1/29/2013"
[datetime]$P3 = "2/26/2013"

$File = import-csv "E:\Powershell\Documents\LooTok\BCMPortal\Period Reports\Excel\helpdeskstats.csv"
$Total_Stats = $File | ?{[datetime]$_.Created -ge [datetime]::Parse($P1) -and [datetime]$_.Created -lt [datetime]::Parse($P3)}
$P2Stats = $File | ?{[datetime]$_.Created -ge [datetime]::Parse($P2) -and [datetime]$_.Created -le [datetime]::Parse($P3)}
$Grouped_Total = $Total_Stats | Group RelatedTo
$GroupedP2 = $P2Stats | Group RelatedTo

Write-Verbose "Creating Excel application"
$xl=New-Object -ComObject "Excel.Application"

#we'll need some constansts
$xlConditionValues=[Microsoft.Office.Interop.Excel.XLConditionValueTypes]
$xlTheme=[Microsoft.Office.Interop.Excel.XLThemeColor]
$xlChart=[Microsoft.Office.Interop.Excel.XLChartType]
$xlIconSet=[Microsoft.Office.Interop.Excel.XLIconSet]
$xlDirection=[Microsoft.Office.Interop.Excel.XLDirection]

Write-Verbose "Adding Worksheet"
$wb=$xl.Workbooks.Add()
$ws=$wb.ActiveSheet

$cells1=$ws.Cells
$cells2=$ws.Cells

$cells1.item(1,1)="Helpdesk Report All"
$cells2.item(1,6)="Helpdesk Report P2"

#define some variables to control navigation
$row1=3
$col1=1
$row2=3
$col2=6

#insert column headings
Write-Verbose "Adding drive headings"

"Related To","Count" | foreach {
    $cells1.item($row1,$col1)=$_
    $cells1.item($row1,$col1).font.bold=$True
    $col1++
}

"Related To","Count" | foreach {
    $cells2.item($row2,$col2)=$_
    $cells2.item($row2,$col2).font.bold=$True
    $col2++
}

foreach ($i in $Grouped_Total) {
    $row1++
    $col1=1
    $cells1.item($Row1,$col1)=$i.name
    $col1++
    $cells1.item($Row1,$col1)=$i.count
    $cells1.item($Row1,$col1).NumberFormat="0"

}

foreach ($i in $GroupedP2) {
    $row2++
    $col2=6
    $cells2.item($Row2,$col2)=$i.name
    $col2++
    $cells2.item($Row2,$col2)=$i.count
    $cells2.item($Row2,$col2).NumberFormat="0"

}

Write-Verbose "Adding some style"

#add some style
$range1=$ws.range("A1")
$range1.Style="Title"
$range2=$ws.Range("F1")
$range2.Style="Title"
#or set it like this
$ws.Range("A3:B3").Style = "Heading 2"
$ws.Range("F3:G3").Style = "Heading 2"

#adjust some column widths
Write-Verbose "Adjusting column widths"

#$ws.columns.item("C:C").columnwidth=15
#$ws.columns.item("D:F").columnwidth=10.5
$ws.columns.item("A:A").EntireColumn.AutoFit() | out-null
$ws.columns.item("F:F").EntireColumn.AutoFit() | out-null


#add some conditional formatting
Write-Verbose "Adding conditional formatting"

#insert a graph
Write-Verbose "Creating a graph"
$chart1=$ws.Shapes.AddChart().Chart
$chart1.chartType=$xlChart::xlPie
$Chart1.ApplyDataLabels(2)

$start1=$ws.range("A3")
#get the last cell
$Y1=$ws.Range($start1,$start1.End($xlDirection::xlDown))
$start1=$ws.range("B3")
#get the last cell
$X1=$ws.Range($start1,$start1.End($xlDirection::xlDown))

$chartdata1=$ws.Range("A$($Y1.item(1).Row):A$($Y1.item($Y1.count).Row),B$($X1.item(1).Row):B$($X1.item($X1.count).Row)")
$chart1.SetSourceData($chartdata1)

#add labels
$chart1.seriesCollection(1).Select() | Out-Null
$chart1.SeriesCollection(1).ApplyDataLabels() | out-Null
#modify the chart title
$chart1.ChartTitle.Text = "Helpdesk Tickets Period 1-2"
Write-Verbose "Repositioning graph"
$ws.shapes.item("Chart 1").top=1
$ws.shapes.item("Chart 1").left=1

#insert a graph
Write-Verbose "Creating a graph"
$chart2=$ws.Shapes.AddChart().Chart
$chart2.chartType=$xlChart::xlPie
$Chart2.ApplyDataLabels(2)

$start2=$ws.range("F3")
#get the last cell
$Y2=$ws.Range($start2,$start2.End($xlDirection::xlDown))
$start2=$ws.range("G3")
#get the last cell
$X2=$ws.Range($start2,$start2.End($xlDirection::xlDown))

$chartdata2=$ws.Range("F$($Y2.item(2).Row):F$($Y2.item($Y2.count).Row),G$($X2.item(2).Row):G$($X2.item($X2.count).Row)")
$chart2.SetSourceData($chartdata2)

#add labels
$chart2.seriesCollection(1).Select() | Out-Null
$chart2.SeriesCollection(1).ApplyDataLabels() | out-Null
#modify the chart title

$chart2.ChartTitle.Text = "Helpdesk Tickets Period 2"
Write-Verbose "Repositioning graph"
$ws.shapes.item("Chart 2").top=1
$ws.shapes.item("Chart 2").left=370

Write-Verbose "Renaming the worksheet" 
#rename the worksheet
$name="6.FC Activity"
$xl.worksheets.Item("Sheet1").name=$name

#make Excel visible
$xl.Visible=$True

#$filepath=Read-Host "Enter a path and filename to save the file"

if ($filepath) {
    Write-Verbose "Saving file to $filepath"
    $wb.SaveAs($filepath)
    $xl.displayAlerts=$False
    $wb.Close()
    $xl.Quit()
}

Thanks,

Joe


login to a list of computers simultaneously?

$
0
0

I do not know where to start on this but i need to know how to script logging into many computers simultaneously so as a logon script will kick off.

It would be better if we had a time out/logoff command of say an hour.

I know to script the lists and for each and all that but have no clue on doing the logon /multi threaded part.

could anyone help with this?

-append option to Tee-Object new in v3

$
0
0

I am glad they added a -append parameter to Tee-Object, but I just found an irregularity to using it.
If an existing file is in ASCII format (not Unicode) and Tee-Object appends to it, then the file becomes a mixture of ASCII and Unicode.

New-Object -COM Excel.Application | certain fields are not showing, inconsistent behavior

$
0
0

Hello All,

Im having some trouble when using New-Object -COM Excel.Application on foreign machines primarily. It seems like my first four categories that are listed at the top of the spreadsheet have gone missing. But the data in which corresponds to the category below it stays intact. All other regions show the categories fine. Has anyone ever seen that before? How can i assure that all my categories stay?

 $excel = New-Object -COM Excel.Application

 $excel.visible = $false

$excel.displayalerts = $false

$excel = $excel.workbooks.add()

#categories Note: I have about 20 categories, they all look like this. The first 4 were missing on just a Tokyo machine. I need somehow a way to enforce that the fields be present after attempt has been made. or run a condition on it. This is inconsistent for just this region.

$Sheet = $excel.worksheets.item(1)

$Sheet.Cells.Item(1,1) = "Category1"

$Sheet.Cells.Item(1,2) = "Category2"

$Sheet.Cells.Item(1,3) = "Category3"

$Sheet.Cells.Item(1,4) = "Category4"

$Workbook = $sheet.UsedRange

$Workbook.Interior.ColorIndex = 49

$Workbook.Font.ColorIndex = 2

$Workbook.Font.Bold = $true

$intRow = 2

# Variable values go in the respectable second row, have about 20 of those as well

$Sheet.Cells.Item($intRow,1) = $variable

$Sheet.Cells.Item($intRow,2) = $variable2

$Sheet.Cells.Item($introw,3) = $variable3

$Sheet.Cells.Item($introw,4) = $variable4

# Now the variable $data is a mass collections of Get-ChildItems which you will see shortly

Foreach ($line in $data)

{

$sheet.Cells.Item($intRow,5) = $line.Name

$sheet.Cells.Item($intRow,6) = $line.Name2

$sheet.Cells.Item($intRow,7) = $line.Name3

$intRow = $intRow + 1

}

$WorkBook.EntureColumn.AutoFit()

$excel.SaveAs($folder + "\" + "name.csv") 

$excel.Close()

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Sheet) | Out-Null

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null

[System.GC]::Collect()

[System.GC]::WaitForPendingFinalizers()

You can foreach a null?!?!?!

$
0
0
> foreach( $d in $null ) { "This will never be printed!" }
This will never be printed!


Huh?  Why would I ever want this to be acceptable behavior?



Get Out of a Function

$
0
0

Hi,

I have a simple PowerShell script which contains just two functions, I would like to run through each of these functions, but in each one there is a condition where the function should terminate. so my script goes like this:

myfunc1
myfunc2
function myfunc1
{

If(some stuff)
{
things
}
ElseIf(some stuff)
{
things
}
Else
{
things
    terminate/exit this function now
}


if(some stuff)
{
things
terminate/exit this function now
}
else
{
things
}


}

function myfunc2
{

If(some stuff)
{
things
}
ElseIf(some stuff)
{
things
}
Else
{
things
    terminate/exit this function now
}


if(some stuff)
{
things
terminate/exit this function now
}
else
{
things
}

is this the correct way to call my functions consecutively, and how would i exit the first function so my script can continue with the second one?

thanks

Steve

Rename Domain Computer Account GPO

$
0
0

I would like to create a script that will run at either startup or shutdown(whichever I can get working) in a GPO that will rename a domain computer based off of what is put into the description field of the machine account in AD.  I wrote something in VBS that grabs the description field of the computer that the script is running on and checks its desc field in AD for the identifier RENAME:.  If RENAME: is present in the desc field it takes what is after RENAME: (i.e. RENAME:IT-COMP-01) and stores that into a variable that will be used as the computer's new name.  This part is working fine but the part I am stuck at is the actual renaming part.  I wanted to use NETDOM but NETDOM isn't installed by default in Windows 7 and I feel a little uncomfortable including the domain and local admin credentials in the script.  I am not very familiar with powershell so wanted to get some input on wether or not I can follow the same procedure as above in powershell to rename the computer based on the AD computer account desc field while keeping admin credentials secure?

Appreciate all help. 

Parsing non deliminated text file

$
0
0

I have a text file that contains information that needs to be imported into SQL table. However, the file isn't delimited in anyway. It contains a header row and the data inline below that. Here is an example:

                           Outstanding      1-15 Days    16-30 Days      31-45 Days     46-65 Days
Student Name      Amount            Past Due      Past Due           Past Due          Past Due       
------------------     ---------------  ------------    ------------       ------------     ------------
DEYOU, KATINA P                 -5.00            0.00              0.00                 0.00               0.00

The only regualarity to the data is that the column length is denotes by the length of the hyphens and these can vary depending on the longest student name in the column. I what I need is a PowerShell script that will evaluate the length of each column by counting the number of hyphens (characters) for each column and save that information to variables. I then would need to read each line in the file and insert a comma at the end of each data element of in the columns. Like this:

                           Outstanding      1-15 Days    16-30 Days      31-45 Days     46-65 Days
Student Name      Amount            Past Due      Past Due           Past Due          Past Due       
-------------------     ---------------  ------------    ------------       ------------     -------------
DEYOU, KATINA P,                 -5.00,          0.00,             0.00,                0.00,               0.00,

Can anyone help me to solve this problem?

Thanks


Support Analyst / Support Engineer

Windows batch and PowerShell passing variables issue.

$
0
0
If I use variable instead of number as build version value, it is not working.

Any suggestion?


Batch Script:
------------

set BuildVersion = 2.1

cd C:\Scripts

powershell.exe -file Deploy-Axsis.ps1 %BuildVersion% (Not working)
powershell.exe -file Deploy-Axsis.ps1 2.1 ( Working) 



PS Script:
----------

$buildVersionMain=$args[0]



Error:
-------
The variable '$buildVersionMain' cannot be retrieved because it has not been set.

Replace wsh 5.8 with 5.7 on windows 7 ?

$
0
0

Hi,

Does anyone know if something will break if I install wsh 5.7 on my windows 5.8 machine? (Assuming I can get around the WFP).

I need SendKeys to function, and I do not need the OS protecting me from this function.

Thanks, Ed

Using module dll in c# 'natively'

$
0
0

Hi,

I'm trying to figure out if what i'm thinking of doing is normal or crazy.

I'm working with a module (from netapp) and I want to build a tool which invokes the cmdlets without having c# invoke powershell which invokes the cmdlets but rather by calling the methods in the dll directly.

I've added the dll to my project as a reference and I can create objects from the types, but it seems like i'm missing some plumping or gloo as i'm having trouble sorting out what to call to actually get the methods to run (in this case i need to connect to a filer, retain the connection object and then run some methods to list, make or remove things on the filer).

So is the best/only way to use a module from c# to create a RunspaceFactory and just run the powershell commands within that space ?

I was hoping there is a way to do it more 'natively' if that makes sense.

Error using Invoke-SqlCmd

$
0
0

Receiving error using this script: The TSQL script runs fine but errors in powershell.

Exception             : System.NullReferenceException: Object reference not set to an instance of an object.

                           at BatchParser.ThunkVariableResolver.ResolveVariable(ThunkVariableResolver* , UInt16* varName, UInt16** varValue)

                           at BatchParser.Variables.ResolveVariable(Variables* , basic_string<unsigned short\,std::char_traits<unsigned short>\,std::allocator<unsigned short> >* name, basic_string<unsigned short\,std::char_traits<unsign

                        ed short>\,std::allocator<unsigned short> >* val)

                           at BatchParser.Batch.listall(Batch* , basic_string<unsigned short\,std::char_traits<unsigned short>\,std::allocator<unsigned short> >* str, IVariables* variables, Int32 mark)

                           at BatchParser.Batch.popall(Batch* , basic_string<unsigned short\,std::char_traits<unsigned short>\,std::allocator<unsigned short> >* str, IVariables* variables, Int32 mark)

                           at BatchParser.ExecutionContext.ProcessBatch(ExecutionContext* , Boolean hasNum)

                           at BatchParser.BatchParserYacc.reduce(BatchParserYacc* , UInt32 ulProd, UInt32 ulSize)

                           at SSYacc.doReduce(SSYacc* )

                           at SSYacc.parse(SSYacc* )

                           at BatchParser.BatchParserInternal.Parse(BatchParserInternal* , ParserState* , Boolean flushBatchBuffer)

                           at ManagedBatchParser.Parser.Parse()

                           at Microsoft.SqlServer.Management.PowerShell.ExecutionProcessor.ExecuteTSql(String sqlCommand)

                           at Microsoft.SqlServer.Management.PowerShell.GetScriptCommand.ProcessRecord()

TargetObject          :

CategoryInfo          : InvalidResult: (:PSObject) [Invoke-Sqlcmd], NullReferenceException

FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

ErrorDetails          :

InvocationInfo        : System.Management.Automation.InvocationInfo

PipelineIterationInfo : {0, 1}

PSMessageDetails      :

cls
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$server = Get-Content c:\SQL_SERVERS\2008_UPDATE_JOB_STEPS.txt
$updatejob = "C:\SCRIPTS\Maintenance\CURRENT\UPDATE_JOB_STEP.sql"

foreach ($server in $server)
{
try
{
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') $server
Invoke-Sqlcmd -InputFile $updatejob -ServerInstance $server 
}
catch
{
$Error[0]|format-list -force
Write-Host "Error on $server"
}
}



copy-item with write-progress

$
0
0

Is there anyway to add a progress bar to my copy block?

$SQLVERSION = Read-Host 'What Version of SQL do you want installed?  Enterprise or Standard?:'
$mediaENT = "SOURCE"
$mediaSTD = "SOURCE"
$LocalENT = "Destination"
$LocalStd = "Destination"

Write-Host "Looking for SQL install media on server..."

		if ($SQLVERSION -eq "ENTERPRISE")
		{
				if(-not (Test-Path "E:\SQLInstallMedia\SQL2008R2_Enterprise_Edition_SP2"))
			{
		Write-Host "Media not found, copying it to $LocalENT"
		Copy-Item $mediaENT $LocalENT -Recurse
		if((Test-Path "E:\SQLInstallMedia\SQL2008R2_Enterprise_Edition_SP2"))
			{
				Write-Host "Media has been copied to $LocalENT"
			}
			}
		}
	if ($SQLVERSION -eq "STANDARD")
	{
			if(-not (Test-Path "E:\SQLInstallMedia\SQL2008R2_STANDARD_Edition_SP2"))
		{
			Write-Host "Media not found, copying it to $LocalSTD"
			Copy-Item $mediaSTD $LocalSTD -Recurse
	if((Test-Path "E:\SQLInstallMedia\SQL2008R2_STANDARD_Edition_SP2"))
		{
			Write-Host "Media has been copied to $LocalSTD"
		}
		}
	}

Something akin to %PATH% for Windows PowerShell

$
0
0
I want to execute/call/reference PowerShell scripts in the Windows PowerShell console WITHOUT having to reference the whole path. In the old command prompt, I can call programs and batch scripts that exist in any path in %PATH% by only typing the file's name. How do I do this with PowerShell? It needs to be permanent.

HTML/CSS formatting fails while sending mail from PowerShell

$
0
0

Hi All,

I'm sending the content of an HTML file through an email to other people.
Below is the code I'm using.

$body = (get-content c:\Temp.html) | out-string
Send-MailMessage -To abc@gmail.com -Subject "Report" –From xyz@adp.com -SmtpServer smtpserver -Body $Body -BodyAsHtml

HTML page when opened locally looks good.
When the mail is received by me, the format looks good.
BUT when I send email to other people, they are not getting the format in correct way.

I've applied CSS while generating HTML, which fails while sending mail to other people.
Any guess what might be the reason?

Thanks,
Pavan

Passing SharePoint List values to DataSet to build email in Powershell

$
0
0

Hi,

I'm new to powershell and SharePoint... I'm creating script to generate an email body and send it to the assignee.  Currently we don't have VS2010 so the only way i can do this that i know is using powershell.

No| Status | assignee
1| Open | Dona
2| Open | Dona
3  | Open  | Rey
4  | Open  | Charice

Can you please tell me how to pass the sharePoint list items in a dataset so i can generate this kind of email below. For example ill be sending the email to Dona.

Sample Email to Dona.

Item No: 1  / Status: Open /Assignee: Dona

Item No:2 /Status: Open / Assignee: Dona

Thanks in Advance.





AutoPopulate the fields with userdetails based on the UniqueID (user picked from people picker) field entered in the SharePoint 2010 list

$
0
0

Hi,

I have a requirement in the SharePoint 2010 List  containing the fields - Unique ID (People picker), FirstName(SingleLineofText), LastName(SingleLineofText) and so on.

Whenever the user fill in the "UniqueID" column, the fields (Firstname and Lastname) should be automatically populated based on the UniqueID.

do we have the powershell script for the same .

Thanks,
Chakradhar


Viewing all 2562 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>