PowerShell Commands
46 TopicsPowershell: how to use an if condition with true false
Highlighted , how is $ True is equal to false? Same way, why does typecasting 'False' to boolean is evaluating to true? What is the right way to use if condition that can receive $True or 'True or $False or 'False' $Stat = $True if($Stat -eq 'fal'){Write-Host "if executed"}else{Write-Host "else block"} if($Stat -eq $False){Write-Host "if executed"}else{Write-Host "else block"} if($Stat -eq 'False'){Write-Host "if executed"}else{Write-Host "else block"} $Stat = 'True' if($Stat -eq 'False'){Write-Host "if executed"}else{Write-Host "else block"} if($Stat -eq 'True'){Write-Host "if executed"}else{Write-Host "else block"} if($Stat -eq $True){Write-Host "if executed"}else{Write-Host "else block"} if($Stat -eq $False){Write-Host "if executed"}else{Write-Host "else block"} $Stat = $False if($Stat){Write-Host "if executed"}else{Write-Host "else block"} $Stat = 'False' if($Stat){Write-Host "if executed"}else{Write-Host "else block"} if([bool]$Stat){Write-Host "if executed"}else{Write-Host "else block"} $dd = [bool]$Stat if($dd){Write-Host "if executed"}else{Write-Host "else block"}Solved126KViews0likes6CommentsPowershell > Output to .txt as one string
I have a powershell script that loops a fileshare and reports the properties of all the files. This part reports to a .txt file: Get-ChildItem -Recurse $source | ?{-not $_.PSIsContainer} | ForEach-Object {Audit-File $_} | Sort-Object fullname | Select FullName,CreationTime,LastWriteTime,Length,Owner | Out-File C:\filename.txt The output is something like this: FullName : C:\temp\testfile CreationTime : 30-6-2017 13:34:16 LastWriteTime : 8-9-2014 17:15:57 Length : 5752832 Owner : BLA\bla.bla Author : But I would like to have something like this: FullName,C:\temp\testfile,CreationTime,30-6-2017 13:34:16,LastWriteTime,8-9-2014 17:15:57,Length,5752832,Owner,BLA\bla.bla,Author So one line for each record. I cannot use a .csv as this cannot handle things like "é", etc.Solved104KViews0likes4CommentsDeleting meetings organized by long gone employee
A user, joe.user@contoso.com, organized some meetings in the past. He left the company 6 month ago. His mailbox is deleted since 5 month. But now his meetings should be cancelled. Environment is Office 365. MS recently announced here (https://portal.office.com/adminportal/home#/MessageCenter?id=MC106884) a Powershell command for that problem. But when I try Remove-CalendarEvents -Identity "joe.user@contoso.com" -CancelOrganizedMeetings I get the error "Object 'joe.user@contoso.com' not found in 'AMy.EURx.prod.outlook.com'". CategoryInfo: NotSpecified: (:) [Remove-CalendarEvents], ManagementObjectNotFoundException Where is my fault or what is wrong with this command?27KViews0likes2CommentsHow to run Powershell command in Loop
Hi, I am new to Powershell script and Need your help on below requirement. I am have powershell script displaying last last 3 commands and output of my powershell script. Below last 3 command lines: $FinalResource=$FinalResource1 | Where-Object{$_.ResourceType -ne $MetricType} Write-Output $FinalResource New-AzResourceLock -LockLevel CanNotDelete -LockName Delete_Lock -ResourceName $FinalResource.Name -ResourceType $FinalResource.ResourceType -ResourceGroupName xxxxxx Below is Output of my powershell script: I am getting list of resources which are not having LOCKS on Azure after that I am applying lock on each resource by using above command. Script is running fine when I am passing single resource but script is failing when I am passing all resources. How to run last command in loop by passing one by one resource so that lock command will apply on all resources. Thanks, BrahmaSolved20KViews0likes5CommentsintuneWin - adding powershell cmds to uninstall app before isntalling new
Having issues w/ superseded deployment with new app versions. Figured it might be easier to just deploy the new version and have PS run the uninstall of pre-existing first. If I want to have intunewin W32 package built I normally just point it to the setup.msi and go - works great. Any suggestions to do the following when building a W32 intunewin package run PS and uninstall existing app (I have the msiexec /x string to uninstall the app. Then once removed (if not already there just proceed) and run the setup.msi for the upgraded app I want to deploy? THanks,Solved16KViews0likes4CommentsPowerShell to update License features
Looking for a way to update the features for our E3 licensed users. Setting them initially is no problem but we have not found a way to update someone that already has an E3. So user A has an E3 but only the "SharePoint Online" feature on and we need 5 other features enabled. Any suggestions would be much appreciated! e11KViews0likes3CommentsConvert CSV to XLSX via PowerShell not working with Task scheduler
Hi, I tried to using this csv to Excel convert in one of storage Capacity reporting script. In script the storage cmd will run and generate a CSV data and I tried to put it as source for this script. It is working successfully when I manually running it. But the xlsx file is not generating when I putting this in a Windows task scheduler and running it , but storage cmd and csv file generation is happening. Could you someone help me on where is wrong. I am confused. Thanks in advance. Below is the script:- $csv = "D:\Temp\UnityScript\Logs\FS_UTIL" +".csv" #Location of the source file $xlsx = "D:\Temp\UnityScript\Logs\FS_UTIL1" +".xlsx" #Desired location of output $delimiter = "," #Specify the delimiter used in the file Remove-Item $csv Remove-Item $xlsx #EMC Storage cmd which give CSV output uemcli -d X.X.X.X -u XXX -p XXX /stor/prov/fs show -output csv -filter "Name,Health details" >> $csv # Create a new Excel workbook with one empty sheet $excel = New-Object -ComObject excel.application $workbook = $excel.Workbooks.Add(1) $worksheet = $workbook.worksheets.Item(1) # Build the QueryTables.Add command and reformat the data $TxtConnector = ("TEXT;" + $csv) $Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1")) $query = $worksheet.QueryTables.item($Connector.name) $query.TextFileOtherDelimiter = $delimiter $query.TextFileParseType = 1 $query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count $query.AdjustColumnWidth = 1 # Execute & delete the import query $query.Refresh() $query.Delete() # Save & close the Workbook as XLSX. $Workbook.SaveAs($xlsx,51) $excel.Quit()10KViews0likes2CommentsTable of Basic PowerShell Commands
The chart lists Windows PowerShell command aliases, the Windows PowerShell cmdlet name, and a description of what the command actually does. Command alias Cmdlet name Description of command % ForEach-Object Performs an operation against each item in a collection of input objects. ? Where-Object Selects objects from a collection based on their property values. ac Add-Content Appends content, such as words or data, to a file. asnp Add-PSSnapIn Adds one or more Windows PowerShell snap-ins to the current session. cat Get-Content Gets the contents of a file. cd Set-Location Sets the current working location to a specified location. chdir Set-Location Sets the current working location to a specified location. clc Clear-Content Deletes the contents of an item, but does not delete the item. clear Clear-Host Clears the display in the host program. clhy Clear-History Deletes entries from the command history. cli Clear-Item Deletes the contents of an item, but does not delete the item. clp Clear-ItemProperty Deletes the value of a property but does not delete the property. cls Clear-Host Clears the display in the host program. clv Clear-Variable Deletes the value of a variable. cnsn Connect-PSSession Reconnects to disconnected sessions compare Compare-Object Compares two sets of objects. copy Copy-Item Copies an item from one location to another. cp Copy-Item Copies an item from one location to another. cpi Copy-Item Copies an item from one location to another. cpp Copy-ItemProperty Copies a property and value from a specified location to another location. curl Invoke-WebRequest Gets content from a webpage on the Internet. cvpa Convert-Path Converts a path from a Windows PowerShell path to a Windows PowerShell provider path. dbp Disable-PSBreakpoint Disables the breakpoints in the current console. del Remove-Item Deletes files and folders. diff Compare-Object Compares two sets of objects. dir Get-ChildItem Gets the files and folders in a file system drive. dnsn Disconnect-PSSession Disconnects from a session. ebp Enable-PSBreakpoint Enables the breakpoints in the current console. echo Write-Output Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console. epal Export-Alias Exports information about currently defined aliases to a file. epcsv Export-Csv Converts objects into a series of comma-separated (CSV) strings and saves the strings in a CSV file. epsn Export-PSSession Imports commands from another session and saves them in a Windows PowerShell module. erase Remove-Item Deletes files and folders. etsn Enter-PSSession Starts an interactive session with a remote computer. exsn Exit-PSSession Ends an interactive session with a remote computer. fc Format-Custom Uses a customized view to format the output. fl Format-List Formats the output as a list of properties in which each property appears on a new line. foreach ForEach-Object Performs an operation against each item in a collection of input objects. ft Format-Table Formats the output as a table. fw Format-Wide Formats objects as a wide table that displays only one property of each object. gal Get-Alias Gets the aliases for the current session. gbp Get-PSBreakpoint Gets the breakpoints that are set in the current session. gc Get-Content Gets the contents of a file. gci Get-ChildItem Gets the files and folders in a file system drive. gcm Get-Command Gets all commands. gcs Get-PSCallStack Displays the current call stack. gdr Get-PSDrive Gets drives in the current session. ghy Get-History Gets a list of the commands entered during the current session. gi Get-Item Gets files and folders. gjb Get-Job Gets Windows PowerShell background jobs that are running in the current session. gl Get-Location Gets information about the current working location or a location stack. gm Get-Member Gets the properties and methods of objects. gmo Get-Module Gets the modules that have been imported or that can be imported into the current session. gp Get-ItemProperty Gets the properties of a specified item. gps Get-Process Gets the processes that are running on the local computer or a remote computer. group Group-Object Groups objects that contain the same value for specified properties. gsn Get-PSSession Gets the Windows PowerShell sessions on local and remote computers. gsnp Get-PSSnapIn Gets the Windows PowerShell snap-ins on the computer. gsv Get-Service Gets the services on a local or remote computer. gu Get-Unique Returns unique items from a sorted list. gv Get-Variable Gets the variables in the current console. gwmi Get-WmiObject Gets instances of Windows Management Instrumentation (WMI) classes or information about the available classes. h Get-History Gets a list of the commands entered during the current session. history Get-History Gets a list of the commands entered during the current session. icm Invoke-Command Runs commands on local and remote computers. iex Invoke-Expression Runs commands or expressions on the local computer. ihy Invoke-History Runs commands from the session history. ii Invoke-Item Performs the default action on the specified item. ipal Import-Alias Imports an alias list from a file. ipcsv Import-Csv Creates table-like custom objects from the items in a CSV file. ipmo Import-Module Adds modules to the current session. ipsn Import-PSSession Imports commands from another session into the current session. irm Invoke-RestMethod Sends an HTTP or HTTPS request to a RESTful web service. ise powershell_ise.exe Explains how to use the PowerShell_ISE.exe command-line tool. iwmi Invoke-WMIMethod Calls Windows Management Instrumentation (WMI) methods. iwr Invoke-WebRequest Gets content from a web page on the Internet. kill Stop-Process Stops one or more running processes. lp Out-Printer Sends output to a printer. ls Get-ChildItem Gets the files and folders in a file system drive. man help Displays information about Windows PowerShell commands and concepts. md mkdir Creates a new item. measure Measure-Object Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text. mi Move-Item Moves an item from one location to another. mount New-PSDrive Creates temporary and persistent mapped network drives. move Move-Item Moves an item from one location to another. mp Move-ItemProperty Moves a property from one location to another. mv Move-Item Moves an item from one location to another. nal New-Alias Creates a new alias. ndr New-PSDrive Creates temporary and persistent mapped network drives. ni New-Item Creates a new item. nmo New-Module Creates a new dynamic module that exists only in memory. npssc New-PSSessionConfigurationFile Creates a file that defines a session configuration. nsn New-PSSession Creates a persistent connection to a local or remote computer. nv New-Variable Creates a new variable. ogv Out-GridView Sends output to an interactive table in a separate window. oh Out-Host Sends output to the command line. popd Pop-Location Changes the current location to the location most recently pushed to the stack. You can pop the location from the default stack or from a stack that you create by using the Push-Location cmdlet. ps Get-Process Gets the processes that are running on the local computer or a remote computer. pushd Push-Location Adds the current location to the top of a location stack. pwd Get-Location Gets information about the current working location or a location stack. r Invoke-History Runs commands from the session history. rbp Remove-PSBreakpoint Deletes breakpoints from the current console. rcjb Receive-Job Gets the results of the Windows PowerShell background jobs in the current session. rcsn Receive-PSSession Gets results of commands in disconnected sessions. rd Remove-Item Deletes files and folders. rdr Remove-PSDrive Deletes temporary Windows PowerShell drives and disconnects mapped network drives. ren Rename-Item Renames an item in a Windows PowerShell provider namespace. ri Remove-Item Deletes files and folders. rjb Remove-Job Deletes a Windows PowerShell background job. rm Remove-Item Deletes files and folders. rmdir Remove-Item Deletes files and folders. rmo Remove-Module Removes modules from the current session. rni Rename-Item Renames an item in a Windows PowerShell provider namespace. rnp Rename-ItemProperty Renames a property of an item. rp Remove-ItemProperty Deletes the property and its value from an item. rsn Remove-PSSession Closes one or more Windows PowerShell sessions (PSSessions). rsnp Remove-PSSnapin Removes Windows PowerShell snap-ins from the current session. rujb Resume-Job Restarts a suspended job rv Remove-Variable Deletes a variable and its value. rvpa Resolve-Path Resolves the wildcard characters in a path, and displays the path contents. rwmi Remove-WMIObject Deletes an instance of an existing Windows Management Instrumentation (WMI) class. sajb Start-Job Starts a Windows PowerShell background job. sal Set-Alias Creates or changes an alias (alternate name) for a cmdlet or other command element in the current Windows PowerShell session. saps Start-Process Starts one or more processes on the local computer. sasv Start-Service Starts one or more stopped services. sbp Set-PSBreakpoint Sets a breakpoint on a line, command, or variable. sc Set-Content Replaces the contents of a file with contents that you specify. select Select-Object Selects objects or object properties. set Set-Variable Sets the value of a variable. Creates the variable if one with the requested name does not exist. shcm Show-Command Creates Windows PowerShell commands in a graphical command window. si Set-Item Changes the value of an item to the valu See the original here.8.2KViews13likes0CommentsFind all files inside directory Trees with a given name. Powershell question
I need help understanding the cmdlet behavior. Simple command Get-ChildItem I want to find all the files in directories with a given name. Example Data: c:\temp\AD\File1.txt c:\temp\AD\File2.txt c:\temp\AD\File3.txt c:\temp\AD\FileX.txt c:\temp2\AD\File1.txt c:\temp2\AD\File2.txt Set-location c:\ Get-ChildItem -Path "*\AD\*" -Include *.txt -Recurse This command will run correctly and show file1 through FileX in any part of the directory tree. Change the Set-location to C:\temp and no files displayed. Even though the AD directory exists in the tree. The problem is when I'm looking for files in a directory on the root of the Get-ChildItem -Path "*\$myDriectoryName\*" -Include *.txt -Recurse will not display anything. I can use the where-object to filter but I'm curious about the behavior. Can I write the path in a different way?Solved7KViews0likes5Commentstimeout powershell command execution
I would like to know if there is any way we can timeout PowerShell command execution after specific time interval. Already tried using start-job, wait-job & stop-job(not able to exit ssl session explained in below example). Also tried to use a timer as explained here (not able to stop the command execution) -> https://mcpmag.com/articles/2018/03/16/wait-action-function-powershell.aspx Example: I would install openssl in Windows, then try to connect to a RPC port. - openssl.exe s_client -connect localhost:135 -> this will connect to port -> ctrl+c will exit the connection. - echo "Q" | openssl.exe s_client -connect localhost:135 -> should actually exit the ssl session but it won't happen only for RPC or some specific ports. - echo "Q" | openssl.exe s_client -connect localhost:443 -> will exit the session normally as it is running webserver and the port is not RPC port. For some reason unable to exit out of the SSL session for some ports like 135. Same issue applies when i try using below method as well for port 135. ------------------------ $TcpClient = New-Object Net.Sockets.TcpClient $TcpClient.Connect("127.0.0.1", "135") $SslStream = New-Object Net.Security.SslStream($TcpClient.GetStream(),$false,({$True} -as [Net.Security.RemoteCertificateValidationCallback])) $SslStream.AuthenticateAsClient("127.0.0.1",$null,$null) ------------------------ above sslstream will exit for any other port other than 135 or some other rpc ports like 49664,49665,49667 etc. https://support.microsoft.com/en-in/help/832017/service-overview-and-network-port-requirements-for-windows -> i see some relation here with RPC ports. So my requirement is to timeout PowerShell command execution after few seconds. Thanks a lot in advance for any kind response in advance.6.3KViews0likes2Comments