Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all 6937 articles
Browse latest View live

Date today plus 14 formated like 08 May 2015

$
0
0

I’m trying to get the date +14 days as a string to put in an email.  In the past I’ve used  $60Days=((Get-Date).AddDays(-60)).Date to get the date 60 days ago but I didn’t need to format it with something likeGet-Date-formatD If I try:

 

$Plus14Days=((Get-Date-formatD).AddDays(+14)).Date

 

It errors on method invocation, so what have I got wrong?

Thanks


Cascading Drop Down boxes on Form

$
0
0

Hi,

Can anyone help, my powershell knowledge is limited, but I'm looking to do the following:

Read a CSV file that has a list of devices, i.e.

Location, Type, Device,URL

So I would be looking to populate a form where a user can select location, then select the Type, then device and connect to a corresponding URL. 

Any ideas ? If someone could point me in the right direction.

Thanks

 

 

 

 

SharePoint solution deployment with PowerShell

$
0
0

While working on SharePoint solutions I often need to deploy those solutions in the development environment. Repetitive actions in that process should be automated in order for me to have more time for development and tests. In this post I will present the basic methods that I use to build custom deployment scripts.

Read More

Reporting on Local Accounts Using PowerShell

$
0
0

One of the things that PowerShell doesn't have is a way to view local accounts on local and remote systems. Fortunately for us, we have a couple of options at our disposal that can get around this to view what accounts are built on a system as well as various details about those accounts.

Read More

Todd Klindt: I'm Not Smart Enough for PowerShell

$
0
0

Jeff Hicks is a PowerShell MVP, all-around smart guy — and he’s apparently doing community service for something, because he agreed to share his expertise with us.

Read More

Manage users in Azure RemoteApp based on Active Directory groups, with PowerShell!

$
0
0

Prior to December 11/12/2014 Azure RemoteApp supported functionality to authorize users to an Azure RemoteApp Collection based on Azure Active Directory group membership.

Read More

Spliting up a Text document into blocks

$
0
0

Hello

I have worked out a solution to my issue, but wondered if there is a more elegant way of doing it (for example using RegEx) using less code.

I have a single text file which contains the following

-----BEGIN NEW CERTIFICATE REQUEST-----
Trees
Trees
Trees
Flowers
-----END NEW CERTIFICATE REQUEST-----
-----BEGIN NEW CERTIFICATE REQUEST-----
Cats
Cats
Dogs
-----END NEW CERTIFICATE REQUEST-----

Now start and end are markers form a given section so..

-----BEGIN NEW CERTIFICATE REQUEST-----
Trees
Trees
Trees
Flowers
-----END NEW CERTIFICATE REQUEST-----

forms section 1

and

-----BEGIN NEW CERTIFICATE REQUEST-----
Cats
Cats
Dogs
-----END NEW CERTIFICATE REQUEST-----

forms section 2

There my be 1 section or 100, or any number e.g. do not know how many sections the file will contain.

I want to extract the data between each section and have each  extracted (saved) to a variable where I can reference each one individually latter on.

I came up with the following which works

cls
$i,$Array2,$Data=$null
$Data = gc c:\temp\csr.csr

foreach ($line in $Data) {

if ($line -match "BEGIN NEW CERTIFICATE REQUEST") {$Start = 1;$Array1= @()} else {$start = 0}

if ($line -match "END NEW CERTIFICATE REQUEST") {$End = 1;[array]$Array2 += $Array1 | Out-String } else {$End = 0}


 if ((!($Start)) -and (!($End)))  {
 
 [array]$Array1 += $line

 }

}

$Array2

Can anyone show me a better way to do the above please,

Thanks

AAnotherUser__

Question about running another script with an argument

$
0
0

Hi,

I need to run ps1 file with arguments from a main script.

let's say i have this script - simple function that writes to screen according to the input parameter from the main script :

------------------------------

function test($global:param1) {

write-host $param1

Start-Sleep 3

}

test($param1)

----------------------------

Main script is something like that:

$global:param1="this is a test"

$arglist = "C:\PS_tests\fucntionTest.ps1", "$param1"  

Start-Process powershell.exe -ArgumentList $arglist 

It does run the function and i can see the 3 seconds delay but the parameter param1 is not in used by the function. Any suggestions how to make it work?

Daniel


Reading Remote registry help

$
0
0

Hello All,

Can you please take a look at my script block. It works exactly as expected when I copy/paste it into the console window. However, when I am running it inside a ps1 file, it crashes with the following error:

 

 

Exception calling "OpenRemoteBaseKey" with "2" argument(s): "The network path was not found."
At C:\scripts\InstalledProgramSearch.ps1:61 char:60
+     $RegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey <<<< ($KeyType, $Server.Name)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
--- Script -----
$KeyType = [Microsoft.Win32.RegistryHive]::LocalMachine
Foreach ($Server in $LiveServers){
	$RegKey = $Null
	$RegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($KeyType, $Server.Name)
	IF ($Server.Processor -like 32){$Keys = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'}
	IF ($Server.Processor -like 64){$Keys = 'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall','SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
	}
	$ProgramsCollection = Foreach ($Key in $Keys){
				$SearchKey = $RegKey.OpenSubKey($Key)
				Foreach($sub in $SearchKey.GetSubKeyNames()){
				IF($Sub -like "Microsoft .NET Framework 4 Client Profile"){
				Try {
   				$Server | add-member -MemberType NoteProperty -Name DotNet -Value "Installed" -ErrorAction Stop
				} Catch {}
			}
	}
} 
	IF($Server.DotNet -Like $Null){ $Server | add-member -MemberType NoteProperty -Name DotNet -Value $Null}
}

I know for 100% the failure is due to 2 values assigned to $Keys. For some (i don't get why) reason, when the Foreach grabs the 2nd Key to go into the next loop,

$SearchKey = $RegKey.OpenSubKey($Key)

becomes Null instead of a new value. I have restarted my powershell session and it still persists. Naturally this error takes place on 64-bit systems only Thank you for your help! Russ

Scheduled Task

$
0
0

I need a script to do several things and not sure if one can be scripted or not due to the complexity of it but i will ask anyway.

 

I have created many tasks (hundreds) within task scheduler.... they are antivirus scan tasks that point to a share and when kicked off it scans that share.

the servers they run on are virtual and only have a specific amount of RAM so i can only run a few scans at a time (Around 5 to 7) 

What i need is a script that will kick off a set number of tasks and then when one of the tasks end, it kicks off a new task and keeps on going down the line of tasks.

Also, we do mid-month patching, which means the servers get a reboot. can the script also keep track of where it was before the reboot and pick up where it left off after the reboot?

Not sure if all of that can be done via powershell but wanted to ask.

Thanks

 

How To Validate Parameters in PowerShell

$
0
0

When coding in a script, or even in a fully-featured software application, it's important to account for as many scenarios as possible. To limit the number of possible scenarios, it's a best practice to incorporate some kind of input validation into your code. Input validation, in its simplest terms, is just putting some kind of constraint on the kind of information the user can pass to your script.

Read More 

PowerShell Tools for Visual Studio Supports Remote Sessions, DSC and Workflows

$
0
0

PowerShell Tools for Visual Studio is a Visual Studio extension that brings the power of Visual Studio to PowerShell developers. Adam Driscoll, the original creator of this extension, got help from Microsoft over the past couple of months. The result is a new release, v3.0.108, offering 64-bit and remote session support, among other improvements.

Read More

Welcome, stranger: Inside Microsoft's command line shell

$
0
0

PowerShell is everywhere, it seems. Not just in Windows Server, SharePoint, SQL Server, Exchange, Lync and Azure cloud, but it’s in third-party software, too. Take VMWare PowerCLI – that’s an extension of PowerShell.

Read More

powershell Decompress zip file

$
0
0

Hi,

I'm trying to write a script that reads a zip file and extracts only the files that have a particular extension.

It works when I specify:

[String]$zipfiles = (Get-ChildItem "E:\zips\" "*.zip").Fullname 

But errors when I specify:

[String]$zipfiles = Get-ChildItem "E:\zips\" "*.zip" | sort LastWriteTime | Select Fullname -ExpandProperty Fullname | Out-String 

With the message:

Exception calling "OpenRead" with "1" argument(s): "Illegal characters in path."

I'm passing the file path to OpenRead within a foreach object loop:

[IO.Compression.ZipFile]::OpenRead($zipfile).Entries

I can't see the illegal character and get member for both shows system.string and they both look identical to me.

Any ideas?

Need some advice please

$
0
0

When I am testing scripts with wmi queries during business hours, they randomly fail on random servers.

Meaning, I need to put in "retry 3 times" logic in order to confirm if the device I am querying is actually having an RPC problem such as a stalled / stopped WMI service.

What is the best way to retry such queries? I feel that Im over doing in the example below...

 Do {
    $WMIErrorCounter=0
    Try {        
        $Service = Get-WmiObject -Class Win32_Service -ComputerName $Computer -EnableAllPrivileges -ErrorAction Stop | Select Caption, State, PathName | ? {$_.PathName -like "*sqlservr.exe*" -and $_.Caption -notlike "*$*" -and $_.Caption -notlike "*#*"}                
    }
    Catch {
            $WMIErrorCounter++
            $ErrorMessage
            IF ($WMIErrorCounter -eq 3){$WMIError = $True}
            Else {$WMIError = $False}
    }
    If ($WMIError){
            $ErrorMessage = "WMI Connection Failed - $Error[0].FullyQualifiedErrorId"
            $SQLProperties = SetOutput -ComputerName $Computer -ErrorMessage $ErrorMessage
            New-Object -TypeName psobject -Property $SQLProperties    
    }
    $WMIErrorCounter = 3
    
    } Until ($WMIErrorCounter = 3)


memory quota Issues when running script

$
0
0

Get-Mailbox -ResultSize Unlimited | Get-MailboxFolderStatistics | Where-Object {$_.Name -eq "Outbox" -and $_.ItemsInFolder -gt '0' } | Select-Object Identity, FolderType, ItemsinFolder, FolderSize | Export-CSV "C:\Outbox.csv"

Hi Guys

When I run this script it is able to get some data in the csv file but eventually I get a message bellow.

Processing data for a remote command failed with the following error message: Deserialized objects exceed the memory quota. For more information, see
 the about_Remote_Troubleshooting Help topic

I tried setting the MaxMemoryPerShellMB from the default to 1024 and then 2048 but I still have the problem. Is there a way I can get that to work? Would a ForEach-Object be better and not have the memory issuesbecause it would not have to load all into memory. Our Exchange Org is very large.

Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024

 

 

Optional Credentials

$
0
0

I writing a function, taht I would like to have an optional credential parameter.

By this I mean, taht if no credential is given, the function should "just" use the current users credential, but the function should also allow me to enter specific credentials, in much the same way as several existing cmdlets.

How can I accomplish this in PowerShell?

 

Function Get-Stuff {

Param ($computername,$credential)

Get-WmiObject Win32_Bios -computername $computername -credential $credential

}

add to the registry on remote servers

$
0
0

Hi all, new to PS and i have a challenge at work.. i have a .reg file that i need to apply to alot of our servers (but not all!)

 

i have a list of them, but how do i do it?

 

what i tried so far is this:

 

$targetservers = Get-Content C:\skripts\sqltest.txt

$originalfile = "\\server\Shared Folders\IT\DBA\02 Scripts\WinServerAdmin\ODBCsources\RegKey_UTV9.reg"

$newfile = "c:\install\registry\utv9.reg"

foreach ($server in $targetservers)

{

Copy-Item $originalfile -Destination $newfile

Invoke-Command -ComputerName $server -ScriptBlock {

Start-Process -filepath "C:\windows\regedit.exe" -argumentlist "/s $newfile"

    }

}

 

it creates the new file on MY pc (and i would be fine with that if it worked) and thats it! no error message at all, and the .reg file has not been applied!

 

i need some help here, i am clearly missing something.... 

modify text string in file

$
0
0

All,

I am looking for direction on manipulating text in a text file. I have a bunch on entries for device names in a file and I would like to generate a pwd for each machine that is the reverse of the device name. This is for a testing lab and nothing more. I don't know where to start for taking an input string and reverse ordering it to out it back onto the file.

Process for script

1. Read a text file for the name
2. Reverse the output to console or into a tab delimited output

EX

DeviceName1 1emanecived
DeviceName2 2emanecived

Apply Registry File to Remote Systems

$
0
0

I'm trying to apply a registry file to remote systems defined in a list.  I tried the following from this thread:

 

$targetservers = Get-Content servers.txt

$HostedRegFile = "C:\Scripts\RegistryFiles\test.reg"

$newfile = "\\$server\c$\Downloads\RegistryFiles\test.reg"

 

foreach ($server in $servers)

{

Copy-Item $HostedRegFile -Destination $newfile

Invoke-Command -ComputerName $server -ScriptBlock {

Start-Process -filepath "C:\windows\regedit.exe" -argumentlist "/s $newfile"

    }

}

 

I get the following error:



I made some edits and got the .reg file to copy over, but it still didn't execute on the remote machines and add content to the registry.

Any ideas how to get it to actually apply?

Thanks for the help.

Viewing all 6937 articles
Browse latest View live