Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Wicaeed
Feb 8, 2005
VBScript related question (Don't shoot me!)

I have the following subroutine in a script that uses wbadmin to back up a folder locally, rename it, then transfer the renamed backup folder to a network drive:

code:
Sub get2K3DBackupStatus
	If objFSO.FolderExists (BackupFolder2K3D) Then
		Set BackupFolder2K3DTmp = objFSO.GetFolder(BackupFolder2K3D)
		BackupFolder2K3DInfo = "Confluece D drive backed up on " & BackupFolder2K3DTmp.DateLastModified & "." & " Total Size: " & BackupFolder2K3DTmp.Size /1024\1024 & "MB"
		objFSO.MoveFolder BackupFolder2K3D, "D:\ConfluenceD_" & CurrentDate
		objFSO.CreateFolder "S:\Backup\Confluence_Backup\ConfluenceD_" & CurrentDate
		objFSO.CopyFolder "D:\ConfluenceD_" & CurrentDate , "S:\Backup\Confluence_Backup\ConfluenceD_" & CurrentDate
	Else
		BackupFolder2K3DInfo = "Confluence D drive backup does not exist"
	End If
End Sub

Lately the backup has been running, but the file has not been being transferred to the network share. I can run the script myself and it works fine, but the scheduled task hangs and keeps running over night.

What would be the simplest way to write a text file with whatever error my script is running into at this point?

Adbot
ADBOT LOVES YOU

Wicaeed
Feb 8, 2005
What is the correct way to use a variable that is a command line program in a script?

I'm kind of new so I'll try to make it clearer:

I am trying to run a mysql dump as part of a powershell script. I've defined the following variables:

code:
$mysqldump = "c:\Program Files\MySQL\MySQL Server 5.1\bin\mysqldump.exe"
$sqlServer = 'confluence'
$sqlUser = 'confluence'
$sqlPassword = 'redacted'
$sqlBackupPath = "D:\Scripts\Confluence\Backups\Confluence_MySQL.bkp"
When I go into powershell to test this script, I run it like such:

code:
invoke-expression $mysqldump -u $sqlUser -p$sqlPassword $sqlServer | Out-File $sqlBackupPath 
I get an error message
code:
Invoke-Expression : A positional parameter cannot be found that accepts argument '-u confluence'.
At line:1 char:18
+ invoke-expression <<<<  $mysqldump "-u confluence"
    + CategoryInfo          : InvalidArgument: (:) [Invoke-Expression], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeExpressionCommand 
I assume I'm not correctly passing the arguments for the command line program, but I've tried googling and I can't find out out to do this.

Any tips? Also is this going to behave differently in my script than if I'm running it right from the PowerShell console?

Wicaeed
Feb 8, 2005
Aha, that works beautifully. I also decided that adding the C:\Program Files\MySQL\MySQL Server 5.1\bin\ to the script environmental path would be easier to deal with as well:

code:
# MySQL Server Backup Settings
# 
#Define Path for mysqldump.exe
$env:Path = $env:Path + ";C:\Program Files\MySQL\MySQL Server 5.1\bin"
$mysqldb = 'confluence'
$mysqlUser = 'confluence'
$mysqlPassword = 'redacted'
$mysqlBackupPath = "D:\Scripts\Confluence\Backups\Confluence_MySQL.bkp"
$mysqlBackup = "mysqldump.exe -u $mysqlUser -p$mysqlPassword -B $mysqldb"
And it is run with:
code:
 Invoke-Expression -Command $mysqlBackup | Out-File $mysqlBackupPath -Encoding UTF8
Works beautifully :)

Wicaeed
Feb 8, 2005
More loving noobie questions:

I am rewriting a vbscript script that we currently use to work around the horrible Windows Server 2008/R2 backup feature.

Right now part of the vbscript looks as such:

code:
 
Sub get2K3DBackupStatus
	If objFSO.FolderExists(BackupFolder2K3D) Then
		Set BackupFolder2K3DTmp = objFSO.GetFolder(BackupFolder2K3D)
		BackupFolder2K3DInfo = "Drive backed up on " & BackupFolder2K3DTmp.DateLastModified & "." & " Total Size: " & BackupFolder2K3DTmp.Size /1024\1024 & "MB"
		objFSO.MoveFolder BackupFolder2K3D, "D:\DriveD_" & CurrentDate
		objFSO.CreateFolder "S:\Backup\BackupD_" & CurrentDate
		objFSO.CopyFolder "D:\DriveD_" & CurrentDate , "S:\DriveD" & CurrentDate
	Else
		BackupFolder2K3DInfo = "Drive backup does not exist"
	End If
End Sub
I am trying to rewrite that into a powershell function, so far I have the following. I've already defined a few variables that this function relies on, and I can use the test-path cmdlet to make sure that the results they are returning are true, however the boolean operator in this function always thinks that the path I'm looking for doesn't exist, weather or not I'm using a variable.

code:
Function get2k3DBackupStatus
{
If ((Test-Path "C:\dell") -ne $false)
{$BackupFolder2K3DInfo = "Drive backed up on $CurrentDate"}
Else
{$BackupFolder2K3DInfo = "Drive backup does not exists"}
}	
Write-Host $BackupFolder2K3DInfo
Always returns "Drive backup does not exists". Is there some secret I'm missing to using variables and boolean operators in functions?

Wicaeed
Feb 8, 2005
Okay, thanks for that clarification. The reason the vbscript is run like it is, is because that the results are later send via email, and from what you said regarding functions, you can't actually store the results as a variable that exists outside the function?

I was under the impression that Functions functioned (:v:) somewhat like subroutes in vbscript. Is that not the case?

If I DID want to store the results to call back on, but keep it inside the function, is that even possible?

Wicaeed
Feb 8, 2005
Sweet. HOWEVER, I have to be setting my function incorrectly, or something. When I call my function it returns a blank result, but if I comment out the function part of it so I'm left with:

code:
#Powershell function to check backup status Path D:\WindowsImageBackup on D: drive
#Function get2k3DBackupStatus
	#{
	If ((Test-Path "C:\dell") -ne $false)
		{$global:BackupFolder2K3Dinfo = "Drive backed up on $CurrentDate"}
	Else
		{$global:BackupFolder2K3Dinfo = "Drive backup does not exist"}
	#}
Write-Host $BackupFolder2K3DInfo
Which returns: Confluence D drive backed up on 12/21/2011 7:54:00 AM

Any ideas?

Wicaeed
Feb 8, 2005
:doh:

Yeah, now it works. Thanks a bunch :)

Wicaeed
Feb 8, 2005
So what's the proper way to go about getting folder paths with spaces to parse properly in powershell?

Example:

code:
$strCBackup = "wbadmin start backup -quiet -backuptarget:d: -include:""c:\Program Files\Atlassian"",c:\confluencedata\"
Returns the following:
code:
PS S:\Confluence_Backup> $strCBackup
wbadmin start backup -quiet -backuptarget:d: -include:"c:\Program Files\Atlassian",c:\confluencedata\
However when I try to use it in a function or use it with Invoke-Expression , wbadmin doesn't recognize the C:\Program Data\ as a valid path.

code:
ERROR - Command syntax incorrect. Error: Files\Atlassian c:\confluencedata". See the command 
syntax below
What's the correct way to get it to recognize that the folder exists with its spaces?

Wicaeed
Feb 8, 2005
:argh:

code:
$strCBackup = "wbadmin start backup -quiet -backuptarget:d: ""-include:C:\confluencedata,C:\Program Files\Atlassian"""
I wish I really understood what these quotes and poo poo to, cause that works fine

Wicaeed
Feb 8, 2005
Okay, so I have this stupidly large function I am using to verify my backup results.

A previous function moves/renames the Windowsimagebackup folder to a network share, then this function verifies that that path exists, and if so removes the backup folder from the local drive.

Heres the code:

code:
Function getfinalbackupstatus
{
		If ((Test-Path  "S:\Confluence_Backup\ConfluenceC_$sDate") -ne $false){
			{
				$BackupFolder2K3CTmp =  "C:\ConfluenceC_$sDate"
				$BackupFolder2K3CFinal = "S:\Confluence_Backup\ConfluenceC_$sDate"
				$GetSize2K3CTmp = "Get-ChildItem $Backupfolder2K3CTmp -recurse | Measure-Object -Property length -Sum"
				$GetSize2K3CFinal = "Get-ChildItem $BackupFolder2K3CFinal -recurse | Measure-Object -Property length -Sum"
			}
				If (($getsize2k3ctmp.sum -eq $GetSize2K3CFinal.sum) -ne $false){
					Remove-Item $BackupFolder2K3CTmp -recurse
					$global:Backup2k3Status = "Confluence Data Backup Successful"
				}
				Else{
					$global:Backup2k3Status = "Confuence Data Backup Failed"
				}
		}		
		If ((Test-Path "S:\Confluence_Backup\ConfluenceD_$sDate") -ne $false){	
			{
				$BackupFolder2K3DTmp = "D:\$ConfluenceD_$sDate"
				$BackupFolder2k3DFinal = "S:\Confluence_Backup\ConfluenceD_$sDate"
				$GetSize2K3DTmp = "Get-ChildItem $Backupfolder2K3DTmp -recurse | Measure-Object -Property length -Sum"
				$GetSize2K3DFinal = "Get-ChildItem $Backupfolder2k3Dfinal -recurse | Measure-Object -Property length -Sum"
			}
				If (($GetSize2K3DTmp.sum -eq $GetSize2K3DFinal.sum) -eq $false){
						If ($Backup2k3Status -eq "Confluence Data Backup Successful"){
							Remove-Item $BackupFolder2K3DTmp -Recurse
							$global:Backup2k3Status = "Confluence Data Backup Successful"
						}
						Else{
							$global:Backup2k3Status = "Confuence Data Backup Failed"
						}
					}
				Else{
					$global:Backup2K3Status = "Confluence Data Backup FAILED"
				}
		}
		Else{
			$global:Backup2K3Status = "Confluence Data Backup FAILED"
		}
}
I realize that it's hideously long, however to me it's fairly straight forward. BUT, when it comes time to run, the second if statement contained in the codeblock always fails.

What's the right way to debug a function, if you have to load the function into memory before you can even run it later with the function name?

Wicaeed
Feb 8, 2005
How would one discover if a file was created on the first weekday in a month?

I can find a bunch of examples from years ago that use vbscript, but none do 100% what I need

Wicaeed
Feb 8, 2005

Mario posted:

What if the 1st is on a Monday? This would match Tuesday and Wednesday as well.

How about (again, not tested):
code:
$info = Get-Item butts.txt
if(($info.CreationTime.DayOfWeek -ne "Saturday" -and $info.CreationTime.DayOfWeek -ne "Sunday" -and $info.CreationTime.Day -eq 1)
-or
($info.CreationTime.DayOfWeek -eq "Monday" -and $info.CreationTime.Day -lt 4))
{
    # it was the first weekday of the month
}

Awesome, I was able to make that work with 99% accuracy. Actually all of that Saturday/Sunday stuff I don't even need since the folders are only created on Weekdays.

If I wanted to return a list of folders, but exclude any created in the previous month, how could I do that? I know I can filter my results with something like

code:
Where-Object {$_.CreationTime -lt (get-date).adddays(-31)}
But that would exclude the previous 31 days of results, which if it's halfway through the month, will start pruning records I don't want pruned.

Any ideas?

Wicaeed fucked around with this message at 18:12 on Jan 5, 2012

Wicaeed
Feb 8, 2005
Hmm good point.

Is there any way to format the value of the file/folder CreationTime to match a get-date format of Myyyy (January 2012 would be 12012, November 2011 would be 112011, and so on).

I honestly don't really need the date, I'm just filtering out files the current and prior month, the date filtering comes later:

http://pastebin.com/WqUp6gxF

Edit:

Actually I came across a realization. I don't need to filter on the first weekday of the month, but the first Friday of the month, and this makes it much easier simple because The year doesn't matter, because at the point where this script has been running that long I will already have the only backup I want for that time period (the first Friday in the month), and the first Friday will always fall within the first 7 days of the month.

code:

Function Findfilescreatedonfirstweekdayofmonth{
   $global:MonthOldbackupfiles = gci "E:\Backups" | Where-Object {$_.CreationTime.Month -ne ([System.DateTime])::Now.Addmonths(-1).Month -and $_.CreationTime.Month -ne ([System.DateTime])::Now.Month}
    Foreach($item in $Montholdbackupfiles){
    if(($item.CreationTime.DayOfWeek -eq "Friday"  -and $item.CreationTime.Day -le 7))
    {
        write-host "$item was the first Friday of the month"
    }
    Else
    {
        write-host "$item was not created during the specified time period"
    }
    }
}
Bazing!

Tell me I'm not wrong in my assumption :ohdear:

Wicaeed fucked around with this message at 18:21 on Jan 6, 2012

Wicaeed
Feb 8, 2005
Quick question, made harder because I don't know what the actual name is for it:

I'm using the following script to get the Month number (1 = January, etc) so that I can include/exclude files from backup based on if they are the current are prior months, without having to worry about the date.

code:
$global:MonthOldbackupfiles = gci "E:\Backup" | Where-Object {$_.CreationTime.Month -ne ([System.DateTime])::Now.Addmonths(-1).Month -and $_.CreationTime.Month -ne ([System.DateTime])::Now.Month}
It works fairly well.

I'm trying to do something similar for whatever a files creation time was for the week , however I can't find a way get the date/time in that format with the pipeline object $_.CreationTime.

I've been reading this Powershell Blog on how the author goes about adding a membertype to the get-date method: http://blogs.technet.com/b/heyscriptingguy/archive/2011/07/08/use-powershell-to-get-the-number-of-the-week-of-the-year.aspx

I was wondering if you could do something similar

code:
get-date -Uformat %V
Which returns just a '2' right now, but as I said I can't find a way to use it with $_.CreationTime.WeekofYear or something similar, because it simply doesn't exist.

Can you manually add a method to do that type of math?

I hope I'm making sense, I'm still pretty new to this and a lot of the terminology isn't there :ohdear:

Wicaeed
Feb 8, 2005
What is the most simple way to save the result of each iteration of a Foreach loop?

For example I have the following loop:
code:
 Foreach ($Item in $FridayBackups[0..5]){
        $script:robosrc = "E:\Data\Prodbackups\Confluence_Backup\$item"
        $script:robodest = "G:\Confluence_Backup\$item"
        $script:robocopy = "robocopy.exe $robosrc $robodest /S /DCopy:T"
        If ((test-path G:\Confluence_Backup\$item) -eq $false){
            Invoke-Expression -Command $robocopy
            Write-Host "$item was transfered to DFS Folder"
            }
        Else{
            Write-Host "$item already exists"
            }
        }
I want to take the result of what was copied to the folder and save each iteration to send in an email.

Right now the write-host lines are there simply so I can see what is going on at the command line.

I don't quite understand hash tables or arrays yet, which is what I think I need to properly get this working.

Any tips?

Wicaeed
Feb 8, 2005

Walter_Sobchak posted:

So, two stupid things I'd like to learn how to do. Honestly, at this point, I'd like to know if they're even possible. I can (hopefully) figure out the actual mechanics. I've only ever had experience scripting with batch files, so for now, I'd like to just use those. If not, hey, always good to learn something new, right?

1) Is there a way to specify a file by the Date Modified column? I basically want to have a script that auto-deletes the oldest file in a certain folder when I run it.

2) How do you check to see if a program is already running? I'm trying to write a script that checks to see if a couple different programs are running, and if not, to start them.

Like I said, I've only ever used simple batch files. If it can't be done with those, oh well. Guess I'd better learn some languages, hahaha. Thanks in advance, goons.

Yay I finally get to help someone! I'm doing pretty much this exact thing with a backup script
You can sort objects oldest to newest by creationtime with the following:
code:
gci | Sort-Object -property Creationtime -Ascending
To check for running processes you can use the Get-WMI cmdlet, or simply get-process if you're running the script locally. From there it's just a simple task of filtering the results vs what you are looking for. As a fellow noob, this is exactly what the powershell pipeline is for. If you know what the process name is when the program is running, you could use something like:

code:
$MyProcess = Get-Process processname
if($MyProcess -eq $null)
{
Start-Process -Filepath <pathtoexe> -otherarguments
}
Else
{
Do something else
}
There's really a huge number of different ways you can accomplish that.

Wicaeed fucked around with this message at 16:05 on Feb 2, 2012

Wicaeed
Feb 8, 2005

adaz posted:

Ridiculously awesome stuff

Holy poo poo, so much useful information there :psypop:

Wait, I thought that variables not defined outside of a function can't exist outside it?

e.g. the difference between $global:variable and $variable, etc...

Wicaeed
Feb 8, 2005
Cool.

Another question:

In the email I am getting with the results, the formatting is crapping everything out on a single line, like so:
code:
20120106_ConfluenceC was removed from the DFS rotation 20120106_ConfluenceD was removed from the DFS rotation 20120127_ConfluenceD was transfered to DFS Folder 20120127_ConfluenceC was transfered to DFS Folder
I tried piping it to format-list but then I get a return like this:

code:
Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData
How can I get it to put one entry on each line?

Wicaeed
Feb 8, 2005
Mmmm, I don't think that's it. I have another script I use to send a separate email, however it uses two variables that only ever output a single line of text. I had to edit the body of the email to add some breaking

code:
Send-MailMessage -To $emailto -Subject "$Backup2k3Status - $sqlstatus" -Body $BackupFolder2k3cinfo`r`r`n$BackupFolder2k3Dinfo`r`r`n$sqlstatus -From $EmailFrom -SmtpServer $EmailServer

Wicaeed
Feb 8, 2005
What's the easiest way to break out of a scriptblock in Powershell? I have a script that will generate quite a few errors if a variable is not set, which can happen if it is a certain date.

Can I add a simple If/Else statement to say something like:

code:
If ($variable -eq $null){
Goto next function
Else{
do something here
}
Edit: Hurr, a simple 'break' will work there. Another question regarding variables.

I've got two variables, one is a folder path, the other is a filename variable. I would like to combine the two to test the existence of the destination file. Code snippet follows:

code:
Foreach ($script:item in $DFSFilesToCopy){
    $script:ParentFoldername = $item | split-path -parent | split-path -leaf
    $script:ParentFolderStructure = $item | split-path -parent
    $script:DestinationFolder = "G:\$ParentFolderName"
    $script:SourceFolder = $ParentFolderStructure
        If ((Test-Path $item) -eq $True) {
        $script:DFSresult += "$item was copied to the DFS folder"
        $script:robocopy = robocopy.exe $SourceFolder $DestinationFolder $item.name /S /DCopy:T
        $robocopy
        }
        Else {
        $script:DFSresult += "$item was not copied because it already exists"
        }
}
When I do something like '$item.name' I get exactly what I want. How can I combine that with $DestinationFolder to get

code:
G:\ParentFolderName\Filename

Wicaeed fucked around with this message at 17:26 on Feb 29, 2012

Wicaeed
Feb 8, 2005
So recently I've noticed some strange behavior in Powershell ISE and scheduled tasks.

I can load up/edit a script in ISE, and when it comes time to run it, I hit F5. This loads the script but nothing really happens. I have to manually type the function that is calling each scriptblock in to the powershell CLI to get it to run properly.

This is affecting scheduled tasks as well. I did install Powershell 3.0 beta on my workstation and have been using it to remote powershell tab to my servers, but I still have 2.0 installed on my servers, however it happens on the servers as well if I am using Powershell ISE in an RDP session.

Any ideas, as I'm completely befuddled by this behavior.

Wicaeed
Feb 8, 2005
Seriously, I've quite thoroughly enjoyed my time with Powershell thus far, I just wish I had more excuses to use it at work :(

Wicaeed
Feb 8, 2005
Before I spend too much time writing a new script, does anyone know of a pre-made Powershell script that I could use to pull a list of user-created scheduled tasks off of a server and tell me what credential and/or username it is set to run as?

Wicaeed
Feb 8, 2005
So I saw this posted on Reddit, give a really good overview of Powershell for those trying to learn it, and also gives a lot of good tips on script creation: https://www.youtube.com/watch?v=-Ya1dQ1Igkc

For example, I didn't even know of the show-command cmdlet.

Blew my fuckin' MIND, man.

Wicaeed
Feb 8, 2005
The remoting feature looked pretty awesome, but it strikes me that third-party applications that run on the server are going to be negatively impacted by removing the Windows Server gui. Our monitoring system (PRTG) relies on a GUI-based control panel that runs on the server. Is there a way (with ps remoting) to redirect GUI content to another computer?

Wicaeed
Feb 8, 2005
So, does anyone know if it's possible to import all of the PowerCLI modules directly into Powershell or Powershell ISE?

edit: nm, apparently

code:
 if ((Get-PSSnapin "VMware.VimAutomation.Core" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "VMware.VimAutomation.Core" } 
gets it done

Wicaeed fucked around with this message at 18:30 on Jun 21, 2012

Wicaeed
Feb 8, 2005
:facepalm:

So for the long time was trying to get a powershell script that (simply) let me know if the current day was the first weekday of the month. For mailing purposes I send an email based on whether or not that is true

code:
$currentday = get-date
$weekdays = "Monday","Tuesday","Wednesday","Thursday","Friday"
$months = 1..12
$firstofmonth = foreach ($month in $months) {1..7| %{get-date -month $month -day $_} | ?{$weekdays -contains $_.dayofweek}|select -first 1}

Function Firstday {
    If ($firstofmonth -contains $currentday)
        {write-host "First weekday of the month"}
    Else
        {Write-Host "Not the first weekday of the month"}
    }

Firstday
FINALLY I was able to do it. I love/hate Powershell

Wicaeed
Feb 8, 2005
So this is kind of a stupid question:

Company has a need to sign executable files with a cert and time stamp from verisign.

This is handled by a relatively simple command line command, but it requires the use of a Windows SKD CMD Shell.

Ideally, I would like to create a script that I can use to simply drag an executable to be signed over, and have poweshell work it's magic.

I'm having a devil of a time finding out how to really DO this, however.

Tips/Hints?

Wicaeed
Feb 8, 2005

Titan Coeus posted:

In that situation, you can make a batch script that accepts the drag and drop, and have that pass the command line argument to the power shell script.

See http://stackoverflow.com/questions/2819908/drag-and-drop-to-a-powershell-script

I actually read that exact post on Stack Overflow and tried it, but for some reason whenever I drag and drop a file the batch script seems to die as it is passing the entire file contents instead of just the path to the powershell script :confused:

Wicaeed
Feb 8, 2005
Quick question regarding this script (a friend wrote it and I tweaked it):

http://pastebin.com/RRxeK3CF

If I wanted to return only servers that match a certain part of the results on the 'logonserver' portion, or the 'NTP Source' result, how could I do that?

Wicaeed
Feb 8, 2005
Has anyone used Powershell & racadm to gather system inventory from a local system?

Wicaeed
Feb 8, 2005
Kind of a long shot, I recently found this script here Kind of a long shot, I recently found this script here that can be used to clean up folders on a server.

I'm going to use it, but I was wondering if there would be an easy way that I might be overlooking to include the name of the server on which it was run, either as the email subject or in the log file anywhere.

I'm kind of new with Powershell, but I figure I'd ask before I start trying to edit the script to do something like that.

Wicaeed
Feb 8, 2005
:woop:

Forgot that there was an optional -EmailSubject field that isn't required, but is automatically set to a string with a few variables. Just set $ComputerName = gc env:computername and called the variable in the default subject line.

Not really too pretty, but it works.

code:
if ($EmailTo -or $EmailFrom -or $EmailSmtpServer) {
    if (($EmailTo,$EmailFrom,$EmailSmtpServer) -contains '') {
        Write-Warning 'EmailTo EmailFrom and EmailSmtpServer parameters only work if all three parameters are used, no email sent...'
    } else {
        $EmailSplat = @{
            To = $EmailTo
            From = $EmailFrom
            SmtpServer = $EmailSmtpServer
            Attachments = $LogFile
        }
        if ($EmailSubject) {
            $EmailSplat.Subject = $EmailSubject
        } else {
            $ComputerName = gc env:computername
            $EmailSplat.Subject = "deleteold.ps1 started at: $StartTime FolderPath: $FolderPath on $ComputerName"
        }
    }
}

Wicaeed
Feb 8, 2005
PowerCLI Time:

Trying to count the number of vCPUs that have been configured in a VM resource pool in our vCenter server. Problem is that we have similarly named resource pools across multiple clusters. I wrote something that can get me 90% of what I'm looking for, what I really need is the total count across all resource pool instances:

code:
Foreach ($rp in Get-Resourcepool -Name "ResourcePool") { 
    $vCPU = Get-VM -Location $rp | Measure-Object -Property NumCPU -SUM | Select -ExpandProperty Sum
    $rp | Select Name,
    @{N='vCPU assigned to VMs';E={$vcpu}}
    }
My results look something like this:

code:
Name                                                                                                            vCPU assigned to VMs
----                                                                                                            --------------------
prod-ubu14                                                                                                                   196
prod-ubu14                                                                                                                   108
prod-ubu14                                                                                                                   168
I'm wracking my brain trying to come up with a way to count all those instances of a result returned in a foreach loop and tally it up at the end. The problem is expanded by the fact that the results have the same name.

edit: Derp, apparently you can do this in one line on PowerCLI and not even have to worry about duplicate named resource pools.

code:
Get-VM -Location "ResourcePoolName" | Measure-Object -Property NumCPU -Sum

Wicaeed fucked around with this message at 01:49 on Aug 11, 2015

Wicaeed
Feb 8, 2005
Is there a way to break up a single line powershell command across multiple lines, allowing for easier readability, but still being able to copy/paste it directly into a Powershell prompt?

I've got something like
code:
Register-ScheduledTask ^
    -TaskName "TestRail Background Task" ^
    -Trigger (-Once -At (Get-Date) -RepetitionInterval (New-Timespan -Minutes 1) -RepetitionDuration ([System.TimeSpan]::MaxValue)) ^
    -Action (New-ScheduledTaskAction -Execute "C:\Program Files (x86)\PHP\v5.6\php.exe" -Argument "E:\TestRail\task.php") ^
    -Settings (New-ScheduledTaskSettingsSet -AsJob -ExecutionTimeLimit 1h -MultipleInstances StopExisting) ^
    -RunLevel ^
But that doesn't seem to work, but according to Google that's how you do it

Wicaeed
Feb 8, 2005
Has anyone run into issues with VSCode not properly honoring PSBreakpoints while debugging Powershell?

I'm used to ISE, in that I add a breakpoint & ISE always honors it, however in VSC I add a breakpoint on something even as simple as a comment and VSC just blows right past it sometimes.

The heck?

Adbot
ADBOT LOVES YOU

Wicaeed
Feb 8, 2005
Anyone used the module here before? https://gallery.technet.microsoft.com/scriptcenter/PowerShell-FTP-Client-db6fe0cb/view/Discussions/4

It's useful (in that it works), but I'm having issues when dling large files (50+GB) over and over as the Get-FTPItem always overwrites the local file, even if they are the same and already present on local disk

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply