VMware Cloud Community
Rashida11
Contributor
Contributor
Jump to solution

Script as a Scheduled Task

Hi i have installed powershell and VI toolkit on the vCenter server ( win2003). when ever I try and set up a schulled i get wrrors

syntax in the run property:

  1. powershell -command "& 'path.ps1'

However if i run the scripot from VI tooolkit it runs fine...

Does anyone know what run syntax and program ( VI toolkit or pwershell ) i should be using ....

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

That's because the VITK prompt runs a few other files while starting up.

It loads a console file (.psc1), which makes sure the VITK snapin is loaded, and it executes the Initialize-VIToolkitEnvironment.ps1 script, which defines some aliases.

In the scheduled task you should enter something like this

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -PSConsoleFile "C:\Program Files\VMware\Infrastructure\VIToolkitForWindows\vim.psc1" c:\temp\test.ps1

And if you need the aliases the script should contain this on the first line

. "C:\Program Files\VMware\Infrastructure\VIToolkitForWindows\Scripts\Initialize-VIToolkitEnvironment.ps1"


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

0 Kudos
20 Replies
LucD
Leadership
Leadership
Jump to solution

That's because the VITK prompt runs a few other files while starting up.

It loads a console file (.psc1), which makes sure the VITK snapin is loaded, and it executes the Initialize-VIToolkitEnvironment.ps1 script, which defines some aliases.

In the scheduled task you should enter something like this

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -PSConsoleFile "C:\Program Files\VMware\Infrastructure\VIToolkitForWindows\vim.psc1" c:\temp\test.ps1

And if you need the aliases the script should contain this on the first line

. "C:\Program Files\VMware\Infrastructure\VIToolkitForWindows\Scripts\Initialize-VIToolkitEnvironment.ps1"


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
bradley4681
Expert
Expert
Jump to solution

If i put the following in the scheduled task run line the task seems to run without error.

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -PSConsoleFile "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" D:\PowerScripts\new.ps1

My script is collecting info about virtual machines and then ftping the csv file to a server. if i open a command window first and run the above command everything seems to run fine, any ideas?

Cheers,

Bradley Sessions

If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".

Cheers! If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Is the scheduled task running with your account or with another account ?

You could add a Start-Transcript (first line) and Stop-Transcript (last line) to your script.

That will record every message in a file. Could perhaps help in pin-pointing the problem.

____________

Blog: LucD notes

Twitter: lucd22


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
bradley4681
Expert
Expert
Jump to solution

its running as a local user account. I did the transaction log and it turned me on to this:

ConvertTo-SecureString : Key not valid for use in specified state.

At D:\PowerScripts\new.ps1:5 char:72

+ $passwd = get-content D:\PowerScripts\pass.txt | convertto-securestring <<<<

+ CategoryInfo : InvalidArgument: (Smiley Happy , C

ryptographicException

+ FullyQualifiedErrorId : ImportSecureString_InvalidArgument_Cryptographic

Error,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

in the top part of my script I have:

$passwd = get-content D:\PowerScripts\pass.txt | convertto-securestring

This seems to work fine except when i run it as this admin user thats local, any ideas?

Cheers,

Bradley Sessions

If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".

Cheers! If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".
0 Kudos
LucD
Leadership
Leadership
Jump to solution

You have to generate the file pass.txt with the same account you are later using for the scheduled task.

To verify, let the scheduled task run once under your account.

____________

Blog: LucD notes

Twitter: lucd22


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
bradley4681
Expert
Expert
Jump to solution

That was my problem, i recreated the password file as the user running the scheduled task and now it works fine. One other issue i found was the ftp function in my script stopped working because that user account had a proxy setup in its internet settings, once i removed that it worked again.

I also attached it so others can see it, with comments in the code.

#vCenters Servers to Connect 
$viservers = "vServer1","vServer2","vServer3","vServer4"
#Username to connect to vCenters
$userName = "username"
#Powershell encrypted password file, encrypt with user account running the script
$passwd = get-content D:\Scripts\pass.txt | convertto-securestring
#Gets username and Password and passes it to function below
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName,$passwd

#Connects to each vCenter and collects the information below for a report
foreach ($singleViserver in $viservers)
{

	Connect-VIServer $singleViserver -Credential $cred

	$HostReport = @()

	Get-VM |Get-View | %{
		$Report = "" | select Name, VMuuid, ESXhost, VMos, IP, FQDN, Status, Customer
		$Report.Name = $_.Name
		$Report.VMuuid =$_.Summary.Config.uuid
		$Report.ESXhost = (Get-View $_.Runtime.Host).Name
		$Report.VMos =$_.Summary.Config.GuestFullName
		$Report.IP =$_.Guest.IPAddress
		$Report.FQDN =$_.Guest.HostName
		$Report.Status = $_.Runtime.PowerState
		$Report.Customer = (Get-VIObjectByVIView $_).CustomFields
		$HostReport += $Report

	}
	#Disconnects after each vCenter
	Disconnect-VIServer -Confirm:$False
}
#Creates a CSV file with the output of the above, create 1 file for all vCenters
$HostReport | Export-Csv ".\Full-HostReport.csv" -Delimiter "|" ñNoTypeInformation

#Takes output CSV and uploads to FTP Server
{
# create the FtpWebRequest and configure it
$ftp = [http://System.Net.FtpWebRequest|http://System.Net.FtpWebRequest]::Create("ftp://yourserver.com/Full-HostReport.csv")
$ftp = [http://System.Net.FtpWebRequest|http://System.Net.FtpWebRequest]$ftp
$ftp.Method = [http://System.Net.WebRequestMethods+Ftp|http://System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential("Username","Username@server.com")
$ftp.UseBinary = $true
$ftp.UsePassive = $true

# read in the file to upload as a byte array
$content = gc -en byte D:\Scripts\Full-HostReport.csv
$ftp.ContentLength = $content.Length

# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)

# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()
}

Cheers,

Bradley Sessions

If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".

Cheers! If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".
0 Kudos
bradley4681
Expert
Expert
Jump to solution

So my script seems to have a problem, its only writing the results of the last vcenter to the csv file. any ideas?

Cheers,

Bradley Sessions

If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".

Cheers! If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Your initialisation of the variable $HostReport should be done outside the loop through the VI Servers.

Something like this.

...
$HostReport = @()

#Connects to each vCenter and collects the information below for a report
foreach ($singleViserver in $viservers)
{

	Connect-VIServer $singleViserver -Credential $cred


	Get-VM |Get-View | %{
...

____________

Blog: LucD notes

Twitter: lucd22


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
bradley4681
Expert
Expert
Jump to solution

ok so now its writing everything but I have a bunch of duplicate entries. Some of the guests are listed 2 or 3 times and some are only listed once. WTF...

Cheers,

Bradley Sessions

If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".

Cheers! If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Perhaps add the vServername in the report (use the $defaultVIServer variable).

That will tell you if the duplicates are coming from the same vCenter or different vCenters.

Btw you can make the duplicates go away by using Sort-Object -Property Name -Unique, but that is just hiding the problem Smiley Wink

____________

Blog: LucD notes

Twitter: lucd22


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
bradley4681
Expert
Expert
Jump to solution

very strange...

MYSERVER201BIZ is actually on the VC-Zurich virtual center but it shows up 3 times in the report, some servers show up 3 or 4 times, and some only show up once. Any ideas?

MYSERVER201BIZ    564df5fb-f8d0-5a7c-ba34-8ad9564d6415    MYSERVER201BIZ.mydomain.net   Microsoft Windows Server 2003, Enterprise Edition (32-bit)    136.157.43.111    poweredOn    SBT    VC-Zurich.mydomain.net

MYSERVER201BIZ    564df5fb-f8d0-5a7c-ba34-8ad9564d6415    MYSERVER201BIZ.mydomain.net   Microsoft Windows Server 2003, Enterprise Edition (32-bit)    136.157.43.111    poweredOn    SBT    VC-Field.mydomain.net

MYSERVER201BIZ    564df5fb-f8d0-5a7c-ba34-8ad9564d6415    MYSERVER201BIZ.mydomain.net   Microsoft Windows Server 2003, Enterprise Edition (32-bit)    136.157.43.111    poweredOn    SBT    VC-Ohio.mydomain.net

Cheers,

Bradley Sessions

If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".

Cheers! If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".
0 Kudos
LucD
Leadership
Leadership
Jump to solution

It could be that the same guest is registered in multiple vCenters.

Do you see the guest in the vSphere client under the same vCenters ?

And if yes, are these guests all pointing to the same datastore location ? Provided you have shared storage for these vCenters.

____________

Blog: LucD notes

Twitter: lucd22


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
bradley4681
Expert
Expert
Jump to solution

they are only registered in 1 vCenter, the example above is only in the VC-Zurich vCenter. The vCenters are not configured for linked mode. There is no shared storage between the vCenters. The are 800miles apart.

I think its something to do with the script or something but i just don't know. would there be a way to write the data for each vCenter after it completes instead of writing it all at once when the script finishes. sorta write and append as it goes a long instead of holding everything in a buffer till the end, or do you have another idea?

Cheers,

Bradley Sessions

If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".

Cheers! If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".
0 Kudos
LucD
Leadership
Leadership
Jump to solution

You only have to change the script slightly

...
$HostReport = @()

#Connects to each vCenter and collects the information below for a report
foreach ($singleViserver in $viservers)
{

	Connect-VIServer $singleViserver -Credential $cred
         "vCenter" +  $singleViserver
         $VCreport = @()
	Get-VM |Get-View | %{
		$Report = "" | select Name, VMuuid, ESXhost, VMos, IP, FQDN, Status, Customer
		$Report.Name = $_.Name
		$Report.VMuuid =$_.Summary.Config.uuid
		$Report.ESXhost = (Get-View $_.Runtime.Host).Name
		$Report.VMos =$_.Summary.Config.GuestFullName
		$Report.IP =$_.Guest.IPAddress
		$Report.FQDN =$_.Guest.HostName
		$Report.Status = $_.Runtime.PowerState
		$Report.Customer = (Get-VIObjectByVIView $_).CustomFields
		$HostReport += $Report
		$VCreport += $Report
	}
	#Disconnects after each vCenter
	Disconnect-VIServer -Confirm:$False
          $VCreport
}
...

You will now get a list of the guests on screen for each vCenter.

____________

Blog: LucD notes

Twitter: lucd22


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
bradley4681
Expert
Expert
Jump to solution

NO MORE DUPLICATES!!!! It seems to be working like it should now. Collecting guest info from all the listed vCenteres. Can you explain what that bit of code you added does, the bit at the top and the two parts near the botom?

Cheers,

Bradley Sessions

If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".

Cheers! If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".
0 Kudos
LucD
Leadership
Leadership
Jump to solution

The line at the top defines a new array to collect the data per loop through all the vCenters.

This new array is empty at the start of each loop.

At the end of each loop (through a specific vCenter) the script displays the content of that array.

These lines were there for debugging purposes, so you could see for which vCenter the duplicate entries were there.

____________

Blog: LucD notes

Twitter: lucd22


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
tekhie
Contributor
Contributor
Jump to solution

***************************************************************

Votre message n'a pas pu etre delivre a Chris Sales <chris.sales@socgen.com>

***************************************************************

Your message could not be delivered to Chris Sales <chris.sales@socgen.com>

0 Kudos
bradley4681
Expert
Expert
Jump to solution

So am I correct in my comments defined below?

Connect-VIServer $singleViserver -Credential $cred

         #Creates New Array*******************
         "vCenter" +  $singleViserver
         $VCreport = @()
         #Creates New Array*******************

	Get-VM |Get-View | %{
		$Report = "" | select Name, VMuuid, ESXhost, VMos, IP, FQDN, Status, Customer
		$Report.Name = $_.Name
		$Report.VMuuid =$_.Summary.Config.uuid
		$Report.ESXhost = (Get-View $_.Runtime.Host).Name
		$Report.VMos =$_.Summary.Config.GuestFullName
		$Report.IP =$_.Guest.IPAddress
		$Report.FQDN =$_.Guest.HostName
		$Report.Status = $_.Runtime.PowerState
		$Report.Customer = (Get-VIObjectByVIView $_).CustomFields
		$HostReport += $Report

                #Displays the report for debugging**********
		$VCreport += $Report 
                #Displays the report for debugging**********
	}
	#Disconnects after each vCenter
	Disconnect-VIServer -Confirm:$False

          #Empties the Array*************
          $VCreport
          #Empties the Array*************

Cheers,

Bradley Sessions

If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".

Cheers! If you found this or other information useful, please consider awarding points for "Correct" or "Helpful".
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Not completely, this owuld be more correct.

Connect-VIServer $singleViserver -Credential $cred

         #Display vCenter name*******************
         "vCenter" +  $singleViserver
         #Display vCenter name*******************

         #Creates New Array*******************
         $VCreport = @()
         #Creates New Array*******************

	Get-VM |Get-View | %{
		$Report = "" | select Name, VMuuid, ESXhost, VMos, IP, FQDN, Status, Customer
		$Report.Name = $_.Name
		$Report.VMuuid =$_.Summary.Config.uuid
		$Report.ESXhost = (Get-View $_.Runtime.Host).Name
		$Report.VMos =$_.Summary.Config.GuestFullName
		$Report.IP =$_.Guest.IPAddress
		$Report.FQDN =$_.Guest.HostName
		$Report.Status = $_.Runtime.PowerState
		$Report.Customer = (Get-VIObjectByVIView $_).CustomFields
		$HostReport += $Report

                #Add the VM entry to the array**********
		$VCreport += $Report 
                #Add the VM entry to the array**********
	}
	#Disconnects after each vCenter
	Disconnect-VIServer -Confirm:$False

          #Display the Array on screen*************
          $VCreport
          #Display the Array on screen*************

____________

Blog: LucD notes

Twitter: lucd22


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos