Search the Community
Showing results for tags 'powershell'.
-
System administrators need to know the storage size of the drives and folders on the server. So, that they can allocate or shrink the storage of the specified drives. Being a powerful administrator tool, PowerShell can get the file, folder, and drive storage size. There is no such dedicated command in PowerShell for getting the folder size. However, with the combination of two to three commands, PowerShell users can get the folder size. Quick Outline: Get Folder Size in PowerShell Bonus Tip: Get File Size in PowerShell Bonus Tip: Get Multiple Folder Sizes in PowerShell Conclusion Get Folder Size in PowerShell The Get-ChildItem command gets items from the provided path. However, it can get the folder size with the assistance of the Measure-Object command and the -Sum parameter. The Measure-Object command calculates the number of files in a folder, the number of characters, words, and lines in a document, and the size of the object. While the -Sum parameter selects the size of the folder, file, or object from the output. This is the syntax to get the folder size in PowerShell: Get-ChildItem -Path "Folder-Path" | Measure-Object -Property Length -sum Example 1: Get Folder Size in PowerShell This instance will get the specified folder size using the Get-ChildItem command, Measure-Object command, and -Sum parameter: Get-ChildItem -Path "C:\Documents" | Measure-Object -Property Length -sum According to the above code: First, use the Get-ChildItem command and specify the folder path. Then, pipe the command to the Measure-Object command. After that assign the Length value to the -Property parameter. Lastly, use the -Sum parameter to display the folder size: Example 2: Get Specified Folder Size in Megabytes (Mb) and Gigabytes (GB) Format To get the folder size in Mbs, you need to concatenate the command that gets folder size with the Sum command and then divide it with the 1Mb value. This is how to retrieve the folder size in Mb’s: (Get-ChildItem -Path "C:\Documents" | Measure-Object -Property Length -Sum).sum / 1Mb According to the above code: Write the code to get the folder size within the round parenthesis and concatenate it with the Sum value. After that, use the forward slash and specify 1Mb to get the folder size in Mbs: Similarly, to get the folder size and display in GB’s, concatenate the command with the Sum value that gets folder size with the 1GB value: (Get-ChildItem -Path "C:\Documents" | Measure-Object -Property Length -Sum).sum / 1GB To get the folder size in GBs, specify 1GB after the forward slash: Example 3: Get Folder Size Including Subfolders in PowerShell To get the folder size along with the subfolders, you need to use the -Recurse parameter. The -Recurse parameter forces the navigator to navigate to the subfolders and include them in the folder size count. This is how you can calculate the subfolder size along with the folder size: (Get-ChildItem -Path "C:\Documents" -Recurse -ErrorAction Ignore | Measure-Object -Property Length -Sum).Sum / 1Mb According to the above code: First, use the Get-ChildItem command and specify the folder you want to get the size of using the -Path parameter. Then use the -Recurse parameter to include the subfolders in the counting folder size query. After that, provide the -ErrorAction parameter having the Ignore value assigned to it to ignore errors during this code execution. Pipe the command to the Measure-Object command and specify the Length value using the -Property parameter. Furthermore, provide the -Sum parameter to display the folder size. Lastly, enclose the whole code within the round parenthesis and concatenate it with the Sum value. Then, specify the forward slash and place the 1Mb to display the folder size in Mbs: Example 4: Get Folder Size Excluding Certain File Types To count the folder size except for the specified file types the -Exclude parameter is used. Specify the file type to the -Exclude parameter to exclude them from the total folder size. This is how you can exclude specified file types from the total folder size: (Get-ChildItem -Path "C:\Documents" -Exclude *.pdf | Measure-Object -Property Length -Sum).Sum/ 1Mb To get the folder size excluding specified file type, simply use the -Exclude parameter and provide it the file type along with the asterisk character. The asterisk will select all the files related to that file type: Example 5: Get File Size of a Certain Type in PowerShell To get only the size of certain file types from the folder, the -Filter parameter is used. The specified file types are specified to the -Filter parameter and then their size gets calculated and displayed in the console. This demonstration gets the file size of a certain type: (Get-ChildItem -Path "C:\Documents" -Filter *.pdf | Measure-Object -Property Length -Sum).Sum/ 1Mb Bonus Tip: Get File Size Using Get-ChildItem in PowerShell The method to get the size of the file is the same as for getting the folder size in PowerShell. The only difference is that you need to provide the file path to the -Path parameter instead of the folder path. This demonstration can get the file size: Get-ChildItem -Path "C:\Documents\File.pdf" | Measure-Object -Property Length -sum To get the file size in PowerShell, simply specify the file path to the -Path parameter: Bonus Tip: Get Multiple Folder Sizes in PowerShell To get the size of more than one folder, specify the folder’s path to the -Path parameter separated by commas. Here is the demonstration to get the multiple folder size in PowerShell: (Get-ChildItem -Path "C:\Documents", "C:\Docs" | Measure-Object -Property Length -sum).Sum /1Mb To get the folder size of multiple folders, simply specify the path of the folders to the -Path parameter: Multiple folder sizes have been retrieved successfully. Conclusion To get the folder size in PowerShell, specify the folder path to the Get-ChildItem and pipe it to the Measure-Object command. Where specify the Length value to the -Property parameter and then provide the -Sum parameter to select and display the folder size in the console. I have provided various examples to get the folder size in PowerShell in this article. View the full article
-
FTP or File Transfer Protocol that transfers the files from a client to a remote host. Genuinely, its core purpose is to transfer files between devices on a computer network running FTP server service. Quick Outline: PowerShell FTP Commands FTP Append Cd Delete Mdelete Send Get Mget Rename Open Close Mkdir Conclusion PowerShell FTP Commands PowerShell allows its users to access the FTP protocol. PowerShell automates the file transfers and quickens file transfers using scripts. FTP has a bunch of other commands for the file transfer management tasks. The FTP commands are available to the computers with TCP/IP protocol installed as a component. 1. FTP The FTP command with the use of FTP protocol transfers the files from a local host to the remote host. Generally, it is an exchange of files where it sends and receives files on a computer running an FTP server service. Example: This example will log on to the specified FTP server: Ftp <ftp.linuxhint.server.com> To log on to the server, first, place the FTP command and specify the server address. 2. Append The Append command appends the text to an existing local file. It appends the text from the local computer file to the file located on the remote server. Example: This example will append the first file to file two on the remote server: Append <textfile1.txt> <textfil2.txt> To append the text file on the remote server: First, place the append command. Then, specify the file you want to append to another file. After that, specify the file to be appended. 3. Cd The CD command navigates to the specified directory. To navigate to any directory on the remote server, simply the directory to the CD command. Example: This example will change the current directory to the specified directory: Cd <Where-Directory-will-be-changed> To navigate to the desired directory, first, place the CD command and then specify the path you want to navigate. 4. Delete The Delete command deletes a single file on a remote FTP server. Example: This example will delete the specified file from the remote server: Delete <testfile.txt> To delete a file from the remote server, specify the file to be deleted to the delete command. 5. Mdelete The Mdelete command deletes more than one file at once on a remote server. Example: This example will delete multiple from the remote computer: Mdelete <file1.txt> <file2.txt> To delete multiple files from the remote computer, simply specify more than two files to the mdelete command. 6. Send The Send command sends individual or lists of files from one computer to another remote computer using FTP protocol. Example: This example will send the specified files to the remote server: Send <testfile1.txt> <testfile2.txt> To send files to the remote server, simply specify the files to the send command. 7. Get The Get command gets a single file from a remote computer using the FTP protocol. Example: This example will retrieve the specified file from the remote server: Get <testfile.txt> To get the file from the remote server, specify that file to the Get command. 8. Mget The Mget command gets multiple files from a remote computer using FTP protocol. Example: This example will get multiple files on the remote server: Mget <file1.exe> <file2.exe> Specify the files to the Mget command to get them on the remote server. 9. Rename The Rename command renames a file on a remote computer using the FTP protocol. Example: This example will rename the file on the remote server: Rename <OldFileName.txt> <NewFileName.txt> According to the above code: First, specify the Rename command. Then, specify the existing file along with the file extension. After that specify the new file name. 10. Open The Open command lets you connect to the provided FTP server. It opens the specified FTP address on the remote server. Example: This example will open the specified server address on the remote computer: Open <ftp.server.com> To open the server on the remote computer, simply specify the server address to the Open command. 11. Close The Close command closes the FTP session on the remote server. However, the prompt remains at the ftp> prompt. Example: This example closes the current FTP session on the remote computer: Close 12. Mkdir The Mkdir command creates a folder on the remote computer using the FTP protocol. Example: This example will create a new directory on the remote computer: Mkdir <Directory-to-be-Created> To create a directory on the remote computer, specify the directory to the Mkdir command. Conclusion PowerShell enables its users to interact with the FTP server. Users with TCP/IP protocol installed on their computers can have access to the FTP commands. PowerShell has a dedicated set of commands to manage the FTP protocol operations on a server. The most commonly used FTP commands include Ftp, Append, Delete, Send, Get, Rename, and Mkdir. View the full article
-
In PowerShell, a property is a class member containing data. A property is the characteristic of an object. An object can have multiple properties such as Name, Mode, or Length. Every object has almost similar properties. However, these properties have a different set of values. Such as the LastAccessTime property value of two items can always be different. Quick Outline: What are the Get Property Commands in PowerShell Get-Member Select-Object Get-Item Get-ItemProperty Get-ChildItem Summary What are the Get Property Commands in PowerShell? The Get Property commands refer to the PowerShell commands list that get the properties of the specified file, item, or object. Get Property commands get the properties of the specified item. These commands include Get-Member, Get-Item, Get-ItemProperty, Select-Object, and Get-ChildItem. 1. Get-Member – Gets the Properties of an Item The Get-Member command gets the properties of an item or object. It gets the specified object’s members, methods, and properties. The object is specified to it using the InputObject parameter or by piping the object to it. However, to get the object’s properties use the -MemberType parameter and specify the Property value. Syntax Here is the syntax of the PowerShell’s Get-Member command: [Command/Directory] | Get-Member -property [Property Value] Example 1: This example will get the properties and not the methods of the given object using Get-Member cmdlet: Get-Process | Get-Member -MemberType Property According to the above code: First, specify the Get-Process command or any other desired command. Then, pipe it to the Get-Member command. After that, use the -MemberType parameter and specify the Property value to get only the properties of an item: Example 2: This demonstration will get the properties of the specified command using the Get-Member cmdlet and Where condition: Get-Process | Get-Member | where{$_.MemberType -eq "Property"} According to the above code: First, the Get-Process command is placed and piped to the Get-Member cmdlet. Then, the Get-Member cmdlet is piped to the Where condition. In the Where condition, the MemberType property is selected which will find values that are equal to the Property instance: 2. Select-Object – Selects Objects or Objects Properties The Select-Object command selects the objects or properties of an object. It can select a specified number of objects, such as the first five items from the index using the -First parameter and the last five using the -Last parameter. Syntax This is the syntax of the Select-Object command: [Command/Object] | Select-Object -Property Property1, Property2, Property3 Example: This example will select the specified properties of an object using the Select-Object command: Get-Command | Select-Object -Property Name, Version, Source According to the above code: First, specify the Get-Command cmdlet and then pipe it to the Select-Object command. After that, use the -Property parameter and specify the properties to select and display: 3. Get-Item – Gets Items from the Given Path The Get-Item command gets the items from the provided location. It gets the properties for one item at a time. Get-Item commands do not get the content of the specified item, unlike the Get-Content command. But, it lists down the item’s properties such as its name, mode, or length. Syntax Here is the syntax of the PowerShell’s Get-Item command: Get-Item -path [Folder Address] Example: This example will get the item from the provided location and will also provide its properties: Get-Item -path C:\Documents\NewFile.txt In accordance with the mentioned command: First, specify the Get-Item command. Then, use the -Path parameter and assign it the item’s path: 4. Get-ItemProperty – Gets Properties of the Specified Item The Get-ItemProperty command gets the properties of the specified item. It gets properties like LastWriteTime, Length, and Mode of the specified item. Syntax Here is the syntax of the PowerShell’s Get-ItemProperty command: Get-ItemProperty -path [Item Address] Example: This example gets the properties of a single specified item using the Get-ItemProperty command: Get-ItemProperty -path C:\Documents\NewFile.txt According to the above code: First, specify the Get-ItemProperty command. After that, specify the file path using the -path parameter: 5. Get-ChildItem – Gets Child Item Properties from Sub Folders The Get-ChildItem command gets the items and child items from the specified locations. The subfolders or files are known as child items. It gets the properties of items like Name, Mode, Length, and LastWriteTime. Syntax Here is the syntax of the PowerShell’s Get-ChildItem command: Get-ChildItem -path [Folder Address] Example: This example not only gets the child items from the specified location but displays the properties of items: Get-ChildItem -path C:\Documents\Files According to the above code: First, mention the Get-ChildItem command. Then, the folder path is specified to the Get-ChildItem command using the -path parameter: Summary A property is a piece of information that describes the object. PowerShell Get Property commands are the commands that get the properties of an item, file, folder, or object. These commands include Get-Member, Get-Item, Get-ItemProperty, Select-Object, and Get-ChildItem. Each command either gets the properties of a file or an object. View the full article
-
powershell 11 Basic PowerShell Office 365 Commands
Linux Hint posted a topic in Development & Programming
Office 365 is a productivity application suite. It comprises apps such as Word, PowerPoint, or Excel. It is available on all devices. It has two versions, Personal and Home. The Personal version is designed for single users while the Home version is designed for more than one family member. Quick Outline: PowerShell Office 365 Commands Get-MsolUser New-MsolUser Set-MsolUserPassword Remove-SPOUser Get-MsolGroup Add-MsolGroupMember Remove-MsoLGroupMember Connect-MsolService New-SPOSite Get-Mailbox Get-Command Conclusion PowerShell Office 365 Commands PowerShell has a dedicated set of Office 365 commands. These commands help manage the Office 365 operations. 1. Get-MsolUser The Get-MsolUser command gets an individual or list of users from the Azure Active Directory. Individual users can be retrieved by specifying the user by its ObjectID or UserPrincipalName parameter. Example: This example will get the list of all Office 365 users: Get-MsolUser * To get all the users from Azure Active Directory, first, use the Get-MsolUser command and specify the asterisk (*). 2. New-MsolUser The New-MsolUser command creates a new user account in the Active Directory domain. It is a part of the Azure Active Directory module. Example: This example will create a new user in Azure Active Directory: New-MsolUser -UserPrincipalName "UserPrincipalName" -DisplayName "John Doe" -FirstName "John" -LastName "Doe" To create a new user in the Azure Active Directory: First, place the New-MsolUser Then, specify the principal username to the -UserPrincipalName After that, specify the display name to the -DisplayName parameter, first name to the -FirstName parameter, and last name to the -LastName 3. Set-MsolUserPassword The Set-MsolUserPassword command resets the Office 365 user password. This cmdlet can only be implemented for those users who have standard identities. Example: This example will reset the Office 365 user account password: Set-MsolUserPassword -UserPrincipalName "UserPrincipalName" -NewPassword "NewPassword" To reset the password of the Office 365 user account: First, place the Set-MsolUserPassword command and specify the user principal name to the -UserPrincipalName Then, specify the new password to the -NewPassword 4. Remove-SPOUser It removes a user account from a SharePoint site collection. For instance, it can remove a specific user or all users at once from a group. Example: This example will remove a user from all SharePoint sites: Get-SPOSite | ForEach {Remove-SPOUser -Site $_.Url -LoginName "LoginNameOrEmail"} To remove a user from all SharePoint sites: First, place the Get-SPOSite command and pipe it to the ForEach commands query. In the ForEach command query, first, place the Remove-SPOUser command and then provide the site URL using the -Site After that, provide the login name or email to the -LoginName 5. Get-MsolGroup The Get-MsolGroup command gets an individual or list of groups from the Azure Active Directory. It gets the details of the groups in Azure Active Directory. It outputs details such as display name, objectID, and description. Example: This example will get all the groups in Azure Active Directory: Get-MsolGroup 6. Add-MsolGroupMember The Add-MsolGroupMember command adds a member or group as a member to an existing security group or a site collection. Example: This example will add a new member to an existing group: Add-MsolGroupMember -GroupObjectId "Group-Object-ID" -GroupMemberObjectId "Group-Member-Object-Id" -GroupMembertype "User" To add a member to the group: First, place the Add-MsolGroupMember command and provide the group object ID to the -GroupObjectId Then, provide the group member object ID to the -GroupMemberObjectId parameter, and the member type to the -GroupMembertype 7. Remove-MsoLGroupMember The Remove-MsoLGroupMember removes a member from an existing security group or a site collection. Example: This example will remove a user from a group: $Group-ID = Get-MsolGroup -SearchString "Group-Member-Name" First, create a variable, get the specified group and store it to the variable: $User-ID = Get-MsolUser -UserPrincipalName "User-Principal-Name" Create another variable, get the specified user and store it to the variable: Remove-MsoLGroupMember -GroupObjectId $Group-ID -GroupMemberType User -GroupMemberObjectId $User-ID Lastly, use the Remove-MsoLGroupMember command. Then, specify the variable that has stored the group value. After that, specify the user type to the -GroupMemberType parameter and assign the variable that stored the user details to the -GroupMemberObjectId parameter. 8. Connect-MsolService The Connect-MsolService command creates or initiates a connection with the Azure Active Directory. Example: This example will connect to the Office services: Connect-MsolService –Credential <Office-365-Instance-Credentials> To create a connection with the Office 365 services: First, place the Connect-MsolService Then, specify the credentials using the -Credential 9. New-SPOSite The New-SPOSite command creates a SharePoint site collection list for the existing company. In case the deleted sites collection exists in the recycle bin then the creation of the SharePoint site collection will fail. Example: This example will create a SharePoint site collection list: New-SPOSite -Url "SharePoint-Site-URL" -Owner "Owner-Email" -StorageQuota "2000" -Title "Title-Of-Presentation" To create a new SharePoint sites collection: First, place the New-SPOSite command and specify the SharePoint site URL to the -URL Then, specify the owner email using the -Owner parameter, and specify the storage quota using the -StorageQuota Lastly, provide the title for the site collection to the -Title 10. Get-Mailbox The Get-mailbox command gets the MailBox objects, such as quota settings, or email addresses. Example 1: This example will retrieve all mailbox reports: Get-Mailbox | Get-MailboxStatistics To get all mailbox reports, first, use the Get-Mailbox command and pipe it to the Get-MailboxStatistics command. Example 2: This example will get the complete mailbox details associated with the specified email address: Get-Mailbox email-address To get the mailbox details, simply provide the email address to the Get-Mailbox command. 11. Get-Command The Get-Command command gets the list of cmdlets associated with the specified module. For instance, it can get the Office 365 commands associated with the MSOnline module. Example 1: This example will get the commands associated with the MSOnline module: Get-Command -Module MSOnline To get the MSOnline commands: First, specify the Get-Command Then, specify the MSOnline module to the -Module Example 2: This example will get the commands associated with the AzureAD module: Get-Command -Module AzureAD Similarly, to get the AzureAD commands: First, specify the Get-Command Then, specify the AzureAD module to the -Module Conclusion Office 365 consists of productivity apps, such as Word, PowerPoint, or Outlook. Microsoft Office 365 can be managed via PowerShell. PowerShell has a set of dedicated commands to manage Office 365 operations. The most commonly used Office 365 commands include Get-MsolUser, New-MsolUser, Set-MsolUserPassword, or Remove-SPOUser. View the full article -
Task Scheduler application is used to create, run, and manage tasks. It schedules tasks such as launching programs, files, or scripts. These tasks are then scheduled to be launched at a particular time. Additionally, PowerShell and Command Prompt can mimic its functionality too. Microsoft has empowered both PowerShell and Command Prompt to perform the tasks that a normal GUI-based user can’t. The most important feature of the Task Scheduler is its ability to import and export scheduled tasks. Importing and exporting the tasks feature is very useful when it comes to moving scheduled tasks from one computer to another. The benefit of the exported or imported tasks is that they can be used on multiple computers. In case your Task Scheduler application is not working or you are unable to use it then, PowerShell can be used to import and export scheduled tasks. Quick Outline: How to Import and Export Scheduled Tasks Using PowerShell Bonus Tip: How to Import and Export Scheduled Tasks Using Command Prompt (CMD) Conclusion How to Import and Export Scheduled Tasks Using PowerShell? As discussed earlier, tasks in Windows can be imported and exported using Task Scheduler, PowerShell, and Command Prompt. But, in this article, we will focus on importing and exporting tasks using PowerShell. Tasks that are imported or exported are saved with the XML (Extensible Markup Language) file extension. Import Scheduled Tasks Using PowerShell Importing scheduled tasks means, injecting scheduled tasks within the Task Scheduler program that were already exported in the form of an XML file. Alongside the Task Scheduler application, PowerShell can also be used to import scheduled tasks. Importing scheduled tasks is a priority task that needs the administrator’s permission. To import scheduled tasks using PowerShell check the instructions provided below. Syntax Here is the syntax to import scheduled tasks using PowerShell: Register-ScheduledTask -xml (Get-Content "Task-Path-to-be-Imported" | Out-String) -TaskName "Task-Name" -TaskPath "Task-Path-TaskScheduler" -User Computer-User-Name –Force According to the above code: First, let’s register a scheduled task using the Register-ScheduledTask Then, use the -xml parameter and assign the Get-Content command to get the scheduled task XML file and pipe it to the Out-String command to convert it to the strings. After that, use the -TaskName parameter to assign the scheduled task name. Use the -TaskPath to specify the path of the task. Use the -User parameter to assign the user’s computer name from which the task will be imported. Lastly, use the -Force parameter to overwrite the import if there exists any with that name already. Note: Replace “Task-Path-to-be-Imported” with the real task path, “Task-Name” with the real task name, “Task-Path-TaskScheduler” with the real Task Scheduler’s path, and finally, add your username to the -User parameter. Step 1: Hit the Windows button to open the Start menu: Step 2: Search PowerShell and click Run as administrator: Step 3: Type the given command and press Enter to import the scheduled tasks: Register-ScheduledTask -xml (Get-Content "C:\Users\Muhammad Farhan\Documents\Sample task.xml" | Out-String) -TaskName "Sample task" -TaskPath "" -User "Muhammad Farhan" –Force Export Scheduled Tasks Using PowerShell Exporting a task means that already scheduled tasks can be exported to an XML file. These scheduled tasks can also be exported using PowerShell. For that purpose, Microsoft has a dedicated command Export-ScheduledTask. To export scheduled tasks using PowerShell check the steps mentioned below. Syntax Here is the syntax for exporting a task using PowerShell: Export-ScheduledTask -TaskName "Task-Name" -TaskPath "Task-Path-Where-it-is-Located" | Out-File "Path-Where-Task-Will-be-Exported" According to the above code: First, use the Export-ScheduledTask command to initiate the exporting process of the scheduled task. Then, use the -TaskName parameter and assign the task name and use the -TaskPath parameter to assign the scheduled task path. After that pipe or export that information to another path using the Out-File Note: Replace “Task-Name” with the real task name, “Task-Path-Where-it-is-Located” with the real location of the task, and “Path-Where-Task-Will-be-Exported” with the targeted file path where the scheduled tasks will be exported. Step 1: Press Windows + X to open the Quick Access Menu, and select Windows PowerShell (Admin) or Terminal (Admin): Step 2: Execute the below code in the console to export scheduled tasks: Export-ScheduledTask -TaskName "Sample task" -TaskPath "" | Out-File "C:\Users\Muhammad Farhan\Documents\Sample task.xml" Bonus Tip: How to Import and Export Scheduled Tasks Using Command Prompt (CMD)? Just like PowerShell, Command Prompt can also import and export scheduled tasks with the help of certain commands. Command Prompt has its own dedicated commands for importing and exporting tasks. Import Scheduled Tasks Using Command Prompt (CMD) Importing scheduled tasks from an XML file to the computer can be done by using the Command Prompt. Syntax Here is the syntax for importing scheduled tasks using CMD: schtasks /create /xml "Task-Path.xml" /tn "Task-Name" /ru "Computer-Username" According to the above code: First, use the SCHTASKS /Create /xml command to create a new xml task. Then specify the XML file path. After that use /tn to assign the task name. Lastly, use the /ru to assign the user name of the computer. Remember: Replace “Task-Path.xml” with the real task, “Task-Name” with the real task name, and “Computer-Username” with your computer’s username. Step 1: Press Windows + R to launch the Run application. Step 2: Type CMD and press Ctrl + Shift + Enter to open PowerShell as an administrator: Step 3: Type the mentioned command in the console to import the scheduled tasks: schtasks /create /xml "C:\Users\Muhammad Farhan\Documents\Sample task.xml" /tn "\NewSampleTask" /ru "Muhammad Farhan" Executing the above command will ask user’s password, so, enter the password when asked to complete the operation: Export Scheduled Tasks Using Command Prompt (CMD) Alongside importing scheduled tasks can be exported to an XML file using Command Prompt. To export the scheduled tasks using CMD, check the mentioned steps. Syntax Here is the syntax for exporting scheduled tasks using PowerShell: schtasks /query /xml /tn "Scheduled-Task-Name" > "TASK-EXPORT-NAME.xml" According to the above code: First, use the schtasks /query /xml command to display one or more scheduled tasks in XML format. Then, use the /tn command to specify the task name. After that, use the > (greater than) sign and assign the targeted file path where the scheduled task will be exported. Remember: Replace “Scheduled-Task-Name” with the scheduled task name, and “TASK-EXPORT-NAME.xml” with the targeted file path where you want to export the scheduled task. Step 1: Open CMD as an administrator: Step 2: Execute the given code in the PowerShell console: schtasks /query /xml /tn "\NewSampleTask" > "C:\Users\Muhammad Farhan\Documents\Sample task.xml" Conclusion To import the scheduled tasks using PowerShell, first, press Windows + X to open the Quick Start Menu and select Windows PowerShell (Admin). Type Register-ScheduledTask -xml (Get-Content “Task-Path-to-be-Imported” | Out-String) -TaskName “Task-Name” -TaskPath “Task-Path-TaskScheduler” -User Computer-User-Name -Force command. Make sure to update these parameters “Task-Path-to-be-Imported”, “Task-Name”, and “Task-Path-TaskScheduler” before executing this command. To export the scheduled tasks using PowerShell, execute this Export-ScheduledTask -TaskName “Task-Name” -TaskPath “Task-Path-Where-it-is-Located” | Out-File “Path-Where-Task-Will-be-Exported” command. Make sure to update the “Task-Name”, “Task-Path-Where-it-is-Located”, and “Path-Where-Task-Will-be-Exported” parameter values before executing this command. Additionally, the method to import and export schedules using the Command Prompt. View the full article
-
What is PowerShell? What is PowerShell PowerShell is a task automation framework and scripting language elaborated by Microsoft. It is designed for system administrators and power users to automate administrative tasks, manage configurations, and interact with various Microsoft products and services. PowerShell provides a command-line interface (CLI) and a scripting environment, allowing users to write scripts that automate tasks using cmdlets (pronounced “command-lets”). Key Features of PowerShell: Cmdlets: Cmdlets are small, single-function commands in PowerShell that perform specific tasks. They follow a verb-noun naming convention (e.g., Get-Process, New-Item) and can be combined to create powerful scripts. Pipeline: PowerShell supports pipelining, allowing the output of one cmdlet to be used as the input for another. This enables the creation of complex and efficient command sequences. Scripting Language: PowerShell is a scripting language with variables, loops, conditional statements, and other programming constructs, making it more versatile than traditional command-line interfaces. Object-Oriented: PowerShell deals with objects rather than text, making it more powerful for managing and manipulating data. Objects can be passed through the pipeline, allowing structured data handling. Remote Management: PowerShell allows administrators to manage remote systems, execute commands on remote machines, and access remote resources using technologies like WS-Management and PowerShell Remoting. Integration with .NET: PowerShell is built on the .NET Framework, providing access to the vast capabilities of the .NET libraries. This allows users to leverage .NET classes and methods in their scripts. Automation and Scripting: PowerShell is designed for automation and scripting tasks. It is particularly useful for automating repetitive administrative tasks, managing configurations, and orchestrating workflows. What is top use cases of PowerShell? Top Use Cases of PowerShell: System Administration: PowerShell is extensively used for system administration tasks, such as managing users, groups, and permissions, configuring network settings, and performing system maintenance. Active Directory Management: PowerShell is a powerful tool for managing and automating tasks in Active Directory, including user and group management, password resets, and organizational unit (OU) management. Server Management: Administrators use PowerShell to manage Windows Server environments, including tasks like configuring server roles and features, monitoring system performance, and automating maintenance tasks. Configuration Management: PowerShell Desired State Configuration (DSC) is a feature that allows administrators to declare the desired state of a system. DSC scripts can be used to automate configuration management and ensure consistent system configurations. Task Automation: PowerShell is widely used for automating repetitive tasks, such as file and folder management, log analysis, and scheduled tasks. Azure Cloud Management: PowerShell is a key tool for managing and automating tasks in Microsoft Azure. It allows users to create and manage Azure resources, deploy applications, and configure virtual machines in the cloud. Exchange Server Administration: Administrators use PowerShell for managing and automating tasks related to Microsoft Exchange Server, including mailbox management, mail flow configuration, and server maintenance. SQL Server Administration: PowerShell can be used to automate tasks related to Microsoft SQL Server, such as database backups, restores, and data migration. Security Operations: PowerShell is employed in security operations for tasks like log analysis, incident response, and malware detection. However, it’s important to note that PowerShell scripts can also be used by malicious actors, and security measures should be implemented to mitigate risks. Development and Build Processes: PowerShell is used in development workflows for tasks such as managing version control systems, building and deploying applications, and automating testing processes. PowerShell’s versatility and integration with Microsoft technologies make it a powerful tool for administrators and developers working in Windows environments. Its scripting capabilities and automation features contribute to increased efficiency and consistency in managing and maintaining systems. What are feature of PowerShell? Features of PowerShell PowerShell is a robust scripting language and automation framework with several features that make it powerful for system administration and automation tasks: Cmdlets (Commandlets): PowerShell consists of a rich set of cmdlets, which are small, task-specific commands that perform specific functions. Cmdlets follow a verb-noun naming convention and can be combined for more complex operations. Pipeline: PowerShell supports pipelining, allowing the output of one cmdlet to be passed as input to another. This facilitates the creation of efficient and concise command sequences. Scripting Language: PowerShell is a full-fledged scripting language with features such as variables, loops, conditional statements, functions, and error handling. This makes it suitable for writing scripts and automation workflows. Object-Oriented: PowerShell behaves data as objects rather than plain text. Cmdlets produce and consume objects, enabling structured data manipulation and processing. Integration with .NET: PowerShell is built on the .NET Framework, providing seamless integration with .NET libraries. This enables access to a wide range of functionalities available in the .NET ecosystem. Remote Management: PowerShell supports remote management, allowing administrators to execute commands on remote systems. This is achieved through technologies like WS-Management and PowerShell Remoting. Script Execution Policy: PowerShell includes a script execution policy that determines the level of security for running scripts. Policies can be set to allow or restrict script execution based on the source and type of script. PowerShell Desired State Configuration (DSC): PowerShell DSC is a configuration management platform that allows administrators to declare and enforce the desired state of a system. It is used for configuration drift prevention and ensuring consistent system configurations. Error Handling and Logging: PowerShell provides mechanisms for error handling, including try-catch-finally blocks, and supports logging and output redirection. Dynamic Typing: PowerShell uses dynamic typing, allowing variables to automatically adapt to the type of data assigned to them. This simplifies scripting and makes it more flexible. Help System: PowerShell includes a comprehensive help system that provides information about cmdlets, functions, and concepts. Users can access detailed help documentation directly from the console. Environmental Variables: PowerShell supports environmental variables that can be used to store and retrieve information about the environment in which scripts are running. What is the workflow of PowerShell? Workflow of PowerShell: The workflow of PowerShell varies based on the tasks at hand, but here’s a general workflow for using PowerShell: Launch PowerShell: Open the PowerShell console or PowerShell Integrated Scripting Environment (ISE) on a Windows machine. Cmdlet Execution: Use built-in or custom cmdlets to perform specific tasks. Cmdlets can be executed individually or combined in a pipeline for more complex operations. Scripting: Write PowerShell scripts using a text editor or PowerShell ISE to automate tasks, perform system configurations, or execute a series of commands. Variable Usage: Utilize variables to store and manage data within scripts. PowerShell supports dynamic typing, making variable usage more flexible. Conditional Statements and Loops: Employ conditional statements (if-else) and loops (for, foreach, while) for decision-making and repetitive tasks within scripts. Error Handling: Implement error handling using try-catch-finally blocks to gracefully manage exceptions and errors that may occur during script execution. Remote Management: Use PowerShell Remoting or other remote management features to execute commands on remote systems. DSC Configuration: Leverage PowerShell Desired State Configuration (DSC) to declare and enforce the desired state of systems, ensuring consistency in configurations. Script Execution Policy: Set and manage the script execution policy to control the security level for running scripts. Output and Logging: Capture and process output, and log relevant information for auditing and troubleshooting purposes. Testing and Debugging: Test scripts in a controlled environment and use debugging features to identify and resolve issues. Automation and Scheduled Tasks: Automate repetitive tasks and schedule scripts using Task Scheduler or other automation tools. Documentation and Help: Document scripts, use comments, and provide help information to make scripts understandable and maintainable. Continuous Improvement: Continuously refine and improve scripts based on evolving requirements and feedback. PowerShell’s workflow is flexible, allowing users to interactively execute commands, write scripts for automation, and manage systems efficiently. Its scripting capabilities make it a powerful tool for system administrators, IT professionals, and developers working in Windows environments. How PowerShell Works & Architecture? PowerShell Works & Architecture PowerShell is a scripting language and automation tool developed by Microsoft. It allows users to manage and automate various tasks on Windows and other platforms. Here’s a breakdown of how it works and its architecture: 1. Core Components: Host: Responsible for executing PowerShell commands and providing access to underlying resources. Engine: Interprets and executes PowerShell scripts. Modules: Packages containing commands, functions, and variables for specific tasks. Runspace: A separate execution environment for each script to ensure isolation and prevent conflicts. 2. Execution Model: Interactive Mode: Allows users to enter and execute commands directly in the console. Scripting Mode: Used for running scripts containing multiple commands and control flow statements. Remote Execution: Executes commands on other computers with PowerShell installed. 3. Cmdlets: Fundamental building blocks of PowerShell. Represent specific actions or tasks. Follow a verb-noun naming convention (e.g., Get-Process, Set-Service). Accept parameters to customize their behavior. 4. Pipeline: Enables chaining commands together to process data in a sequence. Output of one command becomes the input for the next. Supports various operators for filtering, sorting, and manipulating data. 5. Objects and Types: PowerShell works with objects representing real-world entities like processes, files, and services. Objects have properties and methods that can be accessed and manipulated. PowerShell supports strong typing for increased accuracy and flexibility. 6. Remoting: PowerShell can manage remote computers using the WinRM (Windows Remote Management) protocol. Provides secure and efficient way to execute commands and transfer data. Enables managing multiple computers from a single location. 7. Scripting Features: Supports various control flow statements like loops and conditionals. Enables functions to encapsulate reusable code. Provides error handling mechanisms for robust scripts. Integrates with other scripting languages and tools. Benefits of PowerShell Architecture: Modular and extensible: Modules allow for easy addition of new functionalities. Object-oriented: Enables working with data in a structured and efficient way. Powerful scripting language: Supports complex tasks and automation scenarios. Remote management capabilities: Allows for managing multiple systems from a single location. Understanding PowerShell’s architecture helps users write efficient scripts, leverage its full potential, and manage systems effectively. How to Install and Configure PowerShell? Installing PowerShell: On Windows: Pre-installed: PowerShell comes pre-installed on most modern Windows versions (Windows 7 and later). Windows PowerShell: For older versions or specific needs, you can download and install the standalone Windows PowerShell version from the Microsoft website PowerShell Core: For cross-platform compatibility, you can install PowerShell Core On Linux and macOS: Package Manager: Install PowerShell Core using the respective package manager for your Linux distribution or macOS version. Direct Download: Download the appropriate installer package from the PowerShell website Configuring PowerShell: Execution Policies: Set the execution policy to allow running scripts from trusted sources. Use Set-ExecutionPolicy cmdlet with appropriate parameter (e.g., RemoteSigned). Modules: Install additional modules for specific tasks using the Install-Module cmdlet. Discover available modules on the PowerShell Gallery Profiles: Modify profiles to customize the PowerShell environment for different users. Profiles are located in user and system directories. Remoting: Configure WinRM service on remote systems to enable remote management. Use Enter-PSSession cmdlet to connect and manage remote computers. Fundamental Tutorials of PowerShell: Getting started Step by Step Fundamental Tutorials of PowerShell Following is a Step-by-Step Fundamental Tutorials of PowerShell: 1. Introduction to PowerShell: What is PowerShell? Understand the purpose and functionalities of PowerShell as a scripting language and automation tool. Benefits of PowerShell: Explore the advantages of using PowerShell, such as its automation capabilities, object-oriented approach, and extensive community support. Launching PowerShell: Learn how to launch the PowerShell console on your system. 2. Basic Commands: Get-Command: Discover available cmdlets and their functions. Get-Help: Get detailed information and usage examples for specific cmdlets. Get-Process: List running processes on your system. Get-Service: Manage and monitor services. Get-ChildItem: Explore directories and files. 3. Working with Objects: Understanding object structure: Explore properties and methods of objects returned by cmdlets. Filtering objects: Use the Where-Object cmdlet to filter objects based on specific criteria. Sorting objects: Use the Sort-Object cmdlet to sort objects based on specific properties. Formatting output: Use the Format-Table cmdlet to format object output for better readability. 4. Variables and Data Types: Declare and assign values to variables. Understand different data types like strings, numbers, and booleans. Apply variables to store and manipulate data within your scripts. 5. Control Flow: Use If statements to make decisions based on conditions. Use loops (For and While) to iterate through sequences of data. Use switch statements to handle multiple conditions with specific cases. 6. Functions: Create and call custom functions to encapsulate reusable code. Pass parameters to functions to customize their behavior. Use functions to improve script modularity and organization. 7. Scripting Basics: Write simple scripts to automate repetitive tasks. Use comments to document your scripts and improve readability. Save and execute scripts from files. 8. Error Handling: Handle errors gracefully using try-catch blocks. Log errors to files or output them to the console. Improve script robustness by handling potential errors effectively. 9. Advanced Topics (Optional): Remote Management: Use PowerShell to manage remote computers. Modules: Install and use additional modules for specific functionalities. Configuration Management: Use PowerShell for configuration management tasks. PowerShell Desired State Configuration (DSC): Manage and enforce desired configuration of systems. Important Tips for Learning PowerShell: Practice regularly to solidify your understanding. Apply online resources and tutorials for specific tasks. Join the PowerShell community for support and discussions. Start with simple scripts and gradually progress to more complex ones. Don’t hesitate to experiment and discover different features. Mastering PowerShell takes time and practice. By following these tutorials, exploring further resources, and practicing consistently, you can become proficient in using this powerful scripting language for automating tasks and managing your systems effectively. The post What is PowerShell and use cases of PowerShell? appeared first on DevOpsSchool.com. View the full article
-
PowerShell is a text-based scripting tool developed by Microsoft on .NET Common Language Runtime (CLR). It was designed for sysadmins and IT professionals so they can manage their work swiftly. It is more powerful than Command Prompt (CMD), because of its extensive capability to create custom scripts and cmdlets for task automation. PowerShell helps in checking the status of services and processes on your computer and creates automated tasks. It can be embedded into other programs. PowerShell has two modes, one is console and the other is ISE. The PowerShell console helps in managing and manipulating the system by executing built-in commands. While, ISE (Integrated Scripting Environment), helps in writing, testing, and debugging the scripts. Custom scripts are created to install programs, clear the system cache, create or remove users, or launch programs. For instance, PowerShell scripts can help export the titles of 500 videos into text within 10 seconds. Quick Outline: 30 PowerShell Commands Examples Get-Help Get-Process Get-Service Get-Variable Get-Command Show-Command Hostname Get-Clipboard Get-Date Get-ExecutionPolicy Get-History Ping Test-Connection Get-NetIPAddress Clear-History Clear-Host Clear-Content Get-ChildItem Get-Content Get-Item Copy-Item Export-CSV Import-CSV Remove-Item Rename-Item Test-Path Write-Host Write-Output Out-File Format-Table Conclusion 30 PowerShell Commands Examples PowerShell commands are the units of scripting language. They help the system admins perform the recurring tasks. To be good at PowerShell, learn its commands and understand its syntax, how it works, and its aliases. Learning PowerShell commands can make you a pro in it. Let’s have a look at the 30 basic PowerShell commands that are used on a routine by the users with examples. 1. Get-Help The Get-Help command gets help regarding PowerShell commands. A command is placed alongside the Get-Help command to seek help. It displays the name, syntax, alias, and remarks of the specified command. Example: This example will get the helping material of the desired command using the Get-Help command: Get-Help Get-Process First, we placed the Get-Help command. Then placed the command to get helping material related to that command: 2. Get-Process The Get-Process command gets the list of processes on Windows. It displays the process name, id, and CPU usage. It gets all the processes on the computer when executed without parameters. However, the individual process can be retrieved by specifying it to the Get-Process command. Users can specify the process id or name of the process to get information about it. Example: This example will get a single process information using the Get-Process command: Get-Process -Name system According to the above command, first, place the Get-Process command and then specify the process name using the -Name parameter: 3. Get-Service The Get-Service command gets the list of all the services on the system including running, stopped, or suspended. It displays the service status, name, and the DisplayName. Example: This example will get the service information by providing its name to the Get-Service command: Get-Service -Name ALG In the above code, first, the Get-Service command is placed, and then the service name is specified using the -Name parameter: 4. Get-Variable The Get-Variable command gets the variables in the current PowerShell console. It gets variable names and values. It displays all the variables when they are executed without parameters. However, the specified variables can be retrieved by specifying the name of the variable. Example: This example will get a single variable and display its value information in detail using the Get-Variable command: Get-Variable -Name Host -ValueOnly In the above-mentioned code: First, specify the Get-Variable command. Then specify the name of the variable using the -Name parameter. After that, use the -ValueOnly parameter to get the value of the variable in detail: 5. Get-Command The Get-Command command gets the list of all the installed PowerShell commands on Windows. It contains the command types including aliases, functions, and cmdlets. It gets the name, CommandType, version, and source of the commands. Example: This example will get the list of only PowerShell cmdlets installed on the computer using the Get-Command command: Get-Command -CommandType cmdlet According to the above code: First, use the Get-Command command, then specify the command type using the -CommandType parameter: 6. Show-Command The Show-Command command opens the graphical prompt window which contains the list of installed PowerShell commands on the system. Users can scroll this window to see and know about these commands in detail. Example: This example will open the graphical prompt window containing the list of all the commands using the Show-Command command: Show-Command Example: This example will open the graphical prompt window for the specified command using the Show-Command command: Show-Command -Name Invoke-Command In the above-mentioned command: First, use the Show-Command command then specify the command name using the -Name parameter: 7. Hostname The Hostname command gets the DNS (Domain Name System) name of the computer. The hostname is the name specified by the connected network. Example: This example will get the hostname of the computer using the Hostname command: Hostname 8. Get-Clipboard The Get-Clipboard command gets the content copied to the clipboard as text in the PowerShell console. If the content is of multiple lines then it gets the content as an array of strings. Example: This example will get the content copied to the clipboard using the Get-Clipboard command: Get-Clipboard 9. Get-Date The Get-Date command gets the date and time of the computer in the PowerShell console. Various parameters can be with it to get the customized date and time. Example: This example will get the date and time on the computer using PowerShell’s Get-Date command: Get-Date 10. Get-ExecutionPolicy The Get-ExecutionPolicy command gets the execution policies in the PowerShell console. Execution policies are the security policies that determine whether you can load and run the specific script or not on Windows. These execution policies are set by the PowerShell’s Set-ExecutionPolicy command. Example: This example will get the current execution policy on Windows using the Get-ExecutionPolicy command: Get-ExecutionPolicy To learn more about the execution policies read this article. 11. Get-History The Get-History command gets the history of the commands that were executed on the PowerShell console recently in the current session. It is very useful when you want to know what you executed in the current session. Example: This example will get the commands list that were executed in the current session using the Get-History command: Get-History 12. Ping The Ping command tests whether the specified server is accessible or not. To do so, it sends the data packets to that server. If it receives the data packets in return then that server can be contacted. It displays the time consumed during the sending and receiving of the data packets. Example: This example will ping the specified web server and check its availability using the Ping command: ping www.linuxhint.com 13. Test-Connection The Test-Connection command provides the basic information about the computer network such as the computer name, or IP address. It pings the computer network just like the Ping command. It first sends the ICMP echo request and waits for its return. If it returns then that computer can be contacted, else it can be contacted. Example: This example will test the network connection of the provided address using the Test-NetConnection command: Test-Connection www.linuxhint.com 14. Get-NetIPAddress The Get-NetIPAddress command retrieves the IP address information of your computer. It is a network management command that gets the details of both IPv4 and IPv6 protocols. It gets the information of both individual and multiple IP addresses. Example: This example will get the IP address information in detail using the Get-NetIPAddress command: Get-NetIPAddress 15. Clear-History The Clear-History command deletes the history of commands executed in the current session. Its alias is clhy. Executing just its alias will also clear the current session’s history. Example: This example will clear the history of the executed commands in the current PowerShell session using the Clear-History command: Clear-History 16. Clear-Host The Clear-Host command clears all the text including commands and text displayed on the screen. However, it does not clear the history of executed commands. Its standard alias is the cls. Example: This example will clear the text including output commands using the Clear-Host command: Clear-Host 17. Clear-Content The Clear-Content command clears the content from the specified file but does not remove the file. Users need to specify the file to the Clear-Content command to clear its content. Its standard alias is clc. If its standard alias is executed then it does the same job as the Clear-Content command. Example: This example will clear the content of the specified file using the Clear-Content command: Clear-Content -Path C:\Documents\New.txt According to the above code: First, use the Clear-Content command and then specify the file path using the -Path parameter: 18. Get-ChildItem The Get-ChildItem command gets the items and child items from specified locations. A child item is one that is located inside a sub-folder. Example: This example will get the child items from the specified location using the Get-ChildItem command: Get-ChildItem C:\Documents 19. Get-Content The Get-Content command gets the content of a specified text file by the user. It reads the content line by line. Example: This example will get the content of a text file and print it into the PowerShell console using the Get-Content command: Get-Content -Path C:\Documents\New.txt According to the above code: First, use the Get-Content command and then specify the text file path using the -Path parameter: 20. Get-Item The Get-Item command gets the items from the specified location. But, it doesn’t get the item’s content like the Get-Content command does. Example: This example gets all the items in the given locations using the Get-Item command: Get-Item C:\* 21. Copy-Item The Copy-Item command copies the content from one location to another. It has the capability to copy the content from one computer to another. Example: This example will copy a text file using the Copy-Item command: copy-item -Path C:\Documents\New.txt -Destination C:\Documents\Output In the above-mentioned code: First use the Copy-Item command. Then, place the path of the file you want to copy using -Path parameter. After that, use the -Destination parameter and specify the destination path where the file will be copied: 22. Export-CSV The Export-CSV command converts or exports the objects into CSV string values and saves them into the CSV file. Its core function is to export the PowerShell console data into a CSV file. In case, there does not exist a CSV file then it creates it. Example: This example will create and export the data into a CSV file using the Export-CSV command: Get-Process | Export-CSV -Path C:/Documents/New.CSV In accordance with the above-mentioned code: First, place the code or data to be exported into a CSV file, such as a Get-Service command. Then, pipe it to the Export-CSV command. After that use the -Path parameter and specify the CSV file path where the data will be exported: 23. Import-CSV The Import-CSV command imports the content from a CSV file in a table-familiar format. It imports the CSV file data within the PowerShell console. Example: This example will import the content of a CSV file within the PowerShell console using Import-CSV command: Import-CSV -Path C:\Documents\New.CSV In accordance with the above code, to import the content of a CSV file, first, use the Import-CSV command and then specify the CSV file path using the -Path parameter: 24. Remove-Item The Remove-Item command deletes the item from the location specified by the user. It deletes any item in Windows such as files, functions, or folders. Its standard alias is rm, which does the same job when used instead of the Remove-Item command. Example: This example will delete the text file from the specified location using the Remove-Item command: Remove-Item -Path C:\Documents\New.CSV To remove the file, first use the Remove-Item command then specify the file path using the -Path parameter: 25. Rename-Item The Rename-Item command renames the item specified by the user. It changes the name of the file without affecting the data inside the file. It has the capability of renaming one or more files at once. Example: This example will rename the text file using the Rename-Item command: Rename-Item -Path C:\Documents\New.txt -NewName NewName.txt According to the mentioned code: First, place the Rename-Item command. Then, assign the file you want to rename using the -Path parameter. After that, use the -NewName parameter and assign the new name to the file: 26. Test-Path The Test-Path command checks the availability of the specified path in Windows. If the specified exists then PowerShell will return True, if it does not exist then it will return False. It has the ability to check the file, folder, or registry paths. Example: This example will test if the specified path exists or not using the Test-Path command: Test-Path C:\Documents\NewName.txt To test the path, first, use the Test-Path command, then specify the file path: 27. Write-Host The Write-Host command processes the data onto the screen or simply writes and displays it on the screen. Unlike the Echo and Write-Output command has the ability to customize the text, such as coloring the output text. Example: This example will change the text color and background color in PowerShell using the Write-Host command: Write-Host "Hello World" -foregroundcolor white -backgroundcolor red In accordance with the above code: First, use the Write-Host command to enter the text. Then, use the -foregroundcolor parameter and assign the color. After that, use the -backgroundcolor parameter and assign the color: 28. Write-Output The Write-Output command writes the specified objects or text to the pipeline. It can output the content specified to the variable, by just specifying the variable name with it. It outputs the content whatever is specified to it. If there is no pipeline alongside it then it will display the content with the PowerShell console. Example: This example will output the text in the console with the help of Write-Output command: write-output "Hello World" To output the text, first use the Write-Output command and then specify the text: 29. Out-File The Out-File command exports or saves the output of the PowerShell console into a text file specified by the user. The format of the content will be the same as it was in the console. It is a very useful utility to save the information for later use. Example: This demonstration will export the output to the specified text file using the Out-File command: Get-Service | out-file -filepath C:\Documents\NewFile.txt According to the above code: First, use the Get-Process command, or any desired command. There can also be a text. Then, pipe it to the Out-File cmdlet. After that use the -FilePath parameter and specify the text file to save the content inside it: 30. Format-Table The Format-Table command formats the output in the table format. Its standard alias is ft. Alongside displaying multiple values in the table format, it can display the single selective properties as well. Example: This example will format the output of the given command in the table format using Format-Table command: Get-Process | Format-Table -wrap In accordance with the above command: First, use the Get-Service command or any other desired command. Then, pipe it to the Format-Table command. Lastly, use the -wrap parameter to avoid truncation: Conclusion PowerShell commands are the units of scripting language. It helps the system admins perform the recurring tasks swiftly. Learning PowerShell commands and understanding its basics such as its syntax, how it works, and its aliases can make you a pro in it. It has commands like Get-Help, Get-Process, Get-Service, Get-Date, Ping, Get-Clipboard, Clear-History, or Out-File that are used on a routine basis by a standard PowerShell user. All these mentioned commands and more are explained with the help of examples in the above guide. View the full article
-
powershell 30 Basic PowerShell Networking Commands
Linux Hint posted a topic in Development & Programming
PowerShell is a scripting tool used by developers and IT professionals for task automation and configuration management. System administrators create customized scripts for program installation, user management, or file management. Quick Outline: What are Networking Commands in PowerShell What is Computer Networking 30 Basic Powershell Networking Commands Ping nslookup tracert netstat ipconfig GetMac HostName FTP Get-NetRoute Get-NetAdapter Get-NetAdapterHardwareInfo Rename-NetAdapter Restart-NetAdapter Enable-NetAdapter Disable-NetAdapter Get-NetIPInterface Get-NetIPAddress Get-NetConnectionProfile Test-Connection Test-NetConnection Get-NetTCPConnection Get-DnsClient Get-DNSClientCache Clear-DnsClientCache Get-DNSClientServerAddress Set-DnsClientServerAddress Resolve-Dnsname Get-NetFirewallProfile Get-NetNeighbor Get-NetIPConfiguration Conclusion What are Networking Commands in PowerShell? PowerShell has a set of dedicated commands for every task. Similarly, PowerShell has a number of commands for network management. These networking commands perform tasks such as pinging the network, getting IP addresses, enabling or disabling the network adapter, testing a network connection, or clearing the network cache. What is Computer Networking? The term computer networking refers to interconnected computing devices in such a way that they can share resources and data with each other. These computing devices are connected to each other through physical wired cables or using wireless devices. 30 Basic Powershell Networking Commands If you are a networking enthusiast and just started to learn networking then this article is for you. This article will cover the 30 most basic commands that are very useful when it comes to managing the network. All the networking commands will be explained with practical examples. 1. Ping Ping cmdlet checks whether a server is accessible or not. It sends packet information to the server and waits for its return. If the packet data returns then that server is reachable. It cannot be contacted if it does not return the packet information. It then counts and displays the time consumed during sending and receiving packet information. It is like calling a friend on the cell phone and waiting for him to receive it. This is how to ping a website or web server: ping www.linuxhint.com 2. nslookup The nslookup command looks up the DNS and gets the mapping between the IP address and domain name. For instance, the user provides the specific domain address to the nslookup command. In return, the user gets the IP address of that specified domain. Users can do a reverse domain look-up. For that, users need to enter the IP address of the domain and in return, they will get the domain name address. This is how you can look for the domain address: nslookup www.linuxhint.com 3. tracert The tracert command tracks the route through which the IP packet traveled to the destination. It’s like checking the path through which a passenger traveled from one city to another. The tracert command counts the number of hops as well and determines the time each hop took. A hop is referred to as the event at which an IP packet is transferred from one device to another. This is how you can trace the route of a domain: tracert www.linuxhint.com 4. netstat The netstat command determines the network and protocol statistics. It displays all active network connections, TCP and UDP endpoints, ports to which the system is listening, and routing tables. It is the all-in-one command to check all the network activities on Windows. This is how you can check the active network connections statistics: netstat 5. ipconfig The ipconfig command displays the Windows IP configuration. It displays network adapters, IP addresses, subnet masks, DHCP, and DNS information. More importantly, it refreshes the DHCP server and DNS settings This is how you can get the Windows IP configuration: ipconfig 6. GetMac The GetMac command gets the physical MAC address of all the connected network interfaces. This tool is very useful when you need to know each network adapter’s physical Mac address only. This is how you can get the network adapters MAC address: GetMac 7. HostName The hostname command gets the name of the computer that is connected to the network. The hostname is the unique name assigned to the computer that is connected to the network. Hostnames are used to access a computer on the World Wide Web. This is how you can determine the computer hostname: hostname 8. FTP The FTP command transfers the files from the local computer to the remote computer. It transfers files using the TCP network, such as the Internet. It lets you connect to the remote computer from your local computer. This is how you can use the FTP command: FTP 9. Get-NetRoute The Get-NetRoute command gets the IP path or route information with the help of the IP routing table. It gets information like destination network prefixes and the IP address of the next hop. It is like finding a suitable path on the Google map to reach your destination. Here is how you can display the IP route information: Get-NetRoute 10. Get-NetAdapter The Get-NetAdapter command gets the network adapter properties. Such as it displays the name, Mac address, link speed, status, ifIndex, and interface description of the network adapter. It gets the list of network adapters your computer is connected to. This is how you can get the network adapter properties: Get-NetAdapter 11. Get-NetAdapterHardwareInfo The Get-NetAdapterHardwareInfo command gets the network adapter’s hardware information. It gets the list of the network adapters including Wi-Fi, and Ethernet. Furthermore, it gets the segment, bus, PcieLinkSpeed, PcieLinkWidth, and version information of the network adapter’s hardware. Here is how you can get the network adapter’s hardware information: Get-NetAdapterHardwareInfo 12. Rename-NetAdapter The Rename-NetAdapter command renames the network adapter. Yes, the network adapter can be renamed to any desired name. For that purpose, check the mentioned command below. This is how you can rename the network adapter: Rename-NetAdapter -Name "Ethernet 4" -NewName "New Ethernet" According to the above code: First, place the Rename-NetAdapter command. Then, write the existing name of the network adapter using the -Name parameter. After that use the -NewName parameter and specify the new name of the network adapter: 13. Restart-NetAdapter The Restart-NetAdapter command restarts the network adapter. When the network adapter starts to behave unusual, restarting it may help. Here is how you can reboot the network adapter: Restart-NetAdapter -Name "Ethernet 4" According to the above code, first, use the Restart-NetAdapter, then assign the network adapter name using the -Name parameter: 14. Enable-NetAdapter The Enable-NetAdapter command enables the network adapter (Wi-Fi, and Ethernet) if it is found disabled. It is a very useful utility to re-enable the disabled network adapter. A network adapter must be enabled in order to connect the computer to the internet. Here is how you can enable the network adapter: Enable-NetAdapter -Name "Ethernet 4" According to the above code, first, use the Enable-NetAdapter, then specify the name of the network adapter using the -Name parameter: 15. Disable-NetAdapter The Disable-NetAdapter command disables the network adapter such as Wi-Fi, and Ethernet. When a network adapter is disabled, it causes a loss of computer connectivity with the internet. Keep in mind, don’t disable the network adapter that your computer is using to connect to the internet. Here is how you can disable the network adapter: Disable-NetAdapter -Name "Ethernet 4" According to the above code, first, use the Enable-NetAdapter, then specify the name of the network adapter using the -Name parameter: 16. Get-NetIPInterface The Get-NetIPInterface command gets the IP interface of both IPv4 and IPv6 addresses. When this command is executed without parameters, it displays all the IP related configurations and interfaces including loop back and virtual interfaces. This is how you can get the network IP interfaces: Get-NetIPInterface 17. Get-NetIPAddress The Get-NetIPAddress command gets the IP addressing information of your computer. It gets the IP address configurations including IPv4 and IPv6 addresses. Here is how you can get the IP addressing information: Get-NetIPAddress 18. Get-NetConnectionProfile The Get-NetConnectionProfile command gets the network connection profile. It gets the connection profile that is linked to the network adapter. This is how you can get the network connection profile: Get-NetConnectionProfile 19. Test-Connection The Test-Connection command is similar to the ping command. It pings one or more computers by sending the ICMP echo packet requests, and in return gets the echo replies. This is how you can test a local or remote computer connection: Test-Connection www.linuxhint.com 20. Test-NetConnection The Test-NetConnection command displays the diagnostic information about a network connection. It provides information about the network such as RemoteAddress, InterfaceAlias, SourceAddress, PingSucceeded, and PingReplyDetails. This is how you can get the diagnostic information about the network connection: Test-NetConnection 21. Get-NetTCPConnection The Get-NetTCPConnection command gets the current TCP connections. It gets the TCP connection properties including the IP address of local and remote computers, and the connection state. Its core purpose is to check the existing connections to the server. This is how you can test the existing connections to your computer: Get-NetTCPConnection 22. Get-DnsClient The Get-DnsClient command gets the status of the DNS client. It retrieves the details of the network configured on the computer. This is how you can get the status and configuration of the network specified to a computer: Get-DnsClient 23. Get-DNSClientCache The Get-DNSClientCache command gets the contents of the DNS client cache. A DNS client is a temporary storage information that keeps a record of all the recently visited websites. Here is how you can get the client cache of the DNS: Get-DNSClientCache 24. Clear-DnsClientCache The Clear-DnsClientCache command clears the client’s DNS cache. There is no doubt that cache memory helps load web pages faster and enhances the overall web browsing experience. But, clearing the cache keeps you secure by resolving DNS errors. This is how you can clear the client’s DNS cache: Clear-DnsClientCache 25. Get-DNSClientServerAddress The Get-DNSClientServerAddress command gets one or more server IP addresses that are associated with the computer interface. It gets the IP address from the TCP properties on the computer interface. This is how you can get the server IP address on an interface: Get-DNSClientServerAddress 26. Set-DnsClientServerAddress The Set-DnsClientServerAddress command sets one or more IP addresses of DNS servers linked with the computer’s interface. This is how you can set the customized DNS client server address: Set-DnsClientServerAddress -InterfaceAlias "Ethernet/Wi-Fi" -ServerAddresses "2.2.2.2" According to the above code, first, use the Set-DnsClientServerAddress command. Then, use the -InterfaceAlias parameter to assign the computer interface alias, and use the -ServerAddress parameter to assign the server address. 27. Resolve-Dnsname The Resolve-Dnsname command performs the DNS query for the specified name. When a user provides it with the DNS name, then, in return it displays the IP address. This is how you can resolve the DNS name: Resolve-Dnsname www.linuxhint.com 28. Get-NetFirewallProfile The Get-NetFirewallProfile command gets the configuration and status of the specified network firewall profile. Here is how you can check the security status of the computer: Get-NetFirewallProfile 29. Get-NetNeighbor The Get-NetNeighbor command gets the neighbor cache entries. It is like obtaining information from your neighbor and telling it to someone worthy. Here is how you can get the neighbor cache entries: Get-NetNeighbor 30. Get-NetIPConfiguration The Get-NetIPConfiguration command gets the IP network configuration. It gets the IP address, DNS server, and interface of the network. This is how you can get the network IP configuration: Get-NetIPConfiguration Conclusion The Networking term refers to the computers that are interconnected. Network administrators usually have the GUI (Graphical User Interface) for network management. However, network administrators can use the PowerShell to manage the network. To manage the network using PowerShell, administrators must be aware of the networking commands. These commands include ping, tracert, nslookup, Get-NetRoute, or netstat. View the full article -
powershell PowerShell Tutorials for beginners
DevOpsSchool posted a topic in Development & Programming
The post PowerShell Tutorials for beginners appeared first on DevOpsSchool.com. View the full article -
What is Azure PowerShell? Azure PowerShell is a set of cmdlets (command-lets) for managing Azure resources from the PowerShell command line. It provides a comprehensive and powerful toolset for managing Azure resources, including virtual machines, storage accounts, databases, and networking components. Azure PowerShell is widely used by IT professionals to automate tasks, manage complex deployments, and troubleshoot Azure issues. What is cmdlets? Cmdlets, pronounced “command-lets”, are the smallest unit of functionality in PowerShell. They are lightweight commands that are used in the PowerShell environment. Each cmdlet is a .NET Framework class that packages a specific set of functionality. Cmdlets follow a verb-noun naming pattern, such as Get-Help, Get-Process, and Start-Service, which makes them self-descriptive and easy to understand. They are designed to do one thing and do it well, with a consistent interface that makes it easy to chain together in scripts for more complex tasks. Cmdlets can be used to perform operations like managing system processes, reading and writing files, and manipulating data structures. Install Azure PowerShell on Windows 1. Run the following command from PowerShell to determine your PowerShell version: $PSVersionTable.PSVersion 2. Determine if you have the AzureRM PowerShell module installed Get-Module -Name AzureRM -ListAvailable 3. Update to Windows PowerShell 5.1 4. Install .NET Framework 4.7.2 or later 5. Set the PowerShell script execution to remote signed or less restrictive. Check the PowerShell execution policy: Get-ExecutionPolicy -List 6. Set the PowerShell execution policy to remote signed: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser 7. Copy and Paste the following command to install this package using PowerShellGet Install-Module -Name Az or Install-Module -Name Az -Repository PSGallery -Force 8. To update Update-Module -Name Az Install Azure PowerShell on Linux Open the Terminal or other shell host application and run pwsh to start PowerShell. Use the Install-Module cmdlet to install the Az PowerShell module: Install-Module -Name Az -Repository PSGallery -Force PowerShell Commands List Here are 25 basic PowerShell commands: Command nameAliasDescriptionSet-Locationcd, chdir, slSets the current working location to a specified location.Get-Contentcat, gc, typeGets the content of the item at the specified location.Add-ContentacAdds content to the specified items, such as adding words to a file.Set-ContentscWrites or replaces the content in an item with new content.Copy-Itemcopy, cp, cpiCopies an item from one location to another.Remove-Itemdel, erase, rd, ri, rm, rmdirDeletes the specified items.Move-Itemmi, move, mvMoves an item from one location to another.Set-ItemsiChanges the value of an item to the value specified in the command.New-ItemniCreates a new item.Start-JobsajbStarts a Windows PowerShell background job.Compare-Objectcompare, difCompares two sets of objects.Group-ObjectgroupGroups objects that contain the same value for specified properties.Invoke-WebRequestcurl, iwr, wgetGets content from a web page on the Internet.Measure-ObjectmeasureCalculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files …Resolve-PathrvpaResolves the wildcard characters in a path, and displays the path contents.Resume-JobrujbRestarts a suspended jobSet-Variableset, svSets the value of a variable. Creates the variable if one with the requested name does not exist.Show-CommandshcmCreates Windows PowerShell commands in a graphical command window.Sort-ObjectsortSorts objects by property values.Start-ServicesasvStarts one or more stopped services.Start-Processsaps, startStarts one or more processes on the local computer.Suspend-JobsujbTemporarily stops workflow jobs.Wait-JobwjbSuppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are …Where-Object?, whereSelects objects from a collection based on their property values.Write-Outputecho, writeSends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline,… Azure Powershell Commands and Cheat Sheet The post Azure PowerShell Tutorials: Installations and User Guide appeared first on DevOpsSchool.com. View the full article
-
In PowerShell, a cmdlet (command-let) is a small program that performs a specific task or operation. Cmdlets are the basic building blocks of PowerShell scripting, and they are used to manage and automate tasks in the PowerShell environment. Commands, on the other hand, are more general instructions that are typically used to interact with the operating system or applications. Cmdlets are a subset of commands specifically designed for PowerShell, whereas commands can include external programs and scripts not inherently part of the PowerShell environment. Cmdlets: These are lightweight, single-function commands native to PowerShell, built on .NET and designed to be easy to use from the command line. Cmdlets follow a ‘Verb-Noun’ naming convention like Get-Item, Set-Service, etc., and output objects which can be easily piped to other cmdlets. Commands: This is a more general term that can refer to cmdlets, but it also includes other command types in PowerShell such as functions, scripts, aliases, or executable programs. Basically, any operation that you can execute in PowerShell could be considered a command. Here is a table summarizing the key differences between cmdlets and commands in PowerShell: FeatureCmdletsCommandsPurposePerform specific tasks or operationsInteract with the operating system or applicationsStructureConsist of a verb, noun, and parametersConsist of a verb and parameters (optional)OutputTypically return objects that can be piped to other cmdletsTypically return text or error messagesScopeDesigned for managing and automating tasks in PowerShellDesigned for general interaction with the operating system or applications Cmdlets differ from commands in other command-shell environments in the following ways: Cmdlets are instances of .NET Framework classes; they are not stand-alone executables. Cmdlets can be created from as few as a dozen lines of code. Cmdlets do not generally do their own parsing, error presentation, or output formatting. Parsing, error presentation, and output formatting are handled by the Windows PowerShell runtime. Cmdlets process input objects from the pipeline rather than from streams of text, and cmdlets typically deliver objects as output to the pipeline. Cmdlets are record-oriented because they process a single object at a time. Here are some examples of cmdlets: Get-Help Get-Process New-Object Set-Variable Remove-Item Here are some examples of commands: dir cd copy mkdir rm In general, cmdlets are more powerful and flexible than commands. They are also more consistent in their structure and output, making them easier to learn and use. However, commands are still useful for basic tasks and for interacting with applications that do not support cmdlets. The post Difference between between cmdlets and commands in Windows powershell? appeared first on DevOpsSchool.com. View the full article
-
A function is simply a piece of code that contains instructions that can be used to create output from its input. A function can be reused over and over again. The functionality of a function can be enhanced using the “CmdletBinding” attribute. It helps the function to look and operate like a compiled cmdlet in PowerShell. Doing so will provide the function turned into a cmdlet and access to all the cmdlet features. The following post will provide details about the attribute “CmdletBinding”. Learn How PowerShell CmdletBinding Enhances Functions The attribute “CmdletBinding” is utilized to enhance the function. Particularly, the core function of this attribute is to turn the function into an operable cmdlet. Examples explaining the stated attribute are given below. Example 1: Use the “CmdletBinding” Attribute to Transform the String From Upper Case to Lower Case In this example, the “CmdletBinding” attribute will transform the string to lower case: Function String-To-LowerCase { [CmdletBinding()]Param() "THIS IS LINUX HINT PORTAL.".ToLower(); } String-To-LowerCase In the mentioned code above: First, create a function and specify a name for it. Then, create a “Param()” and specify the “[CmdletBinding()]” parameter before it. After that, write a string within inverted quotes and concatenate it with the “ToLower()” method. Lastly, call the function by specifying its name outside the curly braces: Example 2: Use the “CmdletBinding” Attribute in a Function Along With the “-Verbose” Parameter This demonstration will transform the string into lowercase. Moreover, it will display the verbose message with the aid of the “-Verbose” parameter: Function String-To-LowerCase { [CmdletBinding()]Param() Write-Verbose "The -verbose parameter will display the verbose statement." "WELC0ME TO THE CONSOLE.".ToLower(); } String-To-LowerCase -Verbose In the above-stated code: The verbose statement is given using the “Write-Verbose” cmdlet. Then, the function name is specified outside the curly braces along with the “-Verbose” parameter: Example 3: Use the “CmdletBinding” Attribute Along With the “SupportsShouldProcess” and “PSCmdlet” Object This illustration will create a prompt, which will confirm whether to transform the string to upper case or not: Function String-To-LowerCase { [CmdletBinding(SupportsShouldProcess=$True)]Param() Write-Verbose "The -verbose parameter will display the verbose statement." if ($PSCmdlet.ShouldContinue("Confirm?", "Transform string to LowerCase")) { "HELLO WORLD".ToLower(); } Else { "HELLO WORLD" } } In the above-stated code: First, create a function and specify a name. Inside the function, pass the “SupportsShouldProcess=$True” inside the “CmdletBinding()” attribute. After that, create an “if” condition and pass the “$PSCmdlet.ShouldContinue()” parameter inside it. Then, add the text inside the above-stated parameter to be displayed at the time of getting affirmation from the user. The “if” condition will transform the string to lower-case if the user clicks on the “Yes” button else the string case won’t change: Click on the “Yes” button to transform the string into a lowercase: String-To-LowerCase -Confirm It can be observed that the string has been transformed to lower case. Conclusion The “CmdletBinding” attribute in PowerShell is used to convert the function into an operable cmdlet. Doing so will provide access to all cmdlet features to the function turned into a cmdlet. This blog has elaborated on PowerShell’s “CmdletBinding” attribute to enhance the function. View the full article
-
Forum Statistics
63.7k
Total Topics61.7k
Total Posts