Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Content library deployment tool vCenter

$
0
0

Afternoon all

I'm building a Powershell script that will enable me to deploy VM's from my vCenter content library after filling in a brief form. This form pulls through some information from the vCenter to aid in completing it.

I've 2 current issues:

1. If a Combobox only receives only a single result to populate with, I get the below error:

exception settings "datasource": "Complex DataBinding accepts as a data source either an IList or an IListSource

2. When pulling back all the VM folder names, it doesn't list them in a nice tree view like vCenter does (for example, we have several folders identically named "compute") so in order to make these readable, I put in a command that gives the parent folder, followed by the 2nd level folder and finally the ID of that folder. Is there any way to get just the "ID" bit out of the Combobox to pass through to a variable for the rest of my script to use?

# Drawing the box


Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

$CDWVMDeploy                     = New-Object system.Windows.Forms.Form
$CDWVMDeploy.ClientSize          = '500,689'
$CDWVMDeploy.text                = "CDWVMDeploy"
$CDWVMDeploy.TopMost             = $false

$Title                           = New-Object system.Windows.Forms.Label
$Title.text                      = "CDW ServiceWorks VM Deployment Tool"
$Title.AutoSize                  = $true
$Title.width                     = 25
$Title.height                    = 10
$Title.location                  = New-Object System.Drawing.Point(23,25)
$Title.Font                      = 'Microsoft Sans Serif,10,style=Bold'
$Title.ForeColor                 = "#ff0000"

$vCenterLabel                    = New-Object system.Windows.Forms.Label
$vCenterLabel.text               = "Which vCenter?"
$vCenterLabel.AutoSize           = $true
$vCenterLabel.width              = 25
$vCenterLabel.height             = 10
$vCenterLabel.location           = New-Object System.Drawing.Point(21,57)
$vCenterLabel.Font               = 'Microsoft Sans Serif,10'

$vCenterChoice                   = New-Object system.Windows.Forms.ComboBox
$vCenterChoice.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
$vCenterChoice.width             = 141
$vCenterChoice.height            = 20
@('1','2') | ForEach-Object {[void] $vCenterChoice.Items.Add($_)}
$vCenterChoice.location          = New-Object System.Drawing.Point(19,84)
$vCenterChoice.Font              = 'Microsoft Sans Serif,10'

$OSChoice                        = New-Object system.Windows.Forms.ComboBox
$OSChoice.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
$OSChoice.width                  = 200
$OSChoice.height                 = 20
@('cl_template-CentOS7','cl_template-RHL6.4','cl_template-fgvm-FGVM-5.6.4','cl_template-w2008R2-std','cl_template-w2012-std','cl_template-w2012R2-std','cl_template-w2016-std','cl_template-w2019-std') | ForEach-Object {[void] $OSChoice.Items.Add($_)}
$OSChoice.location               = New-Object System.Drawing.Point(19,148)
$OSChoice.Font                   = 'Microsoft Sans Serif,10'

$OSLabel                         = New-Object system.Windows.Forms.Label
$OSLabel.text                    = "OS Choice?"
$OSLabel.AutoSize                = $true
$OSLabel.width                   = 25
$OSLabel.height                  = 10
$OSLabel.location                = New-Object System.Drawing.Point(21,118)
$OSLabel.Font                    = 'Microsoft Sans Serif,10'

$VMNameChoice                    = New-Object system.Windows.Forms.TextBox
$VMNameChoice.multiline          = $false
$VMNameChoice.width              = 244
$VMNameChoice.height             = 40
$VMNameChoice.location           = New-Object System.Drawing.Point(20,347)
$VMNameChoice.Font               = 'Microsoft Sans Serif,10'

$CPUChoice                       = New-Object system.Windows.Forms.ComboBox
$CPUChoice.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
$CPUChoice.width                 = 100
$CPUChoice.height                = 20
@('1','2') | ForEach-Object {[void] $CPUChoice.Items.Add($_)}
$CPUChoice.location              = New-Object System.Drawing.Point(19,214)
$CPUChoice.Font                  = 'Microsoft Sans Serif,10'

$CPUSocketLabel                  = New-Object system.Windows.Forms.Label
$CPUSocketLabel.text             = "vSocket"
$CPUSocketLabel.AutoSize         = $true
$CPUSocketLabel.width            = 25
$CPUSocketLabel.height           = 10
$CPUSocketLabel.location         = New-Object System.Drawing.Point(21,185)
$CPUSocketLabel.Font             = 'Microsoft Sans Serif,10'

$RAMLabel                        = New-Object system.Windows.Forms.Label
$RAMLabel.text                   = "RAM (GB)"
$RAMLabel.AutoSize               = $true
$RAMLabel.width                  = 25
$RAMLabel.height                 = 10
$RAMLabel.location               = New-Object System.Drawing.Point(140,185)
$RAMLabel.Font                   = 'Microsoft Sans Serif,10'

$RAMChoice                       = New-Object system.Windows.Forms.ComboBox
$RAMChoice.width                 = 100
$RAMChoice.height                = 20
@('2','4','6','8','10','12','16','20','24','32','48','64','128') | ForEach-Object {[void] $RAMChoice.Items.Add($_)}
$RAMChoice.location              = New-Object System.Drawing.Point(140,213)
$RAMChoice.Font                  = 'Microsoft Sans Serif,10'

$VMNameLabel                     = New-Object system.Windows.Forms.Label
$VMNameLabel.text                = "VM Name?"
$VMNameLabel.AutoSize            = $true
$VMNameLabel.width               = 25
$VMNameLabel.height              = 10
$VMNameLabel.location            = New-Object System.Drawing.Point(21,319)
$VMNameLabel.Font                = 'Microsoft Sans Serif,10'

$DeployButton                    = New-Object system.Windows.Forms.Button
$DeployButton.text               = "DEPLOY"
$DeployButton.width              = 174
$DeployButton.height             = 49
$DeployButton.location           = New-Object System.Drawing.Point(75,617)
$DeployButton.Font               = 'Microsoft Sans Serif,25,style=Bold'
$DeployButton.ForeColor          = "#7ed321"

$vCoreLabel                      = New-Object system.Windows.Forms.Label
$vCoreLabel.text                 = "vCore (Socket x Core = Total vCPU)"
$vCoreLabel.AutoSize             = $true
$vCoreLabel.width                = 25
$vCoreLabel.height               = 10
$vCoreLabel.location             = New-Object System.Drawing.Point(21,253)
$vCoreLabel.Font                 = 'Microsoft Sans Serif,10'

$CoreBox                         = New-Object system.Windows.Forms.ComboBox
$CoreBox.width                   = 100
$CoreBox.height                  = 20
@('1','2','3','4','6','8','10','12','16') | ForEach-Object {[void] $CoreBox.Items.Add($_)}
$CoreBox.location                = New-Object System.Drawing.Point(19,282)
$CoreBox.Font                    = 'Microsoft Sans Serif,10'

$ConnectButton                   = New-Object system.Windows.Forms.Button
$ConnectButton.text              = "Connect"
$ConnectButton.width             = 99
$ConnectButton.height            = 26
$ConnectButton.location          = New-Object System.Drawing.Point(185,81)
$ConnectButton.Font              = 'Microsoft Sans Serif,10,style=Bold'
$ConnectButton.ForeColor         = "#7ed321"

$DatastoreChoice                 = New-Object system.Windows.Forms.ComboBox
$DatastoreChoice.width           = 244
$DatastoreChoice.height          = 20
$DatastoreChoice.location        = New-Object System.Drawing.Point(20,411)
$DatastoreChoice.Font            = 'Microsoft Sans Serif,10'

$DatastoreLabel                  = New-Object system.Windows.Forms.Label
$DatastoreLabel.text             = "Datastore?"
$DatastoreLabel.AutoSize         = $true
$DatastoreLabel.width            = 25
$DatastoreLabel.height           = 10
$DatastoreLabel.location         = New-Object System.Drawing.Point(21,381)
$DatastoreLabel.Font             = 'Microsoft Sans Serif,10'

$NetworkLabel                    = New-Object system.Windows.Forms.Label
$NetworkLabel.text               = "Network?"
$NetworkLabel.AutoSize           = $true
$NetworkLabel.width              = 25
$NetworkLabel.height             = 10
$NetworkLabel.location           = New-Object System.Drawing.Point(21,439)
$NetworkLabel.Font               = 'Microsoft Sans Serif,10'

$NetworkChoice                   = New-Object system.Windows.Forms.ComboBox
$NetworkChoice.width             = 245
$NetworkChoice.height            = 20
$NetworkChoice.location          = New-Object System.Drawing.Point(19,460)
$NetworkChoice.Font              = 'Microsoft Sans Serif,10'

$ClusterLabel                    = New-Object system.Windows.Forms.Label
$ClusterLabel.text               = "Cluster?"
$ClusterLabel.AutoSize           = $true
$ClusterLabel.width              = 25
$ClusterLabel.height             = 10
$ClusterLabel.location           = New-Object System.Drawing.Point(23,490)
$ClusterLabel.Font               = 'Microsoft Sans Serif,10'

$ClusterChoice                   = New-Object system.Windows.Forms.ComboBox
$ClusterChoice.width             = 245
$ClusterChoice.height            = 20
$ClusterChoice.location          = New-Object System.Drawing.Point(21,511)
$ClusterChoice.Font              = 'Microsoft Sans Serif,10'

$FolderLabel                     = New-Object system.Windows.Forms.Label
$FolderLabel.text                = "VM Folder?"
$FolderLabel.AutoSize            = $true
$FolderLabel.width               = 25
$FolderLabel.height              = 10
$FolderLabel.location            = New-Object System.Drawing.Point(25,548)
$FolderLabel.Font                = 'Microsoft Sans Serif,10'

$FolderChoice                    = New-Object system.Windows.Forms.ComboBox
$FolderChoice.width              = 450
$FolderChoice.height             = 20
$FolderChoice.location           = New-Object System.Drawing.Point(21,575)
$FolderChoice.Font               = 'Microsoft Sans Serif,10'

$CDWVMDeploy.controls.AddRange(@($Title,$vCenterLabel,$vCenterChoice,$OSChoice,$OSLabel,$VMNameChoice,$CPUChoice,$CPUSocketLabel,$RAMLabel,$RAMChoice,$VMNameLabel,$DeployButton,$vCoreLabel,$CoreBox,$ConnectButton,$DatastoreChoice,$DatastoreLabel,$NetworkLabel,$NetworkChoice,$ClusterLabel,$ClusterChoice,$FolderLabel,$FolderChoice))




#End GUI Region



#Disable certificate checking
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false

#What happens when clicking "connect" button
$ConnectButton.Add_Click({ConnecttoVC})
function ConnecttoVC
{
#Disconnect any existing sessions
disconnect-viserver -Confirm:$false

#connect to vCenter
connect-viserver $vCenterChoice.selecteditem


#Get Folder into FolderChoice box
$Folders = get-folder | where{$_.Type -eq "vm"} | select parent,name,id |Sort-Object parent
$FolderChoice.DataSource = $Folders
$FolderChoice.SelectedItem

#Get Cluster choice 
$Clusters = Get-Cluster
$ClusterChoice.Datasource = $Clusters
$ClusterChoice.SelectedItem

#Get Datastore choice

$Datastores = Get-Datastore | Sort-Object
$DatastoreChoice.DataSource = $Datastores
$DatastoreChoice.SelectedItem

#Get networks choice

$Network = Get-VDPortGroup | Sort-Object
$NetworkChoice.DataSource = $Network
$NetworkChoice.SelectedItem
}

#What happens when clicking "deploy" button
$DeployButton.Add_Click({DeployVM})
function DeployVM 
{ 

#Need to get these variables from the combo/free text boxes from form into the below

#region Starter Vars ()
$cluster = Get-Cluster $ClusterChoice.Text
$datacenter = $cluster | Get-Datacenter
$datastore = Get-Datastore $DatastoreChoice.Text
$folder = Get-Folder $FolderChoice.Text
$vmSubnet = Get-VDPortgroup -Name $NetworkChoice.Text
$NewVM = $VMNameChoice.Text
#endregion


#Spin up the vm from a content library template.
Get-ContentLibraryItem -Name $OSChoice.Text | New-VM -Name $NewVM -resourcePool $cluster -location $folder -datastore $datastore -DiskStorageFormat "Thin" -confirm:$false

#assumes a single nic, which as a template should be your standard
$NewVM | Get-NetworkAdapter | Set-NetworkAdapter -NetworkName $vmSubnet -StartConnected $true -confirm:$false

#Set CPU's
get-VM -name $NewVM | set-VM -NumCpu $CPUChoice.text
$TotalvCPU=$CPUChoice.text*$CoreBox.text
$spec=New-Object –Type VMware.Vim.VirtualMAchineConfigSpec –Property @{“NumCoresPerSocket” = $CoreBox.text}
($NewVM).ExtensionData.ReconfigVM_Task($spec)
$NewVM | set-vm -numcpu $TotalvCPU -confirm:$false

#Set Memory

set-vm $vm -MemoryGB $RAMChoice.text -confirm:$false

#Need to complete the below only if Windows OS selected (need to put an if statement in?)
set-vm $vm -OSCustomizationSpec "+ServiceWorks Windows Templates" -confirm:$false
Get-VM $NewVM
$spec = New-Object VMware.Vim.VirtualMachineConfigSpec
$spec.Firmware = [VMware.Vim.GuestOsDescriptorFirmwareType]::efi
$vm.ExtensionData.ReconfigVM($spec)

} 


[void]$CDWVMDeploy.ShowDialog()

Thanks!


Try, Catch, If, Invoke-Command and error handling

$
0
0

I'm still learning Powershell so please take it easy on me. Here is what I am trying to do, find a process called wview.exe on multiple remote computers, if wview.exe exist stop it + log it + increase counter, if it doesn't but computer is up, log it + increase counter, if we can't connect log it + increase counter. I would like to avoid having to test the connection first.

Here is a sample of what I have:

Foreach ($Computer in $Computers){    #Try to connect to the computer    Try{        $ProcessCount = Invoke-Command -ComputerName $Computer -ScriptBlock {@(Stop-Process -force -passthru -processname wview).count} -SessionOption (New-PSSessionOption -NoMachineProfile)        #If we find 1 or more wview.exe let's log it and + counters        If($ProcessCount -eq 1){            Write-Host $Computer " Processes killed: $ProcessCount"            #$Result is an array to store the result to log to a file in the full script            $Results += $Computer + " Processes killed: $ProcessCount"            #Counters to store in summary for log file            $SuccessConnectCount++            $SuccessKillCount++        }            #Else ... no wview processes found, let's log it and + counter            Else{                Write-Host $Computer ": 0 WView processes to kill"                $Results += $Computer + ": 0 WView processes to kill"                #Counter to store in summary for log file                $SuccessConnectCount++            }    }       #If we get a system error, let's catch it and log it as failed count.    Catch{        Write-Host $Computer ": Connection error"        $Results += $Computer + ": Connection error"        #Counter to store in summary for log file        $FailConnectCount++    }
}

I've tried multiple things like erroractions, catching system errors etc, however the script seems to either hit the try statement (if or else, never both) or catch statement and never all 3 (try, if, else and catch) when all 3 scenarios are present.




Replacing first Character of every word in a string with an Uppercase

$
0
0

Hi,

Is it possible to replace all first character of every word in a string with UpperCase?

$="autocad lite"

Should look "Autocad Lite" .

Thanks,

François

rename of acitve directory user account and now user cannot access skype

$
0
0

i have a user  Crystal Morin in Active directory who recently had a name change

since the name change user no longer has access to skye

iN the extended attribute of the user there is no msRTCSIP  nor is ther  the attibute msRTCPSIP-UsesrEnabled


What is the powershell command to add  msRTCSIP-PrimaryUserAddress to crystal morin

Powershell - Import-CSV filter concatenated column

$
0
0

I concatenated 3 columns of CSV file, and need to filter based on those values in those 3 columns.

I managed to concatenate these 3 columns but no idea how to filter results based on it, below returns nothing:


Import-Csv "C:\1.csv" | Select-Object  @{n=’ResourceName’;e={$_.FIRST_NAME + "," + $_.LAST_NAME + "," + $_.ADDRESS} `
| Where-Object {$_.FIRST_NAME -like "Petar" -and $_.LAST_NAME -like "Petrovic" -and $_.ADDRESS -like "Prvomajska 1"}



Remove rows from a csv file based on the values from the text file

$
0
0

Hi All,

I have a .csv file called input.csv with the following columns.

Columns:

#TYPE Selected.Microsoft.PowerShell.Commands.MatchInfo"Path","Filename","Pattern","LineNumber","Line","APPID","LastWriteTime"

with the sample values below separated by comma and with in double quotes

Sample Values:

"\\XXXXXX\d$\Apps\Archive\XXX-2015-08-14_16-08-34\Service\log4net.xml","log4net.xml","password=|pass=|passwd=|passphrase=|pwd=|psw=|\<password\>","60","              <connectionString value=""data source=SQLSVR;initial catalog=test_log4net;integrated security=false;persist security info=True;User ID=sa;Password=sa""/>","765","7/8/2015 6:03:44 PM""\\XXXXXX\d$\Support\__PACKAGE\Support\Software\PowerShell\Carbon\Service\Install-Service.ps1","Install-Service.ps1","password=|pass=|passwd=|passphrase=|pwd=|psw=|\<password\>","187","            $passwordArgName = 'password='","1310","1/28/2014 4:59:06 PM"

I have a file called exclude.txt  with the value like below which matches the column Line in input.csv

Sample Value in the exclude.txt

"            $passwordArgName = 'password='"

I have written the code below to exclude the line which contains the value in the exclude.txt and put the remaining in an output file.  But it is not working and simple returning all the values in input.csv.  Please review and me know what I a doing wrong here.

$import = @{}


$import = Get-Content C:\PC\Libaudit\input.csv
 select -Skip 1

$database = Get-Content C:\PC\Libaudit\exclude.txt
 
$import |
 where {$_ -notcontains $database} |
 Add-Content C:\PC\LibAudit\ToUpload.csv

Thanks for your help

SS

How to create CheckBox programatically by select ComboBox Item?

$
0
0

Anyone can give me idea, please... I would like to bring files to GroupBox GUI as a CheckBox format. Because the files inside of some folder, I create ComboBox to make user easy to choose which folder they need to see the files. I do some stuff here, but I still struggle to show the file. Once I execute my script, all the files appear in the GroupBox without select the folder first. My expectation, the files will show only user select the folder.

Please give me some idea, I am newbie with PowerShell,really appreciated with the help. Thank you.

ExpiryDate for groupMember

$
0
0

Hi I try to display my groupmember's expiry date 

when i try this i've got no result 

Get-ADuser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0 } –Properties "Name", "msDS-UserPasswordExpiryTimeComputed" | where {$_.memberof -eq 'Grp_Users_SSL'} | 
Select-Object -Property "Name",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}

and when i try this it tells me it can't use get-adgroupmember | get aduser ...

get-adgroupmember "Grp_Users_SSL" | Where objectClass -eq "user"| Get-ADuser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0 } –Properties "Name", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "Name",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}


how to find the .msi file executed last and it's exit code using powershell

$
0
0

how to find the .msi file executed last and it's exit code using powershell

Hi ,

I searched the forum and couldn't find what I was looking for. Please assist.

variable for multiple users pointing at AppData\Local\Microsoft\Outlook\RoamCache

$
0
0

Good evening Powershell Experts, 

I'm migrating users from outlook 2010 to Office 365 and I've been tasked to ensure their Autocomplete file will be copied across while migrating

The issue I have is with a script I'm building to copy the content of the "AppData\Local\Microsoft\Outlook\RoamCache" to a shared drive so I can then copy it back after the migration has been succesfull.

As each PC has more than one user account logged into, I'm unsure how to create the variable to point to Roamcache folder for each of them.

This is what I have managed to create so far:

$ErrorActionPreference = 'SilentlyContinue'

#Get the date
$date = get-date -format "ddMMyyyy"

#Get the path to the c:\users
$users = "C:\Users\" 

#get the users on the local pc
$localusers = (Get-ChildItem $users).Name

#Get the path to the roam cache folder
$sourcefile =($users+$localusers)+("\AppData\Local\Microsoft\Outlook\RoamCache") - this is where I have the issue

#get the path to the destination folder
$Destination = "\\server\share\home\admin.account\new folder"+$date

#copying the files across

ForEach  ($user in $sourcefile){
    If (test-path $sourcefile){  
        ForEach( $file in $sourcefile){ 
            Write-Host "Copying..."
            Copy-Item -Path $sourcefile -Destination $Destination  -Verbose
            
        }
    } 
    else {
        Write-Host "Location does not exist"

    }
}

I would really appreciate your help!

Thank you in advance

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32"

$
0
0

Hello!

I am in the process of learning PowerShell.  I am not a professional programmer, and I've had no real training in PowerShell.  I will finally be receiving training after the new year, but in the meantime I am trying to get a script working, and have hit a snag.

In our environment, we use BitLocker to encrypt the local drives on all our computers.  The drive encryption is one of the last steps of our imaging process, and the recovery key normally gets backed up into AD.  I have recently discovered that some computers have been deployed without the BitLocker recovery key getting backed up into AD.  I am trying to write a script that will build a list of all computer objects in AD, use that list to build another list of machines missing recovery the key, and output list.

First, I needed to figure out how to identify machines missing the recovery key.  Some Googling turned up that the recovery key is stored as a child object of the computer object, and is called msFVE-RecoveryInformation.  I put together a small list of machines as my test group.  PC2, PC3, PC5, and PC6 are missing the recovery key, and the remaining machines in the test group are not.  Remember, I am not a professional programmer, so this probably does not follow all the best practices that a pro would employ.  Here is what I came up with, and it works:

$Computers = @("PC1","PC2","PC3","PC4","PC5","PC6","PC7")

# Create the list.
$NullBitLocker = New-Object System.Collections.Generic.List[System.Object]

foreach ($Computer in $Computers) {
    $BitLockerKey = Get-AdObject -Filter "objectclass -eq 'msFVE-RecoveryInformation'" -SearchBase (Get-ADComputer $Computer).DistinguishedName -Properties msFVE-RecoveryPassword | Select-Object msFVE-RecoveryPassword
    If ($null -eq $BitLockerKey) { $NullBitLocker.Add($Computer) }
}

$NullBitLocker

The second task was to figure out how to get a list of machines from AD, which was fairly straight-forward.  Our printers are setup as computer objects, and the "-like '*$'" part filters out the printers.  This also works, but it would be nice to filter out some OUs, like for handheld scanners that run Windows but are not encrypted with BitLocker.

   try{
   $ou = "OU=MyOffice,DC=MyCompany,DC=com"
   $Computers = Get-ADComputer -Filter 'SamAccountName -like "*$"' -SearchBase $ou | Select Name
   }

   catch {
   $error[0].exception.message
   }

   $Computers

At this point, I figured that since both pieces of code work in isolation, all I had to do was combine the two.  So I produced this script.  Note that in the ForEach loop I changed "(Get-ADComputer $Computer)" to "(Get-ADComputer $Computers[$Computer])".

try{
  $ou = "OU=MyOffice,DC=MyCompany,DC=com"
  $Computers = Get-ADComputer -Filter 'SamAccountName -like "*$"' -SearchBase $ou | Select Name
 }

catch {
  $error[0].exception.message
 }

# Create the list.
  $NullBitLocker = New-Object System.Collections.Generic.List[System.Object]
    
 ForEach ($Computer in $Computers) {
            $BitLockerKey = Get-AdObject -Filter "objectclass -eq 'msFVE-RecoveryInformation'" -SearchBase (Get-
     ADComputer $Computers[$Computer]).DistinguishedName -Properties msFVE-RecoveryPassword | Select-Object 
    msFVE-RecoveryPassword
        If ($null -eq $BitLockerKey) { $NullBitLocker.Add($Computer) }
 }

$NullBitLocker

I figured that would work.  Instead, what I get is this:

 Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32".
 At G:\Scripts\PowerShell\BitLocker\BitLocker.ps1:22 char:9+         $BitLockerKey = Get-AdObject -Filter "objectclass -eq 'msFVE- ...+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [], RuntimeException+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException

I am stumped as to what I did wrong.  Any guidance you can offer in getting these two pieces of code combined and working will be greatly appreciated!

Also, while it is a secondary concern at this point, any tips on how to filter out certain OUs would be appreciated as well.

Thanks in advance for any help that you can offer!

--Tom




using send-mailmessage to have resulted attachment html file placed in the body of message

$
0
0
Hi. Thanks for the time. I guess the title is a bit confusing. What I am trying to is 1) export a list to an htm file and then 2) email that htm into the body of the email.  Can this be done using send-mailMessage? This is what I have below and it works as an attachment but I want to put it the attachment into the body of the email.

get-messagetrackinglog -resultsize unlimited -recipient me@domain.com -start (get-date).adddays(-1) |select messageid -unique | measure | ft count > c:\myfolder\emails.htm

Send-MailMessage -to "me@domain.com" -subject "Daily" -smtpserver smtp -from "me@domain.com" -attachment "c:\myfolder\emails.htm"

Powershell function: Unzip all files in a folder

$
0
0

I have a folder "Zipped" which contains 100s of .zip files

I want to unzip all zip-files in this folder to "\\zipped\Unzipped" folder.

It seems expand-archive cmdlet only support one file at a time.
So do you need to create an array with all filenames and then create a loop to unzip all files?

notepad $PSHOME access denied as administrator

$
0
0
I would like to edit the $PSHOME profile but I am denied access even as the administrator. I am the sole user of my consumer grade laptop and I am running PowerShell 6 with administrator permissions. I have already set execution policy to unrestricted to try and gain access but it did not work. Any and all help is appreciated.

Do you want to be acknowledged as Microsoft Windows PowerShell Guru? Submit your work to December 2019 competition!

$
0
0


What is TechNet Guru Competition?

Each month the TechNet Wiki council organizes a contest of the best articles posted that month. This is your chance to be announced as MICROSOFT TECHNOLOGY GURU OF THE MONTH!

One winner in each category will be selected each month for glory and adoration by the MSDN/TechNet Ninjas and community as a whole. Winners will be announced in dedicated blog post that will be published in Microsoft Wiki Ninjas blog, a tweet from the Wiki Ninjas Twitter account, links will be published at Microsoft TNWiki group on Facebook, and other acknowledgement from the community will follow.

Some of our biggest community voices and many MVPs have passed through these halls on their way to fame and fortune.

If you have already made a contribution in the forums or gallery or you published a nice blog, then you can simply convert it into a shared wiki article, reference the original post, and register the article for the TechNet Guru Competition. The articles must be written in December 2019 and must be in English. However, the original blog or forum content can be from beforeDecember 2019.

Come and see who is making waves in all your favorite technologies. Maybe it will be you!


Who can join the Competition?

Anyone who has basic knowledge and the desire to share the knowledge is welcome. Articles can appeal to beginners or discusse advanced topics. All you have to do is to add your article to TechNet Wiki from your own specialty category.


How can you win?

  1. Please copy/Write over your Microsoft technical solutions and revelations to TechNetWiki.
  2. Add a link to your new article on THIS WIKI COMPETITION PAGE (so we know you've contributed)
  3. (Optional but recommended) Add a link to your article at the TechNetWiki group on Facebook. The group is very active and people love to help, you can get feedback and even direct improvements in the article before the contest starts.

Do you have any question or want more information?

Feel free to ask any questions below, or Join us at the official MicrosoftTechNet Wiki groups on facebook. Read More about TechNet Guru Awards.

If you win, people will sing your praises online and your name will be raised as Guru of the Month.


PS: Above top banner came from Vimal Kalathil.

Thanks & Regards,
Kamlesh | Blog | Twitter | Posting is provided "AS IS" with no warranties, and confers no rights.


New-PSSession connection to compliance centre - Access is Denied

$
0
0

Hi, 

I am attempting to connect to the Security & Compliance centre remotely. Last week this was working a lot of the time (optimistically >50% of the time), however, as of Monday (24th September) I am only getting errors - see below.

I have checked and eliminated the following as reason this isn't working: 

  • The username and password are 100% correct
  • The account does not have MFA
  • The account has the correct authorisation roles

I cannot use the Exchange Online PowerShell Module provided by Microsoft as this has to be done remotely.

A potential I may have identified is that the redirect isn't working or is being blocked, whether this is a Microsoft thing or an internal network thing I cannot be sure as I do not know what the ps.compliance.protection.outlook <g class="gr_ gr_46 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="46" id="46">url</g> redirects to or how to connects to my domains centre. 

So my Two Questions are:

  • Has anyone ever come across this issue before and has a potential solution?
  • What are the next steps in the connection process that occur in order to connect directly to my domain? i.e. URLs (generic) and/or ports?

Code used to connect

$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $cred -Authentication Basic -AllowRedirection


Error messge received:

New-PSSession : [ps.compliance.protection.outlook.com] Connecting to remote server ps.compliance.protection.outlook.com 
failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting 
Help topic.
At line:31 char:16+ ...  $session = New-PSSession -ConfigurationName Microsoft.Exchange -Conn ...+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], 
PSRemotingTransportException+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed


Configuring the AD FS Identifier so that it matches the AD FS token issuer

$
0
0

I'm in a complete brain fart and I feel as though my eyes are going to pop out of my head troubleshooting ADFS. I am trying to set ADFS Identifier so that it matches the token issuer. If I do Get-AdfsProperties in PowerShell it works very well. The problem comes when I want to set the -Identifier to match the token issuer. Its giving a weird error. Below is my PowerShell script and results.

PS C:\Windows\system32>$adfsProperties = Get-AdfsProperties PS C:\Windows\system32>Set-AdfsProperties -Identifier $adfsProperties.IdTokenIssuer Set-AdfsProperties : Cannot validate the argument on parameter 'Identifier'. The argument is null. Provide a valid value for the argument, then try running the command again. At line: 1 cahr: 32 +Set-AdfsProperties -Identifier $adfsProperties.IdTokenIssuer + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo :InvalidData: (:) [Set-AdfsProperties], ParameterBindingException +FullyQualifiedErrorId :PositionalParameterNotFound, Microsoft.IdentityServer.Management.COmmands.SetServicePropertiesCommand

Any help please!!

Delete Outlook meeting room calendar subject for everyone except administrators

$
0
0

I am currently using the following command to hide calendar item subject for all meetings in MeetingRoom1. However, I would like to set this to false for 2 administrators so they can still see meeting title

Set-CalendarProcessing-IdentityMeetingRoom1-DeleteSubject  $true

Could you help me complete this and add exceptions to set false for 2 admins?


Output from powershell not ordered as expected

$
0
0

Hi there,

I have a powershell which will list all the SQL clusters in a domain with their corresponding nodes etc but it doesn’t output that info in the structured way I was expecting of cluster name followed by that clusters’ nodes sequentially. Any ideas how to straighten that out?

$cluster = Get-Cluster -domain xxxx.com 

$cluster | foreach-object {
        write-host "$_"
        Get-ClusterNode -Cluster $_.Name
        } 

This gives me the correct information but sequenced like:-

Cluster1
Cluster2

cluster1 node1
cluster1 node2
cluster 2 node1
cluster2 node2

Instead of the below:-

Cluster1
cluster1node1 cluster1node2

Cluster2
Cluster2node1
Cluster2node2

Many thanks for looking.

Cheers,

rob

Question marks and forwardslashes in Outlook folder names and how to use with Set-MailboxFolderPermission

$
0
0

Let's say I want to get/set permissions of a folder called "Done?" under Inbox.

Get-MailboxFolderPermission "user:\Inbox\Done?"

returns:

The operation couldn't be performed because 'user:\Inbox\Done?' couldn't be found.
    + CategoryInfo          : NotSpecified: (:) [Get-MailboxFolderPermission], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : 5E04CCC9,Microsoft.Exchange.Management.StoreTasks.GetMailboxFolderPermission

tried ` as an escape character but didn't work either. This is on PS v2, Exchange 2010

Any help will be appriciated!

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>