Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Tuesday, April 21, 2015

Use User Credentials in MDT 2013 to Run Powershell Script

#UserName
$tmpuser=$tsenv:UserID
$tmpuser=[System.Text.Encoding]::Default.GetString([System.Convert]::FromBase64String($tmpuser))

#DomainName
$tmpdomain=$tsenv:UserDomain
$tmpdomain=[System.Text.Encoding]::Default.GetString([System.Convert]::FromBase64String($tmpdomain))

#set password to variable
$tmppassword=$tsenv:UserPassword

#Decode Password
[string]$tmppassword=[System.Text.Encoding]::Default.GetString([System.Convert]::FromBase64String($tmppassword))

#Convert to secure string
$mypassword=ConvertTo-SecureString -String $tmppassword -AsPlainText -Force

#format domainname\username for PSCredential object
[string]$tmpFQusername=$tmpdomain + "\" + $tmpuser

$creds = new-object System.Management.Automation.PSCredential($tmpFQusername,$mypassword)


Place the above code into your custom scripts to use PScredentials

Wednesday, February 25, 2015

Using PSEXEC to execute powershell scripts remotely

I ran into an issue where I found myself having to hit the any key to complete a psexec call to a batch file that launches powershell. The workaround was to add -inputformat none to my launch parameters for powershell.

example: powershell -inputformat none -file C:\scripts\StampBackups.ps1 -executionpolicy bypass 

ref http://stackoverflow.com/questions/4238192/running-powershell-from-msdeploy-runcommand-does-not-exit/4239192#4239192

ref https://connect.microsoft.com/PowerShell/feedback/details/572313/powershell-exe-can-hang-if-stdin-is-redirected

Tuesday, June 5, 2012

VMWare Physical to Virtual Conversion Speedup

Here is a powershell script I wrote that disables SSL for  P2V Conversions using VM converter. 

$xml = New-Object XML
Function FindIT {
#test to see if it's a vista or better
if (Test-Path "$env:programdata\VMware\VMware vCenter Converter Standalone\converter-worker.xml"){
$filelocation = "$env:programdata\VMware\VMware vCenter Converter Standalone\converter-worker.xml";return $filelocation }
#test to see if it's 2k3 or older
Elseif (Test-Path "$Env:AllusersProfile\Application Data\VMware\VMware vCenter Converter Standalone\converter-worker.xml"){
$filelocation = "$Env:AllusersProfile\Application Data\VMware\VMware vCenter Converter Standalone\converter-worker.xml";return $filelocation}
else {Return $false}
}

if(!($filelocation= FindIT) -eq $false){
$xml.load($filelocation)
if ($xml.Config.nfc.useSSl -eq "true") {
Write-Host "SSL is Enabled.  I'm backing it up and changing it."
if (Test-Path "$filelocation.old"){Remove-Item "$filelocation.old" -Force}
Rename-Item "$filelocation" -NewName "$filelocation.old"
$xml.Config.nfc.useSSl = "false"
$xml.Save("$filelocation")
}else{Write-Host "SSL is not enabled"}
} else { Write-Host "I didn't find it where I thought it should be... Sorry." }



Update:  I changed the hard coded path to $env:programdata for vista+
Update:  I changed the hard coded path to $Env:AllusersProfile for 2003-

Sunday, June 3, 2012

Set Replicating Directory Changes for Sharepoint Userprofile service


Script to Set Replicating Directory Changes for Sharepoint Userprofile service.

This covers both aspects of the Replicating AD Permissions that need to be setup for sync process to work properly.  This was written as a result of reading http://www.harbar.net/articles/sp2010ups.aspx


Function Set-replicatingChanges{
param (
$domain,
$path)

#change this for your USER PROFILE SYNC Account
$user = "sp_userprofile"
$path
$acl = get-acl ".\$path"
#get sid of user
$objUser = New-Object System.Security.Principal.NTAccount($domain, $user)
$SID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])

$ReplicatingChangesGUID = new-object Guid 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2
$act = [System.Security.AccessControl.AccessControlType]::Allow
$readProperty = [System.DirectoryServices.ActiveDirectoryRights]::ReadProperty
$GenericExecute = [System.DirectoryServices.ActiveDirectoryRights]::GenericExecute
$ExtendedRight = [System.DirectoryServices.ActiveDirectoryRights]::ExtendedRight

#sets permissions
$ace = New-Object System.DirectoryServices.ActiveDirectoryAccessRule -ArgumentList ($SID, $ReadProperty, $act)
$ACL.addaccessrule($ace)
$ace = New-Object System.DirectoryServices.ActiveDirectoryAccessRule ($SID, $GenericExecute, "Allow")
$ACL.addaccessrule($ace)
$ace = New-Object System.DirectoryServices.ActiveDirectoryAccessRule($SID, $ExtendedRight, "Allow",$ReplicatingChangesGUID)
$ACL.addaccessrule($ace)
Set-Acl -ACLObject $acl -Path ".\$path"

}

#ipmo activeDirectory #automate this
if (!(Get-Module -name activedirectory)){
if ((Get-Module -ListAvailable|?{$_.name -eq "activedirectory"})){ipmo activedirectory}
}
if (test-path ad:){cd ad:}else{Write-Host "I couldn't map to ad:" -ForegroundColor Red;break}

$domain =$env:USERDOMAIN
$configContainer=(gci|?{$_.Objectclass -eq "Configuration"}).DistinguishedName
$domainDN = (gci|?{$_.name -eq $domain}).DistinguishedName

set-replicatingChanges $domain $configContainer
set-replicatingChanges $domain $domainDN

Saturday, June 2, 2012

Set IP Address via Powershell

I wanted to script a complete install from powershell for my lab enviroment.  So I knew i had to start with some plain old fashion calls to wmi and whatnot.  So I ended up googling it and came across Andy's post over at wordpress http://getpowershell.wordpress.com/2008/08/13/powershell-function-set-ipaddress/

So easily read and cleanly coded I wanted to share here as well, the only modifications that I changed was adding the requirement that parameters that have to be specified and out-null some responses.:



function Set-IPAddress {
param(  
[parameter(Mandatory = $true)][string]$networkinterface,
[parameter(Mandatory = $true)][string]$ip,
[parameter(Mandatory = $true)][string]$mask,
[parameter(Mandatory = $true)][string]$gateway,
[parameter(Mandatory = $true)][string]$dns1,
[string]$dns2,
[string]$registerDns = "TRUE"
)


$dns = $dns1
if($dns2){$dns ="$dns1,$dns2"}
$index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex
$NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index}|out-null
$NetInterface.EnableStatic($ip, $mask)|out-null
$NetInterface.SetGateways($gateway)|out-null
$NetInterface.SetDNSServerSearchOrder($dns)|out-null
$NetInterface.SetDynamicDNSRegistration($registerDns)|out-null
}



Friday, June 1, 2012

Powershell Community extensions command reference


http://www.codeplex.com/PowerShellCX

How did I get the list below for you?
 Get-Command|where {$_.modulename -eq "pscx"}|% {$_.name}

Add-DirectoryLength
Add-PathVariable
Add-ShortPath
call
Clear-MSMQueue
ConvertFrom-Base64
ConvertTo-Base64
ConvertTo-MacOs9LineEnding
ConvertTo-Metric
ConvertTo-UnixLineEnding
ConvertTo-WindowsLineEnding
Convert-Xml
cvxml
Disconnect-TerminalSession
Dismount-VHD
e
Edit-File
Edit-HostProfile
Edit-Profile
ehp
Enable-OpenPowerShellHere
ep
Expand-Archive
Export-Bitmap
fhex
Format-Byte
Format-Hex
Format-Xml
fxml
gcb
Get-ADObject
Get-AdoConnection
Get-AdoDataProvider
Get-AlternateDataStream
Get-Clipboard
Get-DhcpServer
Get-DomainController
Get-DriveInfo
Get-EnvironmentBlock
Get-FileTail
Get-FileVersionInfo
Get-ForegroundWindow
Get-Hash
Get-Help
Get-HttpResource
Get-LoremIpsum
Get-MountPoint
Get-MSMQueue
Get-OpticalDriveInfo
Get-PathVariable
Get-PEHeader
Get-Privilege
Get-PropertyValue
Get-PSSnapinHelp
Get-ReparsePoint
Get-ScreenCss
Get-ScreenHtml
Get-ShortPath
Get-TabExpansion
Get-TerminalSession
Get-TypeName
Get-Uptime
Get-ViewDefinition
gpv
gtn
help
igc
Import-Bitmap
Invoke-AdoCommand
Invoke-Apartment
Invoke-BatchFile
Invoke-Elevated
Invoke-GC
Invoke-Method
Invoke-NullCoalescing
Invoke-Reflector
Invoke-Ternary
Join-String
less
ln
lorem
Mount-VHD
New-Hardlink
New-HashObject
New-Junction
New-MSMQueue
New-Shortcut
New-Symlink
nho
ocb
Out-Clipboard
Out-Speech
Ping-Host
Pop-EnvironmentBlock
Push-EnvironmentBlock
ql
qs
QuoteList
QuoteString
Read-Archive
Receive-MSMQueue
Remove-AlternateDataStream
Remove-MountPoint
Remove-ReparsePoint
Resize-Bitmap
Resolve-ErrorRecord
Resolve-Host
Resolve-HResult
Resolve-WindowsError
rf
rver
rvhr
rvwer
Send-MSMQueue
Send-SmtpMail
Set-BitmapSize
Set-Clipboard
Set-FileTime
Set-ForegroundWindow
Set-LocationEx
Set-PathVariable
Set-Privilege
Set-ReadOnly
Set-VolumeLabel
Set-Writable
Show-Tree
skip
Skip-Object
sls
Split-String
sro
Start-TabExpansion
Stop-RemoteProcess
Stop-TerminalSession
su
swr
tail
Test-AlternateDataStream
Test-Assembly
Test-MSMQueue
Test-Script
Test-UserGroupMembership
Test-Xml
touch
Unblock-File
Write-BZip2
Write-Clipboard
Write-GZip
Write-Tar
Write-Zip

Wednesday, March 14, 2012

SQL Powershell Set all DBs to Simple recovery

Simple recovery model has its place but here's an easy way to set it programatically

$DBinstanace = sqlserver:\sql\\
gci $DBinstanace\Databases| where {$_.RecoveryModel -like "Full"}|`
foreach {
$_.RecoveryModel = [Microsoft.SqlServer.Management.Smo.RecoveryModel]::Simple
$_.Alter()
}

Friday, October 15, 2010

Exchange 2007 servicecontrol.ps1 bug

You run ServiceControl.ps1 AfterPatch or ServiceControl.ps1 and get the error below. Microsoft made a mistake !

It's a bug in the script...

add a line at line 900:

$activity = 'BeforePatch'

add a line at line 958:

$activity='AfterPatch'


----------- snippet of error --------------
Write-Progress : Cannot bind argument to parameter 'Activity' because it is nul
l.
At D:\Program Files\Microsoft\Exchange Server\bin\ServiceControl.ps1:1017 char:
25
+ write-Progress -Activity <<<< $activity -Id 0 -Status 'Completed' -Completed
+ CategoryInfo : InvalidData: (:) [Write-Progress], ParameterBind
ingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M
icrosoft.PowerShell.Commands.WriteProgressCommand