MECM/SCCM Application Deployment - sccm

I'm currently having an issue. Using Powershell, I'm trying to create deployments for multiple applications for multiple collections without having to hardcode anything. For example, lets say that if I have 4 collections and 4 applications. I want to be able to create an deployment with all 4 collections for all 4 for the applications. Currently this is the code that I have:
$dpgName = Get-CMDistributionPointGroup -Name "All_Distribution_Groups"
$collName = Get-CMCollection -Name "*Patching*"
foreach ($coll in $collName.Name){
(Get-CMApplication | Where-Object {$_.LocalizedDisplayName -like "Visual C++ Redistributable*"} | Select LocalizedDisplayName) | % {New-CMApplicationDeployment -CollectionName $coll -Name "$($_.LocalizedDisplayName)" -DeadlineDateTime (get-date) -TimeBaseOn LocalTime -DeployAction Install -DeployPurpose Required -OverrideServiceWindow $False -RebootOutsideServiceWindow $False -UserNotification DisplaySoftwareCenterOnly -EnableMomAlert $False -GenerateScomAlertOnFailure $False -DistributionPointGroupName $dpgName -DistributeContent}
}
But when I attempt to run this script, I get the following error:
New-CMApplicationDeployment : Validation of input parameters failed. Cannot continue.
At line:5 char:133
+ ... yName) | % {New-CMApplicationDeployment -CollectionName $coll -Name " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (Microsoft.Confi...ationDeployment:NewApplicationDeployment) [New-CMApplicationDeployment], InvalidOperationException
+ FullyQualifiedErrorId : ValidationFailed,Microsoft.ConfigurationManagement.PowerShell.Cmdlets.Deployments.NewApplicationDeployment

Related

PowerShell script to connect all network printers on servers and then remove them

I have a list of around 15 servers that for each one of them I want to connect to all network printers on a printer server, and then remove all connections.
This is the powershell script I wrote-
$servers = Get-Content -Path <path to csv>
foreach ($server in $servers){
$printers = Import-Csv -Path <path to csv>
foreach ($printer in $printers){
$printername = "\\printerserver\" + $printer
Add-Printer -ConnectionName $printername | Out-Null
}
Get-WmiObject Win32_Printer | where{$_.Network -eq ‘true‘} | foreach{$_.delete()}
}
The servers CSV contains a single column with FQDN'S of said servers.
The printers CSV contains plain names of network printers.
This is the error I am receiving:
Add-Printer : The specified server does not exist, or the server or printer name is invalid. Names may not contain ',' or '\' characters.
At line:9 char:1
+ Add-Printer -ConnectionName $printername | Out-Null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (MSFT_Printer:ROOT/StandardCimv2/MSFT_Printer) [Add-Printer], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070709,Add-Printer
What am I doing wrong here? Thanks.
Edit 1:
Content of servers csv:
servername
server01.domain
server02.domain
server03.domain
Content of printers csv:
printername
printer01
printer02
printer03

New-ADUser unable to concatanate name and domainname

I'm trying to create userprincipalname as combination of username and hardcoded domainname
csv file:
name,displayname,givenname,surname
dhall,Don Hall,Don,Hall
Code:
Import-csv "c:\output.csv" | ForEach-Object {new-aduser -name $_.name -UserPrincipalName ("{0}#{1}" -f $_.name,"Dev.domain.Net") -DisplayName "$($_.givenname $_.surname)" -givenName $_.givenname -surname $_.surname -path "OU=Workspaces,DC=Dev,DC=domain,DC=Net" -AccountPassword (convertto-securestring passs -asplaintext -force) -Enabled [System.Convert]::toboolean($true)) -ChangePasswordAtLogon ([system.convert]::ToBoolean($true))}
And getting:
At line:1 char:159
+ ... -f $_.name,"Dev.domain.Net") -DisplayNa
+
Unexpected token '$_' in expression or stateme
+ CategoryInfo : ParserError: (:)
+ FullyQualifiedErrorId : UnexpectedToken
Tried also -UserPrincipalName ([string]::Concat($_.name,"#dev.domain.net"))
but same error
PS C:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
5 1 14393 1944
Windows server 2016
Not sure what's causing that error (don't have an AD controller to test against at the moment so can't validate) but in cases where I'm going to need to reuse a property multiple times I tend to assign it to a temporary variable (makes it slightly easier to write the code and don't run into issues with the pipeline variable getting updated).
Import-CSV "c:\output.csv" | ForEach-Object {
$name = $_.name
$upn = "{0}#{1}" -f $name,"dev.domain.net"
New-ADUser -Name $name -UserPrincipalName $upn #...
}

Metadata export error when running on large directory structures

This script exports the basic file metadata in PowerShell to a .csv.
PS K:\> Get-childitem -recurse -file | select-object length,lastwritetime,fullname | export-csv filelist.csv -notypeinformation
It works great on simple directory structures of 10-20K files, but when I run it on 500K+ files of complex, multi-level directory structures it freezes or gives me error:
At line:1 char:1
+ Get-childitem -recurse -file | select-object length,lastwritetime,ful ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (0:Int32) [], RuntimeException
+ FullyQualifiedErrorId : CallDepthOverflow
Is this a problem with the -recurse or else? Using PowerShell 5 1 (Major Minor).
Test to see how long the filepaths are.
If the filepaths are more than 248 characters... That may be why you are getting the error.
To check to see if any come back with more than 248 characters you can do
Get-childitem "filepath" -recurse | % {
$filepath = $_.FullName
$charactercount = ($filepath | Measure-Object -Character).Characters
If ($charactercount -gt 248){write-host $filepath}
}

Unable to run PowerShell script in Windows 2008 R2 Standard which is installed by Vagrant

I am unable to run this PowerShell script
# Execute .exe file
Get-ChildItem "C:\vagrant" -Filter *.exe | Where Name -NotMatch '.*NoDB\.exe$' | % {
New-Object psobject -Property #{
No = [int]([regex]::Match($_.Name, '(?<=CL)\d+').Value)
Name = $_.FullName
}
} | Sort No -Descending | Select -ExpandProperty Name -First 1 |
Foreach { & $_ -s2 -sp"-SilentInstallation=server -UpdateMaterials=yestoall -UpgradeDBIfRequired=yes"}
in Windows Windows 2008 R2 Standard because
**********************
Windows PowerShell Transcript Start
Start time: 20160719080730
Username : VAGRANT-2008R2\vagrant
Machine : VAGRANT-2008R2 (Microsoft Windows NT 6.1.7601 Service Pack 1)
**********************
Transcript started, output file is C:\Users\vagrant\Documents\PowerShell_transc
ript.20160719080730.txt
Where-Object : Cannot bind parameter 'FilterScript'. Cannot convert the "Name"
value of type "System.String" to type "System.Management.Automation.ScriptBlock
".
At C:\vagrant\Install_Ortho.ps1:7 char:49
+ Get-ChildItem "C:\vagrant" -Filter *.exe | Where <<<< Name -NotMatch '.*NoDB
\.exe$' | % {
+ CategoryInfo : InvalidArgument: (:) [Where-Object], ParameterBi
ndingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerSh
ell.Commands.WhereObjectCommand
**********************
Windows PowerShell Transcript End
End time: 20160719080730
**********************
I tried to use this advice "Try using {} instead of parentheses around your argument." Same error.
This syntax:
Where Property -[OperatorAsParameterName] 'value'
is introduced in PowerShell 3.0 - Windows 2008 R2 comes with PowerShell 2.0!
The version 2.0 equivalent would be:
Where {$_.Name -NotMatch '.*NoDB\.exe$'}
You may fix that one instance, but then other parts of the scripts will likely going to fail, and you have to keep fixing version 3.0 syntax until you've rewritten the entire thing
I would recommend finding a 2008R2-specific version of Vagrant, or filing this finding as a compatibility bug with their development team

Remove-Item doesn't work, Delete does

Does anyone have any idea why Remove-Item would fail while Delete works?
In below script, I get a list of files I'd like to delete.
Using Remove-Item I get following error message:
VERBOSE: Performing the operation "Remove File" on target
"\\UncPath\Folder\test.rtf". Remove-Item : Cannot remove item
\\UncPath\Folder\test.rtf: Access to the path is denied.
but using Delete is deleting those files as we speak.
Script
$files = gci \\UncPath\Folder| ?{ $_.LastWriteTime -le (Get-Date).addDays(-28) }
# This doesn't work
$files | Remove-Item -force -verbose
# But this does
$files | % { $_.Delete() }
powershell may act strange with UNC path, I think it prepends the UNC Path with the current provider you can verify this with :
cd c:
test-path \\127.0.0.1\c$
returns TRUE
cd HKCU:
test-path \\127.0.0.1\c$
returns FALSE
when specifying the fullpath we're telling powershell to use the filesystem provider, that solves the problem. you could also specify the provider like remove-item filesystem::\\uncpath\folder
I can finally repro this and IMO it appears to be a bug. The repro is to have an open share like C$ but to set Deny Modify perms for the user on the file. When I do that, I observe this:
PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | ri -for
ri : Cannot remove item \\Keith-PC\C$\Users\Keith\foo.txt: Access to the path is denied.
At line:1 char:43
+ gci '\\Keith-PC\C$\Users\Keith\foo.txt' | ri -for
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (\\Keith-PC\C$\Users\Keith\foo.txt:FileInfo) [Remove-Item], ArgumentExc
eption
+ FullyQualifiedErrorId : RemoveFileSystemItemArgumentError,Microsoft.PowerShell.Commands.RemoveItemCommand
PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Delete()} # <== this works!
I also observe that removing the -Force parameter deletes the file without error as well. The deny perms still allow me to delete the file from Windows Explorer so that leads me to believe that the file should delete. So what is up with using the -Force parameter? When I delve into the ErrorRecord I see this:
Message : Access to the path is denied.
ParamName :
Data : {}
InnerException :
TargetSite : Void set_Attributes(System.IO.FileAttributes)
StackTrace : at System.IO.FileSystemInfo.set_Attributes(FileAttributes value)
at Microsoft.PowerShell.Commands.FileSystemProvider.RemoveFileSystemItem(FileSystemInfo
fileSystemInfo, Boolean force)
It seems that the -Force parameter is trying to set (more likely reset) attributes and the permissions on the file don't allow it e.g.:
PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Attributes = 'Normal'}
Exception setting "Attributes": "Access to the path is denied."
At line:1 char:45
+ gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Attributes = 'Normal'}
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
So it seems to me that PowerShell should first try as if the -Force weren't present and if that fails, then try resetting attributes.

Resources